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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.93.4  2(raebur    4:7): # $Id: lonnet.pm,v 1.1172.2.93.4.1 2017/06/21 19:55:01 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.1172.2.93.4  2(raebur 1691:7):         my $rep;
                   1692:7):         if ($namespace =~ /^enc/) {
                   1693:7):             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
                   1694:7):         } else {
                   1695:7):             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                   1696:7):         }
1.866     raeburn  1697:         my %returnhash;
1.875     albertel 1698:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1699:             return %returnhash;
                   1700:         }
1.806     raeburn  1701:         my @pairs=split(/\&/,$rep);
                   1702:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1703:             return @pairs;
                   1704:         }
                   1705:         my $i=0;
                   1706:         foreach my $item (@$storearr) {
                   1707:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1708:             $i++;
                   1709:         }
                   1710:         return %returnhash;
                   1711:     } else {
1.880     banghart 1712:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1713:     }
                   1714: }
                   1715: 
                   1716: # -------------------------------------------- put items in domain db files 
                   1717: 
                   1718: sub put_dom {
1.860     raeburn  1719:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1720:     if (!$udom) {
                   1721:         $udom=$env{'user.domain'};
                   1722:         if (defined(&domain($udom,'primary'))) {
                   1723:             $uhome=&domain($udom,'primary');
                   1724:         } else {
1.874     albertel 1725:             undef($uhome);
1.860     raeburn  1726:         }
                   1727:     } else {
                   1728:         if (!$uhome) {
                   1729:             if (defined(&domain($udom,'primary'))) {
                   1730:                 $uhome=&domain($udom,'primary');
                   1731:             }
                   1732:         }
                   1733:     } 
                   1734:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1735:         my $items='';
                   1736:         foreach my $item (keys(%$storehash)) {
                   1737:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1738:         }
                   1739:         $items=~s/\&$//;
1.1172.2.93.4  2(raebur 1740:7):         if ($namespace =~ /^enc/) {
                   1741:7):             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
                   1742:7):         } else {
                   1743:7):             return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1744:7):         }
1.806     raeburn  1745:     } else {
1.860     raeburn  1746:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1747:     }
                   1748: }
                   1749: 
1.1023    raeburn  1750: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1751: sub newput_dom {
1.1023    raeburn  1752:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1753:     my $result;
                   1754:     if (!$udom) {
                   1755:         $udom=$env{'user.domain'};
                   1756:     }
1.1023    raeburn  1757:     if ($udom) {
                   1758:         my $uname = &get_domainconfiguser($udom);
                   1759:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1760:     }
                   1761:     return $result;
                   1762: }
                   1763: 
1.1023    raeburn  1764: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1765: sub del_dom {
1.1023    raeburn  1766:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1767:     if (ref($storearr) eq 'ARRAY') {
                   1768:         if (!$udom) {
                   1769:             $udom=$env{'user.domain'};
                   1770:         }
1.1023    raeburn  1771:         if ($udom) {
                   1772:             my $uname = &get_domainconfiguser($udom); 
                   1773:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1774:         }
                   1775:     }
                   1776: }
                   1777: 
1.1023    raeburn  1778: # ----------------------------------construct domainconfig user for a domain 
                   1779: sub get_domainconfiguser {
                   1780:     my ($udom) = @_;
                   1781:     return $udom.'-domainconfig';
                   1782: }
                   1783: 
1.837     raeburn  1784: sub retrieve_inst_usertypes {
                   1785:     my ($udom) = @_;
                   1786:     my (%returnhash,@order);
1.989     raeburn  1787:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1788:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1789:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44  raeburn  1790:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  1791:     } else {
                   1792:         if (defined(&domain($udom,'primary'))) {
                   1793:             my $uhome=&domain($udom,'primary');
                   1794:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1795:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44  raeburn  1796:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  1797:                 return (\%returnhash,\@order);
                   1798:             }
                   1799:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1800:             my @pairs=split(/\&/,$hashitems);
                   1801:             foreach my $item (@pairs) {
                   1802:                 my ($key,$value)=split(/=/,$item,2);
                   1803:                 $key = &unescape($key);
                   1804:                 next if ($key =~ /^error: 2 /);
                   1805:                 $returnhash{$key}=&thaw_unescape($value);
                   1806:             }
                   1807:             my @esc_order = split(/\&/,$orderitems);
                   1808:             foreach my $item (@esc_order) {
                   1809:                 push(@order,&unescape($item));
                   1810:             }
                   1811:         } else {
1.1172.2.44  raeburn  1812:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  1813:         }
1.1172.2.44  raeburn  1814:         return (\%returnhash,\@order);
1.837     raeburn  1815:     }
                   1816: }
                   1817: 
1.868     raeburn  1818: sub is_domainimage {
                   1819:     my ($url) = @_;
1.1172.2.74  raeburn  1820:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  1821:         if (&domain($1) ne '') {
                   1822:             return '1';
                   1823:         }
                   1824:     }
                   1825:     return;
                   1826: }
                   1827: 
1.899     raeburn  1828: sub inst_directory_query {
                   1829:     my ($srch) = @_;
                   1830:     my $udom = $srch->{'srchdomain'};
                   1831:     my %results;
                   1832:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1833:     my $outcome;
1.899     raeburn  1834:     if ($homeserver ne '') {
1.904     albertel 1835: 	my $queryid=&reply("querysend:instdirsearch:".
                   1836: 			   &escape($srch->{'srchby'}).':'.
                   1837: 			   &escape($srch->{'srchterm'}).':'.
                   1838: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1839: 	my $host=&hostname($homeserver);
                   1840: 	if ($queryid !~/^\Q$host\E\_/) {
1.1172.2.93.4  1(raebur 1841:7): 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 1842: 	    return;
                   1843: 	}
                   1844: 	my $response = &get_query_reply($queryid);
                   1845: 	my $maxtries = 5;
                   1846: 	my $tries = 1;
                   1847: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1848: 	    $response = &get_query_reply($queryid);
                   1849: 	    $tries ++;
                   1850: 	}
                   1851: 
                   1852:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1853:             if ($response eq 'unavailable') {
                   1854:                 $outcome = $response;
                   1855:             } else {
                   1856:                 $outcome = 'ok';
                   1857:                 my @matches = split(/\n/,$response);
                   1858:                 foreach my $match (@matches) {
                   1859:                     my ($key,$value) = split(/=/,$match);
                   1860:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1861:                 }
1.899     raeburn  1862:             }
                   1863:         }
                   1864:     }
1.909     raeburn  1865:     return ($outcome,%results);
1.899     raeburn  1866: }
                   1867: 
                   1868: sub usersearch {
                   1869:     my ($srch) = @_;
                   1870:     my $dom = $srch->{'srchdomain'};
                   1871:     my %results;
                   1872:     my %libserv = &all_library();
                   1873:     my $query = 'usersearch';
                   1874:     foreach my $tryserver (keys(%libserv)) {
                   1875:         if (&host_domain($tryserver) eq $dom) {
                   1876:             my $host=&hostname($tryserver);
                   1877:             my $queryid=
1.911     raeburn  1878:                 &reply("querysend:".&escape($query).':'.
                   1879:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1880:                        &escape($srch->{'srchtype'}).':'.
                   1881:                        &escape($srch->{'srchterm'}),$tryserver);
                   1882:             if ($queryid !~/^\Q$host\E\_/) {
                   1883:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1884:                 next;
1.899     raeburn  1885:             }
                   1886:             my $reply = &get_query_reply($queryid);
                   1887:             my $maxtries = 1;
                   1888:             my $tries = 1;
                   1889:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1890:                 $reply = &get_query_reply($queryid);
                   1891:                 $tries ++;
                   1892:             }
                   1893:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1894:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1895:             } else {
1.911     raeburn  1896:                 my @matches;
                   1897:                 if ($reply =~ /\n/) {
                   1898:                     @matches = split(/\n/,$reply);
                   1899:                 } else {
                   1900:                     @matches = split(/\&/,$reply);
                   1901:                 }
1.899     raeburn  1902:                 foreach my $match (@matches) {
                   1903:                     my ($uname,$udom,%userhash);
1.911     raeburn  1904:                     foreach my $entry (split(/:/,$match)) {
                   1905:                         my ($key,$value) =
                   1906:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1907:                         $userhash{$key} = $value;
                   1908:                         if ($key eq 'username') {
                   1909:                             $uname = $value;
                   1910:                         } elsif ($key eq 'domain') {
                   1911:                             $udom = $value;
1.911     raeburn  1912:                         }
1.899     raeburn  1913:                     }
                   1914:                     $results{$uname.':'.$udom} = \%userhash;
                   1915:                 }
                   1916:             }
                   1917:         }
                   1918:     }
                   1919:     return %results;
                   1920: }
                   1921: 
1.912     raeburn  1922: sub get_instuser {
                   1923:     my ($udom,$uname,$id) = @_;
                   1924:     my $homeserver = &domain($udom,'primary');
                   1925:     my ($outcome,%results);
                   1926:     if ($homeserver ne '') {
                   1927:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1928:                            &escape($id).':'.&escape($udom),$homeserver);
                   1929:         my $host=&hostname($homeserver);
                   1930:         if ($queryid !~/^\Q$host\E\_/) {
                   1931:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1932:             return;
                   1933:         }
                   1934:         my $response = &get_query_reply($queryid);
                   1935:         my $maxtries = 5;
                   1936:         my $tries = 1;
                   1937:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1938:             $response = &get_query_reply($queryid);
                   1939:             $tries ++;
                   1940:         }
                   1941:         if (!&error($response) && $response ne 'refused') {
                   1942:             if ($response eq 'unavailable') {
                   1943:                 $outcome = $response;
                   1944:             } else {
                   1945:                 $outcome = 'ok';
                   1946:                 my @matches = split(/\n/,$response);
                   1947:                 foreach my $match (@matches) {
                   1948:                     my ($key,$value) = split(/=/,$match);
                   1949:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1950:                 }
                   1951:             }
                   1952:         }
                   1953:     }
                   1954:     my %userinfo;
                   1955:     if (ref($results{$uname}) eq 'HASH') {
                   1956:         %userinfo = %{$results{$uname}};
                   1957:     } 
                   1958:     return ($outcome,%userinfo);
                   1959: }
                   1960: 
1.1172.2.69  raeburn  1961: sub get_multiple_instusers {
                   1962:     my ($udom,$users,$caller) = @_;
                   1963:     my ($outcome,$results);
                   1964:     if (ref($users) eq 'HASH') {
                   1965:         my $count = keys(%{$users});
                   1966:         my $requested = &freeze_escape($users);
                   1967:         my $homeserver = &domain($udom,'primary');
                   1968:         if ($homeserver ne '') {
                   1969:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   1970:             my $host=&hostname($homeserver);
                   1971:             if ($queryid !~/^\Q$host\E\_/) {
                   1972:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   1973:                          ' for host: '.$homeserver.'in domain '.$udom);
                   1974:                 return ($outcome,$results);
                   1975:             }
                   1976:             my $response = &get_query_reply($queryid);
                   1977:             my $maxtries = 5;
                   1978:             if ($count > 100) {
                   1979:                 $maxtries = 1+int($count/20);
                   1980:             }
                   1981:             my $tries = 1;
                   1982:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   1983:                 $response = &get_query_reply($queryid);
                   1984:                 $tries ++;
                   1985:             }
                   1986:             if ($response eq '') {
                   1987:                 $results = {};
                   1988:                 foreach my $key (keys(%{$users})) {
                   1989:                     my ($uname,$id);
                   1990:                     if ($caller eq 'id') {
                   1991:                         $id = $key;
                   1992:                     } else {
                   1993:                         $uname = $key;
                   1994:                     }
                   1995:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
                   1996:                     $outcome = $resp;
                   1997:                     if ($resp eq 'ok') {
                   1998:                         %{$results} = (%{$results}, %info);
                   1999:                     } else {
                   2000:                         last;
                   2001:                     }
                   2002:                 }
                   2003:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2004:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2005:                     $outcome = $response;
                   2006:                 } else {
                   2007:                     ($outcome,my $userdata) = split(/=/,$response,2);
                   2008:                     if ($outcome eq 'ok') {
                   2009:                         $results = &thaw_unescape($userdata);
                   2010:                     }
                   2011:                 }
                   2012:             }
                   2013:         }
                   2014:     }
                   2015:     return ($outcome,$results);
                   2016: }
                   2017: 
1.912     raeburn  2018: sub inst_rulecheck {
1.923     raeburn  2019:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2020:     my %returnhash;
                   2021:     if ($udom ne '') {
                   2022:         if (ref($rules) eq 'ARRAY') {
                   2023:             @{$rules} = map {&escape($_);} (@{$rules});
                   2024:             my $rulestr = join(':',@{$rules});
                   2025:             my $homeserver=&domain($udom,'primary');
                   2026:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2027:                 my $response;
                   2028:                 if ($item eq 'username') {                
                   2029:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2030:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2031:                                               $homeserver));
1.923     raeburn  2032:                 } elsif ($item eq 'id') {
                   2033:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2034:                                               ':'.&escape($id).':'.$rulestr,
                   2035:                                               $homeserver));
1.945     raeburn  2036:                 } elsif ($item eq 'selfcreate') {
                   2037:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2038:                                                &escape($udom).':'.&escape($uname).
                   2039:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2040:                 }
1.912     raeburn  2041:                 if ($response ne 'refused') {
                   2042:                     my @pairs=split(/\&/,$response);
                   2043:                     foreach my $item (@pairs) {
                   2044:                         my ($key,$value)=split(/=/,$item,2);
                   2045:                         $key = &unescape($key);
                   2046:                         next if ($key =~ /^error: 2 /);
                   2047:                         $returnhash{$key}=&thaw_unescape($value);
                   2048:                     }
                   2049:                 }
                   2050:             }
                   2051:         }
                   2052:     }
                   2053:     return %returnhash;
                   2054: }
                   2055: 
                   2056: sub inst_userrules {
1.923     raeburn  2057:     my ($udom,$check) = @_;
1.912     raeburn  2058:     my (%ruleshash,@ruleorder);
                   2059:     if ($udom ne '') {
                   2060:         my $homeserver=&domain($udom,'primary');
                   2061:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2062:             my $response;
                   2063:             if ($check eq 'id') {
                   2064:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2065:                                  $homeserver);
1.943     raeburn  2066:             } elsif ($check eq 'email') {
                   2067:                 $response=&reply('instemailrules:'.&escape($udom),
                   2068:                                  $homeserver);
1.923     raeburn  2069:             } else {
                   2070:                 $response=&reply('instuserrules:'.&escape($udom),
                   2071:                                  $homeserver);
                   2072:             }
1.912     raeburn  2073:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2074:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2075:                 ($response ne 'no_such_host')) {
                   2076:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2077:                 my @pairs=split(/\&/,$hashitems);
                   2078:                 foreach my $item (@pairs) {
                   2079:                     my ($key,$value)=split(/=/,$item,2);
                   2080:                     $key = &unescape($key);
                   2081:                     next if ($key =~ /^error: 2 /);
                   2082:                     $ruleshash{$key}=&thaw_unescape($value);
                   2083:                 }
                   2084:                 my @esc_order = split(/\&/,$orderitems);
                   2085:                 foreach my $item (@esc_order) {
                   2086:                     push(@ruleorder,&unescape($item));
                   2087:                 }
                   2088:             }
                   2089:         }
                   2090:     }
                   2091:     return (\%ruleshash,\@ruleorder);
                   2092: }
                   2093: 
1.976     raeburn  2094: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2095: 
                   2096: sub get_domain_defaults {
1.1172.2.35  raeburn  2097:     my ($domain,$ignore_cache) = @_;
                   2098:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2099:     my $cachetime = 60*60*24;
1.1172.2.35  raeburn  2100:     unless ($ignore_cache) {
                   2101:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2102:         if (defined($cached)) {
                   2103:             if (ref($result) eq 'HASH') {
                   2104:                 return %{$result};
                   2105:             }
1.943     raeburn  2106:         }
                   2107:     }
                   2108:     my %domdefaults;
                   2109:     my %domconfig =
1.989     raeburn  2110:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2111:                                   'requestcourses','inststatus',
1.1172.2.9  raeburn  2112:                                   'coursedefaults','usersessions',
1.1172.2.46  raeburn  2113:                                   'requestauthor','selfenrollment',
1.1172.2.89  raeburn  2114:                                   'coursecategories','autoenroll',
                   2115:                                   'helpsettings'],$domain);
1.1172.2.41  raeburn  2116:     my @coursetypes = ('official','unofficial','community','textbook');
1.943     raeburn  2117:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2118:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2119:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2120:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2121:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2122:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2123:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1172.2.91  raeburn  2124:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2125:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2126:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943     raeburn  2127:     } else {
                   2128:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2129:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2130:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2131:     }
1.976     raeburn  2132:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2133:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2134:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2135:         } else {
                   2136:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29  raeburn  2137:         }
1.1172.2.6  raeburn  2138:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2139:         foreach my $item (@usertools) {
                   2140:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2141:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2142:             }
                   2143:         }
1.1172.2.29  raeburn  2144:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2145:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2146:         }
1.976     raeburn  2147:     }
1.985     raeburn  2148:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37  raeburn  2149:         foreach my $item ('official','unofficial','community','textbook') {
1.985     raeburn  2150:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2151:         }
                   2152:     }
1.1172.2.9  raeburn  2153:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2154:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2155:     }
1.989     raeburn  2156:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44  raeburn  2157:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2158:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2159:         }
                   2160:     }
1.1047    raeburn  2161:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60  raeburn  2162:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2163:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2164:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2165:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2166:         }
1.1172.2.41  raeburn  2167:         foreach my $type (@coursetypes) {
                   2168:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2169:                 unless ($type eq 'community') {
                   2170:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2171:                 }
                   2172:             }
                   2173:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2174:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2175:             }
1.1172.2.60  raeburn  2176:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2177:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2178:                     $domdefaults{$type.'postsubtimeout'} =
                   2179:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
                   2180:                 }
                   2181:             }
1.1172.2.30  raeburn  2182:         }
1.1172.2.67  raeburn  2183:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2184:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2185:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2186:                 if (@clonecodes) {
                   2187:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2188:                 }
                   2189:             }
                   2190:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2191:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2192:         }
1.1047    raeburn  2193:     }
1.1073    raeburn  2194:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2195:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2196:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2197:         }
                   2198:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2199:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2200:         }
1.1172.2.62  raeburn  2201:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2202:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2203:         }
1.1073    raeburn  2204:     }
1.1172.2.41  raeburn  2205:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2206:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2207:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2208:                             'approval','limit');
                   2209:             foreach my $type (@coursetypes) {
                   2210:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2211:                     my @mgrdc = ();
                   2212:                     foreach my $item (@settings) {
                   2213:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2214:                             push(@mgrdc,$item);
                   2215:                         }
                   2216:                     }
                   2217:                     if (@mgrdc) {
                   2218:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2219:                     }
                   2220:                 }
                   2221:             }
                   2222:         }
                   2223:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2224:             foreach my $type (@coursetypes) {
                   2225:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2226:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2227:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2228:                     }
                   2229:                 }
                   2230:             }
                   2231:         }
                   2232:     }
1.1172.2.46  raeburn  2233:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2234:         $domdefaults{'catauth'} = 'std';
                   2235:         $domdefaults{'catunauth'} = 'std';
                   2236:         if ($domconfig{'coursecategories'}{'auth'}) {
                   2237:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2238:         }
                   2239:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2240:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2241:         }
                   2242:     }
1.1172.2.76  raeburn  2243:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2244:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2245:     }
1.1172.2.89  raeburn  2246:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2247:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2248:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2249:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2250:         }
                   2251:     }
1.1172.2.23  raeburn  2252:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2253:     return %domdefaults;
                   2254: }
                   2255: 
1.1172.2.93.4  2(raebur 2256:7): sub course_portal_url {
                   2257:7):     my ($cnum,$cdom) = @_;
                   2258:7):     my $chome = &homeserver($cnum,$cdom);
                   2259:7):     my $hostname = &hostname($chome);
                   2260:7):     my $protocol = $protocol{$chome};
                   2261:7):     $protocol = 'http' if ($protocol ne 'https');
                   2262:7):     my %domdefaults = &get_domain_defaults($cdom);
                   2263:7):     my $firsturl;
                   2264:7):     if ($domdefaults{'portal_def'}) {
                   2265:7):         $firsturl = $domdefaults{'portal_def'};
                   2266:7):     } else {
                   2267:7):         $firsturl = $protocol.'://'.$hostname;
                   2268:7):     }
                   2269:7):     return $firsturl;
                   2270:7): }
                   2271:7): 
1.344     www      2272: # --------------------------------------------------- Assign a key to a student
                   2273: 
                   2274: sub assign_access_key {
1.364     www      2275: #
                   2276: # a valid key looks like uname:udom#comments
                   2277: # comments are being appended
                   2278: #
1.498     www      2279:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2280:     $kdom=
1.620     albertel 2281:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2282:     $knum=
1.620     albertel 2283:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2284:     $cdom=
1.620     albertel 2285:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2286:     $cnum=
1.620     albertel 2287:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2288:     $udom=$env{'user.name'} unless (defined($udom));
                   2289:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2290:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2291:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2292:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2293:                                                   # assigned to this person
                   2294:                                                   # - this should not happen,
1.345     www      2295:                                                   # unless something went wrong
                   2296:                                                   # the first time around
                   2297: # ready to assign
1.364     www      2298:         $logentry=$1.'; '.$logentry;
1.496     www      2299:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2300:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2301: # key now belongs to user
1.346     www      2302: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2303:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2304:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2305:                 return 'ok';
                   2306:             } else {
                   2307:                 return 
                   2308:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2309: 	    }
                   2310:         } else {
                   2311:             return 'error: Could not assign key, try again later.';
                   2312:         }
1.364     www      2313:     } elsif (!$existing{$ckey}) {
1.345     www      2314: # the key does not exist
                   2315: 	return 'error: The key does not exist';
                   2316:     } else {
                   2317: # the key is somebody else's
                   2318: 	return 'error: The key is already in use';
                   2319:     }
1.344     www      2320: }
                   2321: 
1.364     www      2322: # ------------------------------------------ put an additional comment on a key
                   2323: 
                   2324: sub comment_access_key {
                   2325: #
                   2326: # a valid key looks like uname:udom#comments
                   2327: # comments are being appended
                   2328: #
                   2329:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2330:     $cdom=
1.620     albertel 2331:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2332:     $cnum=
1.620     albertel 2333:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2334:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2335:     if ($existing{$ckey}) {
                   2336:         $existing{$ckey}.='; '.$logentry;
                   2337: # ready to assign
1.367     www      2338:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2339:                                                  $cdom,$cnum) eq 'ok') {
                   2340: 	    return 'ok';
                   2341:         } else {
                   2342: 	    return 'error: Count not store comment.';
                   2343:         }
                   2344:     } else {
                   2345: # the key does not exist
                   2346: 	return 'error: The key does not exist';
                   2347:     }
                   2348: }
                   2349: 
1.344     www      2350: # ------------------------------------------------------ Generate a set of keys
                   2351: 
                   2352: sub generate_access_keys {
1.364     www      2353:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2354:     $cdom=
1.620     albertel 2355:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2356:     $cnum=
1.620     albertel 2357:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2358:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2359:     unless (($cdom) && ($cnum)) { return 0; }
                   2360:     if ($number>10000) { return 0; }
                   2361:     sleep(2); # make sure don't get same seed twice
                   2362:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2363:     my $total=0;
                   2364:     for (my $i=1;$i<=$number;$i++) {
                   2365:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2366:                   sprintf("%lx",int(100000*rand)).'-'.
                   2367:                   sprintf("%lx",int(100000*rand));
                   2368:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2369:        $newkey=~s/0/h/g; # and also 0 and O
                   2370:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2371:        if ($existing{$newkey}) {
                   2372:            $i--;
                   2373:        } else {
1.364     www      2374: 	  if (&put('accesskeys',
                   2375:               { $newkey => '# generated '.localtime().
1.620     albertel 2376:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2377:                            '; '.$logentry },
                   2378: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2379:               $total++;
                   2380: 	  }
                   2381:        }
                   2382:     }
1.620     albertel 2383:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2384:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2385:     return $total;
                   2386: }
                   2387: 
                   2388: # ------------------------------------------------------- Validate an accesskey
                   2389: 
                   2390: sub validate_access_key {
                   2391:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2392:     $cdom=
1.620     albertel 2393:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2394:     $cnum=
1.620     albertel 2395:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2396:     $udom=$env{'user.domain'} unless (defined($udom));
                   2397:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2398:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2399:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2400: }
                   2401: 
                   2402: # ------------------------------------- Find the section of student in a course
1.652     albertel 2403: sub devalidate_getsection_cache {
                   2404:     my ($udom,$unam,$courseid)=@_;
                   2405:     my $hashid="$udom:$unam:$courseid";
                   2406:     &devalidate_cache_new('getsection',$hashid);
                   2407: }
1.298     matthew  2408: 
1.815     albertel 2409: sub courseid_to_courseurl {
                   2410:     my ($courseid) = @_;
                   2411:     #already url style courseid
                   2412:     return $courseid if ($courseid =~ m{^/});
                   2413: 
                   2414:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2415: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2416: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2417: 	return "/$cdom/$cnum";
                   2418:     }
                   2419: 
                   2420:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2421:     if (exists($courseinfo{'num'})) {
                   2422: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2423:     }
                   2424: 
                   2425:     return undef;
                   2426: }
                   2427: 
1.298     matthew  2428: sub getsection {
                   2429:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2430:     my $cachetime=1800;
1.551     albertel 2431: 
                   2432:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2433:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2434:     if (defined($cached)) { return $result; }
                   2435: 
1.298     matthew  2436:     my %Pending; 
                   2437:     my %Expired;
                   2438:     #
                   2439:     # Each role can either have not started yet (pending), be active, 
                   2440:     #    or have expired.
                   2441:     #
                   2442:     # If there is an active role, we are done.
                   2443:     #
                   2444:     # If there is more than one role which has not started yet, 
                   2445:     #     choose the one which will start sooner
                   2446:     # If there is one role which has not started yet, return it.
                   2447:     #
                   2448:     # If there is more than one expired role, choose the one which ended last.
                   2449:     # If there is a role which has expired, return it.
                   2450:     #
1.815     albertel 2451:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2452:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2453:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2454:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2455:         my $section=$1;
                   2456:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2457:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2458:         my $now=time;
1.548     albertel 2459:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2460:             $Expired{$end}=$section;
                   2461:             next;
                   2462:         }
1.548     albertel 2463:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2464:             $Pending{$start}=$section;
                   2465:             next;
                   2466:         }
1.599     albertel 2467:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2468:     }
                   2469:     #
                   2470:     # Presumedly there will be few matching roles from the above
                   2471:     # loop and the sorting time will be negligible.
                   2472:     if (scalar(keys(%Pending))) {
                   2473:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2474:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2475:     } 
                   2476:     if (scalar(keys(%Expired))) {
                   2477:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2478:         my $time = pop(@sorted);
1.599     albertel 2479:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2480:     }
1.599     albertel 2481:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2482: }
1.70      www      2483: 
1.599     albertel 2484: sub save_cache {
                   2485:     &purge_remembered();
1.722     albertel 2486:     #&Apache::loncommon::validate_page();
1.620     albertel 2487:     undef(%env);
1.780     albertel 2488:     undef($env_loaded);
1.599     albertel 2489: }
1.452     albertel 2490: 
1.599     albertel 2491: my $to_remember=-1;
                   2492: my %remembered;
                   2493: my %accessed;
                   2494: my $kicks=0;
                   2495: my $hits=0;
1.849     albertel 2496: sub make_key {
                   2497:     my ($name,$id) = @_;
1.872     albertel 2498:     if (length($id) > 65 
                   2499: 	&& length(&escape($id)) > 200) {
                   2500: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2501:     }
1.849     albertel 2502:     return &escape($name.':'.$id);
                   2503: }
                   2504: 
1.599     albertel 2505: sub devalidate_cache_new {
                   2506:     my ($name,$id,$debug) = @_;
                   2507:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81  raeburn  2508:     my $remembered_id=$name.':'.$id;
1.849     albertel 2509:     $id=&make_key($name,$id);
1.599     albertel 2510:     $memcache->delete($id);
1.1172.2.81  raeburn  2511:     delete($remembered{$remembered_id});
                   2512:     delete($accessed{$remembered_id});
1.599     albertel 2513: }
                   2514: 
                   2515: sub is_cached_new {
                   2516:     my ($name,$id,$debug) = @_;
1.1172.2.81  raeburn  2517:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for 
                   2518:                                      # keys in %remembered hash, which persists for
                   2519:                                      # duration of request (no restriction on key length).
                   2520:     if (exists($remembered{$remembered_id})) {
                   2521: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2522: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2523: 	$hits++;
1.1172.2.81  raeburn  2524: 	return ($remembered{$remembered_id},1);
1.599     albertel 2525:     }
1.1172.2.81  raeburn  2526:     $id=&make_key($name,$id);
1.599     albertel 2527:     my $value = $memcache->get($id);
                   2528:     if (!(defined($value))) {
                   2529: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2530: 	return (undef,undef);
1.416     albertel 2531:     }
1.599     albertel 2532:     if ($value eq '__undef__') {
                   2533: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2534: 	$value=undef;
                   2535:     }
1.1172.2.81  raeburn  2536:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2537:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2538:     return ($value,1);
                   2539: }
                   2540: 
                   2541: sub do_cache_new {
                   2542:     my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81  raeburn  2543:     my $remembered_id=$name.':'.$id;
1.849     albertel 2544:     $id=&make_key($name,$id);
1.599     albertel 2545:     my $setvalue=$value;
                   2546:     if (!defined($setvalue)) {
                   2547: 	$setvalue='__undef__';
                   2548:     }
1.623     albertel 2549:     if (!defined($time) ) {
                   2550: 	$time=600;
                   2551:     }
1.599     albertel 2552:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2553:     my $result = $memcache->set($id,$setvalue,$time);
                   2554:     if (! $result) {
1.872     albertel 2555: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2556: 	$memcache->disconnect_all();
1.872     albertel 2557:     }
1.600     albertel 2558:     # need to make a copy of $value
1.1172.2.81  raeburn  2559:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2560:     return $value;
                   2561: }
                   2562: 
                   2563: sub make_room {
1.1172.2.81  raeburn  2564:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 2565: 
1.1172.2.81  raeburn  2566:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 2567:                                     : $value;
1.599     albertel 2568:     if ($to_remember<0) { return; }
1.1172.2.81  raeburn  2569:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2570:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2571:     my $to_kick;
                   2572:     my $max_time=0;
                   2573:     foreach my $other (keys(%accessed)) {
                   2574: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2575: 	    $to_kick=$other;
                   2576: 	    $max_time=&tv_interval($accessed{$other});
                   2577: 	}
                   2578:     }
                   2579:     delete($remembered{$to_kick});
                   2580:     delete($accessed{$to_kick});
                   2581:     $kicks++;
                   2582:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2583:     return;
                   2584: }
                   2585: 
1.599     albertel 2586: sub purge_remembered {
1.604     albertel 2587:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2588:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2589:     undef(%remembered);
                   2590:     undef(%accessed);
1.428     albertel 2591: }
1.70      www      2592: # ------------------------------------- Read an entry from a user's environment
                   2593: 
                   2594: sub userenvironment {
                   2595:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2596:     my $items;
                   2597:     foreach my $item (@what) {
                   2598:         $items.=&escape($item).'&';
                   2599:     }
                   2600:     $items=~s/\&$//;
1.70      www      2601:     my %returnhash=();
1.1009    raeburn  2602:     my $uhome = &homeserver($unam,$udom);
                   2603:     unless ($uhome eq 'no_host') {
                   2604:         my @answer=split(/\&/, 
                   2605:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2606:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2607:             return %returnhash;
                   2608:         }
1.1009    raeburn  2609:         my $i;
                   2610:         for ($i=0;$i<=$#what;$i++) {
                   2611: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2612:         }
1.70      www      2613:     }
                   2614:     return %returnhash;
1.1       albertel 2615: }
                   2616: 
1.617     albertel 2617: # ---------------------------------------------------------- Get a studentphoto
                   2618: sub studentphoto {
                   2619:     my ($udom,$unam,$ext) = @_;
                   2620:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2621:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2622:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2623:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2624:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2625:             } else {
                   2626:                 my ($result,$perm_reqd)=
1.707     albertel 2627: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2628:                 if ($result eq 'ok') {
                   2629:                     if (!($perm_reqd eq 'yes')) {
                   2630:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2631:                     }
                   2632:                 }
                   2633:             }
                   2634:         }
                   2635:     } else {
                   2636:         my ($result,$perm_reqd) = 
1.707     albertel 2637: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2638:         if ($result eq 'ok') {
                   2639:             if (!($perm_reqd eq 'yes')) {
                   2640:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2641:             }
                   2642:         }
                   2643:     }
                   2644:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2645: }
                   2646: 
                   2647: sub retrievestudentphoto {
                   2648:     my ($udom,$unam,$ext,$type) = @_;
                   2649:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2650:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2651:     if ($ret eq 'ok') {
                   2652:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2653:         if ($type eq 'thumbnail') {
                   2654:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2655:         }
                   2656:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2657:         return $tokenurl;
                   2658:     } else {
                   2659:         if ($type eq 'thumbnail') {
                   2660:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2661:         } else { 
                   2662:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2663:         }
1.617     albertel 2664:     }
                   2665: }
                   2666: 
1.263     www      2667: # -------------------------------------------------------------------- New chat
                   2668: 
                   2669: sub chatsend {
1.724     raeburn  2670:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2671:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2672:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2673:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2674:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2675: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2676: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2677: }
                   2678: 
                   2679: # ------------------------------------------ Find current version of a resource
                   2680: 
                   2681: sub getversion {
                   2682:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  2683:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2684:     return &currentversion(&filelocation('',$fname));
                   2685: }
                   2686: 
                   2687: sub currentversion {
                   2688:     my $fname=shift;
                   2689:     my $author=$fname;
                   2690:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2691:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2692:     my $home=&homeserver($uname,$udom);
1.292     www      2693:     if ($home eq 'no_host') { 
                   2694:         return -1; 
                   2695:     }
1.1112    www      2696:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2697:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2698: 	return -1;
                   2699:     }
1.1112    www      2700:     return $answer;
1.263     www      2701: }
                   2702: 
1.1111    www      2703: #
                   2704: # Return special version number of resource if set by override, empty otherwise
                   2705: #
                   2706: sub usedversion {
                   2707:     my $fname=shift;
                   2708:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2709:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2710:     if ($urlversion) { return $urlversion; }
                   2711:     return '';
                   2712: }
                   2713: 
1.1       albertel 2714: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2715: 
1.1       albertel 2716: sub subscribe {
                   2717:     my $fname=shift;
1.761     raeburn  2718:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2719:     $fname=~s/[\n\r]//g;
1.1       albertel 2720:     my $author=$fname;
                   2721:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2722:     my ($udom,$uname)=split(/\//,$author);
                   2723:     my $home=homeserver($uname,$udom);
1.335     albertel 2724:     if ($home eq 'no_host') {
                   2725:         return 'not_found';
1.1       albertel 2726:     }
                   2727:     my $answer=reply("sub:$fname",$home);
1.64      www      2728:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2729: 	$answer.=' by '.$home;
                   2730:     }
1.1       albertel 2731:     return $answer;
                   2732: }
                   2733:     
1.8       www      2734: # -------------------------------------------------------------- Replicate file
                   2735: 
                   2736: sub repcopy {
                   2737:     my $filename=shift;
1.23      www      2738:     $filename=~s/\/+/\//g;
1.1142    raeburn  2739:     my $londocroot = $perlvar{'lonDocRoot'};
                   2740:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2741:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2742:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2743: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2744: 	return &repcopy_userfile($filename);
                   2745:     }
1.532     albertel 2746:     $filename=~s/[\n\r]//g;
1.8       www      2747:     my $transname="$filename.in.transfer";
1.828     www      2748: # FIXME: this should flock
1.607     raeburn  2749:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2750:     my $remoteurl=subscribe($filename);
1.64      www      2751:     if ($remoteurl =~ /^con_lost by/) {
                   2752: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2753:            return 'unavailable';
1.8       www      2754:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2755: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2756: 	   return 'not_found';
1.64      www      2757:     } elsif ($remoteurl =~ /^rejected by/) {
                   2758: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2759:            return 'forbidden';
1.20      www      2760:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2761:            return 'ok';
1.8       www      2762:     } else {
1.290     www      2763:         my $author=$filename;
                   2764:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2765:         my ($udom,$uname)=split(/\//,$author);
                   2766:         my $home=homeserver($uname,$udom);
                   2767:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2768:            my @parts=split(/\//,$filename);
                   2769:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2770:            if ($path ne "$londocroot/res") {
1.8       www      2771:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2772: 	       return 'bad_request';
1.8       www      2773:            }
                   2774:            my $count;
                   2775:            for ($count=5;$count<$#parts;$count++) {
                   2776:                $path.="/$parts[$count]";
                   2777:                if ((-e $path)!=1) {
                   2778: 		   mkdir($path,0777);
                   2779:                }
                   2780:            }
                   2781:            my $ua=new LWP::UserAgent;
                   2782:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2783:            my $response=$ua->request($request,$transname);
                   2784:            if ($response->is_error()) {
                   2785: 	       unlink($transname);
                   2786:                my $message=$response->status_line;
1.672     albertel 2787:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2788:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2789:                return 'unavailable';
1.8       www      2790:            } else {
1.16      www      2791: 	       if ($remoteurl!~/\.meta$/) {
                   2792:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2793:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2794:                   if ($mresponse->is_error()) {
                   2795: 		      unlink($filename.'.meta');
                   2796:                       &logthis(
1.672     albertel 2797:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2798:                   }
                   2799: 	       }
1.8       www      2800:                rename($transname,$filename);
1.607     raeburn  2801:                return 'ok';
1.8       www      2802:            }
1.290     www      2803:        }
1.8       www      2804:     }
1.330     www      2805: }
                   2806: 
                   2807: # ------------------------------------------------ Get server side include body
                   2808: sub ssi_body {
1.381     albertel 2809:     my ($filelink,%form)=@_;
1.606     matthew  2810:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2811:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2812:     }
1.953     www      2813:     my $output='';
                   2814:     my $response;
1.980     raeburn  2815:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2816:        ($output,$response)=&externalssi($filelink);
1.953     www      2817:     } else {
1.1004    droeschl 2818:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2819:        $filelink .= 'inhibitmenu=yes';
1.953     www      2820:        ($output,$response)=&ssi($filelink,%form);
                   2821:     }
1.778     albertel 2822:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2823:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2824:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2825:     if (wantarray) {
                   2826:         return ($output, $response);
                   2827:     } else {
                   2828:         return $output;
                   2829:     }
1.8       www      2830: }
                   2831: 
1.15      www      2832: # --------------------------------------------------------- Server Side Include
                   2833: 
1.782     albertel 2834: sub absolute_url {
                   2835:     my ($host_name) = @_;
                   2836:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2837:     if ($host_name eq '') {
                   2838: 	$host_name = $ENV{'SERVER_NAME'};
                   2839:     }
                   2840:     return $protocol.$host_name;
                   2841: }
                   2842: 
1.942     foxr     2843: #
                   2844: #   Server side include.
                   2845: # Parameters:
                   2846: #  fn     Possibly encrypted resource name/id.
                   2847: #  form   Hash that describes how the rendering should be done
                   2848: #         and other things.
1.944     foxr     2849: # Returns:
1.950     raeburn  2850: #   Scalar context: The content of the response.
                   2851: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2852: #     
1.15      www      2853: sub ssi {
                   2854: 
1.944     foxr     2855:     my ($fn,%form)=@_;
1.15      www      2856:     my $ua=new LWP::UserAgent;
1.23      www      2857:     my $request;
1.711     albertel 2858: 
                   2859:     $form{'no_update_last_known'}=1;
1.895     albertel 2860:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2861:     if (%form) {
1.782     albertel 2862:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1172.2.58  raeburn  2863:       $request->content(join('&',map {
                   2864:             my $name = escape($_);
                   2865:             "$name=" . ( ref($form{$_}) eq 'ARRAY'
                   2866:             ? join("&$name=", map {escape($_) } @{$form{$_}})
                   2867:             : &escape($form{$_}) );
                   2868:         } keys(%form)));
1.23      www      2869:     } else {
1.782     albertel 2870:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2871:     }
                   2872: 
1.15      www      2873:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.2  raeburn  2874:     my $response= $ua->request($request);
1.944     foxr     2875:     if (wantarray) {
1.1172.2.3  raeburn  2876: 	return ($response->content, $response);
1.944     foxr     2877:     } else {
1.1172.2.3  raeburn  2878: 	return $response->content;
1.942     foxr     2879:     }
1.324     www      2880: }
                   2881: 
                   2882: sub externalssi {
                   2883:     my ($url)=@_;
                   2884:     my $ua=new LWP::UserAgent;
                   2885:     my $request=new HTTP::Request('GET',$url);
                   2886:     my $response=$ua->request($request);
1.954     raeburn  2887:     if (wantarray) {
                   2888:         return ($response->content, $response);
                   2889:     } else {
                   2890:         return $response->content;
                   2891:     }
1.15      www      2892: }
1.254     www      2893: 
1.492     albertel 2894: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2895: 
                   2896: sub allowuploaded {
                   2897:     my ($srcurl,$url)=@_;
                   2898:     $url=&clutter(&declutter($url));
                   2899:     my $dir=$url;
                   2900:     $dir=~s/\/[^\/]+$//;
                   2901:     my %httpref=();
                   2902:     my $httpurl=&hreflocation('',$url);
                   2903:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2904:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2905: }
1.477     raeburn  2906: 
1.1172.2.13  raeburn  2907: #
                   2908: # Determine if the current user should be able to edit a particular resource,
                   2909: # when viewing in course context.
                   2910: # (a) When viewing resource used to determine if "Edit" item is included in
                   2911: #     Functions.
                   2912: # (b) When displaying folder contents in course editor, used to determine if
                   2913: #     "Edit" link will be displayed alongside resource.
                   2914: #
                   2915: #  input: six args -- filename (decluttered), course number, course domain,
                   2916: #                   url, symb (if registered) and group (if this is a group
                   2917: #                   item -- e.g., bulletin board, group page etc.).
                   2918: #  output: array of five scalars --
                   2919: #          $cfile -- url for file editing if editable on current server
                   2920: #          $home -- homeserver of resource (i.e., for author if published,
                   2921: #                                           or course if uploaded.).
                   2922: #          $switchserver --  1 if server switch will be needed.
                   2923: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   2924: #          $forceview -- 1 if icon/link should be to go to view mode
                   2925: #
                   2926: 
                   2927: sub can_edit_resource {
                   2928:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   2929:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   2930: #
                   2931: # For aboutme pages user can only edit his/her own.
                   2932: #
                   2933:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   2934:         my ($sdom,$sname) = ($1,$2);
                   2935:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   2936:             $home = $env{'user.home'};
                   2937:             $cfile = $resurl;
                   2938:             if ($env{'form.forceedit'}) {
                   2939:                 $forceview = 1;
                   2940:             } else {
                   2941:                 $forceedit = 1;
                   2942:             }
                   2943:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   2944:         } else {
                   2945:             return;
                   2946:         }
                   2947:     }
                   2948: 
                   2949:     if ($env{'request.course.id'}) {
                   2950:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   2951:         if ($group ne '') {
                   2952: # if this is a group homepage or group bulletin board, check group privs
                   2953:             my $allowed = 0;
                   2954:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   2955:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   2956:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   2957:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   2958:                     $allowed = 1;
                   2959:                 }
                   2960:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   2961:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   2962:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   2963:                     $allowed = 1;
                   2964:                 }
                   2965:             }
                   2966:             if ($allowed) {
                   2967:                 $home=&homeserver($cnum,$cdom);
                   2968:                 if ($env{'form.forceedit'}) {
                   2969:                     $forceview = 1;
                   2970:                 } else {
                   2971:                     $forceedit = 1;
                   2972:                 }
                   2973:                 $cfile = $resurl;
                   2974:             } else {
                   2975:                 return;
                   2976:             }
                   2977:         } else {
1.1172.2.15  raeburn  2978:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2979:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   2980:                     return;
                   2981:                 }
                   2982:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  2983: #
                   2984: # No edit allowed where CC has switched to student role.
                   2985: #
                   2986:                 return;
                   2987:             }
                   2988:         }
                   2989:     }
                   2990: 
                   2991:     if ($file ne '') {
                   2992:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   2993:             if (&is_course_upload($file,$cnum,$cdom)) {
                   2994:                 $uploaded = 1;
                   2995:                 $incourse = 1;
                   2996:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   2997:                     $cfile = &hreflocation('',$file);
                   2998:                     if ($env{'form.forceedit'}) {
                   2999:                         $forceview = 1;
                   3000:                     } else {
                   3001:                         $forceedit = 1;
                   3002:                     }
                   3003:                 }
                   3004:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3005:                 $incourse = 1;
                   3006:                 if ($env{'form.forceedit'}) {
                   3007:                     $forceview = 1;
                   3008:                 } else {
                   3009:                     $forceedit = 1;
                   3010:                 }
                   3011:                 $cfile = $resurl;
                   3012:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   3013:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3014:                     $incourse = 1;
                   3015:                     if ($env{'form.forceedit'}) {
                   3016:                         $forceview = 1;
                   3017:                     } else {
                   3018:                         $forceedit = 1;
                   3019:                     }
                   3020:                     $cfile = $resurl;
                   3021:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   3022:                     $incourse = 1;
                   3023:                     $cfile = $resurl.'/smpedit';
                   3024:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   3025:                     $incourse = 1;
                   3026:                     if ($env{'form.forceedit'}) {
                   3027:                         $forceview = 1;
                   3028:                     } else {
                   3029:                         $forceedit = 1;
                   3030:                     }
                   3031:                     $cfile = $resurl;
1.1172.2.93.4  2(raebur 3032:7):                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   3033:7):                     $incourse = 1;
                   3034:7):                     if ($env{'form.forceedit'}) {
                   3035:7):                         $forceview = 1;
                   3036:7):                     } else {
                   3037:7):                         $forceedit = 1;
                   3038:7):                     }
                   3039:7):                     $cfile = $resurl;
1.1172.2.15  raeburn  3040:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3041:                     $incourse = 1;
                   3042:                     if ($env{'form.forceedit'}) {
                   3043:                         $forceview = 1;
                   3044:                     } else {
                   3045:                         $forceedit = 1;
                   3046:                     }
                   3047:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3048:                 }
                   3049:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3050:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3051:                 if (&is_on_map($template)) {
                   3052:                     $incourse = 1;
                   3053:                     $forceview = 1;
                   3054:                     $cfile = $template;
                   3055:                 }
                   3056:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3057:                     $incourse = 1;
                   3058:                     if ($env{'form.forceedit'}) {
                   3059:                         $forceview = 1;
                   3060:                     } else {
                   3061:                         $forceedit = 1;
                   3062:                     }
                   3063:                     $cfile = $resurl;
1.1172.2.93.4  2(raebur 3064:7):             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3065:7):                 $incourse = 1;
                   3066:7):                 if ($env{'form.forceedit'}) {
                   3067:7):                     $forceview = 1;
                   3068:7):                 } else {
                   3069:7):                     $forceedit = 1;
                   3070:7):                 }
                   3071:7):                 $cfile = $resurl;
1.1172.2.13  raeburn  3072:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3073:                 $incourse = 1;
                   3074:                 $forceview = 1;
                   3075:                 if ($symb) {
                   3076:                     my ($map,$id,$res)=&decode_symb($symb);
                   3077:                     $env{'request.symb'} = $symb;
                   3078:                     $cfile = &clutter($res);
                   3079:                 } else {
                   3080:                     $cfile = $env{'form.suppurl'};
1.1172.2.93.4  1(raebur 3081:7):                     my $escfile = &unescape($cfile);
          2(raebur 3082:7):                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   3083:7):                         $cfile = '/adm/wrapper'.$escfile;
                   3084:7):                     } else {
                   3085:7):                         $escfile =~ s{^http://}{};
                   3086:7):                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3087:7):                     }
1.1172.2.13  raeburn  3088:                 }
1.1172.2.31  raeburn  3089:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3090:                 if ($env{'form.forceedit'}) {
                   3091:                     $forceview = 1;
                   3092:                 } else {
                   3093:                     $forceedit = 1;
                   3094:                 }
                   3095:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3096:             }
                   3097:         }
                   3098:         if ($uploaded || $incourse) {
                   3099:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  3100:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  3101:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3102:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3103:             # Check that the user has permission to edit this resource
                   3104:             my $setpriv = 1;
                   3105:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3106:             if (defined($cfudom)) {
                   3107:                 $home=&homeserver($cfuname,$cfudom);
                   3108:                 $cfile=$file;
                   3109:             }
                   3110:         }
                   3111:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   3112:             (($home ne '') && ($home ne 'no_host'))) {
                   3113:             my @ids=&current_machine_ids();
                   3114:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3115:                 $switchserver=1;
                   3116:             }
                   3117:         }
                   3118:     }
                   3119:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3120: }
                   3121: 
                   3122: sub is_course_upload {
                   3123:     my ($file,$cnum,$cdom) = @_;
                   3124:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3125:     $uploadpath =~ s{^\/}{};
                   3126:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3127:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   3128:         return 1;
                   3129:     }
                   3130:     return;
                   3131: }
                   3132: 
                   3133: sub in_course {
                   3134:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3135:     if ($hideprivileged) {
                   3136:         my $skipuser;
1.1172.2.23  raeburn  3137:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3138:         my @possdoms = ($cdom);
                   3139:         if ($coursehash{'checkforpriv'}) {
                   3140:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   3141:         }
                   3142:         if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13  raeburn  3143:             $skipuser = 1;
                   3144:             if ($coursehash{'nothideprivileged'}) {
                   3145:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3146:                     my $user;
                   3147:                     if ($item =~ /:/) {
                   3148:                         $user = $item;
                   3149:                     } else {
                   3150:                         $user = join(':',split(/[\@]/,$item));
                   3151:                     }
                   3152:                     if ($user eq $uname.':'.$udom) {
                   3153:                         undef($skipuser);
                   3154:                         last;
                   3155:                     }
                   3156:                 }
                   3157:             }
                   3158:             if ($skipuser) {
                   3159:                 return 0;
                   3160:             }
                   3161:         }
                   3162:     }
                   3163:     $type ||= 'any';
                   3164:     if (!defined($cdom) || !defined($cnum)) {
                   3165:         my $cid  = $env{'request.course.id'};
                   3166:         $cdom = $env{'course.'.$cid.'.domain'};
                   3167:         $cnum = $env{'course.'.$cid.'.num'};
                   3168:     }
                   3169:     my $typesref;
                   3170:     if (($type eq 'any') || ($type eq 'all')) {
                   3171:         $typesref = ['active','previous','future'];
                   3172:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3173:         $typesref = [$type];
                   3174:     }
                   3175:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3176:                               $typesref,undef,[$cdom]);
                   3177:     my ($tmp) = keys(%roles);
                   3178:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3179:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3180:     if (@course_roles > 0) {
                   3181:         return 1;
                   3182:     }
                   3183:     return 0;
                   3184: }
                   3185: 
1.478     albertel 3186: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3187: # input: action, courseID, current domain, intended
1.637     raeburn  3188: #        path to file, source of file, instruction to parse file for objects,
                   3189: #        ref to hash for embedded objects,
                   3190: #        ref to hash for codebase of java objects.
1.1095    raeburn  3191: #        reference to scalar to accommodate mime type determined
                   3192: #          from File::MMagic if $parser = parse.
1.637     raeburn  3193: #
1.485     raeburn  3194: # output: url to file (if action was uploaddoc), 
                   3195: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3196: #
1.478     albertel 3197: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3198: # course.
1.477     raeburn  3199: #
1.478     albertel 3200: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3201: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3202: #          course's home server.
1.477     raeburn  3203: #
1.478     albertel 3204: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3205: #          be copied from $source (current location) to 
                   3206: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3207: #         and will then be copied to
                   3208: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3209: #         course's home server.
1.485     raeburn  3210: #
1.481     raeburn  3211: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3212: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3213: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3214: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3215: #         in course's home server.
1.637     raeburn  3216: #
1.477     raeburn  3217: 
                   3218: sub process_coursefile {
1.1095    raeburn  3219:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3220:         $mimetype)=@_;
1.477     raeburn  3221:     my $fetchresult;
1.638     albertel 3222:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3223:     if ($action eq 'propagate') {
1.638     albertel 3224:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3225: 			     $home);
1.481     raeburn  3226:     } else {
1.477     raeburn  3227:         my $fpath = '';
                   3228:         my $fname = $file;
1.478     albertel 3229:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3230:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3231:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3232:         if ($action eq 'copy') {
                   3233:             if ($source eq '') {
                   3234:                 $fetchresult = 'no source file';
                   3235:                 return $fetchresult;
                   3236:             } else {
                   3237:                 my $destination = $filepath.'/'.$fname;
                   3238:                 rename($source,$destination);
                   3239:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3240:                                  $home);
1.481     raeburn  3241:             }
                   3242:         } elsif ($action eq 'uploaddoc') {
                   3243:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 3244:             print $fh $env{'form.'.$source};
1.481     raeburn  3245:             close($fh);
1.637     raeburn  3246:             if ($parser eq 'parse') {
1.1024    raeburn  3247:                 my $mm = new File::MMagic;
1.1095    raeburn  3248:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3249:                 if ($type eq 'text/html') {
1.1024    raeburn  3250:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3251:                     unless ($parse_result eq 'ok') {
                   3252:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3253:                     }
1.637     raeburn  3254:                 }
1.1095    raeburn  3255:                 if (ref($mimetype)) {
                   3256:                     $$mimetype = $type;
                   3257:                 } 
1.637     raeburn  3258:             }
1.477     raeburn  3259:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3260:                                  $home);
1.481     raeburn  3261:             if ($fetchresult eq 'ok') {
                   3262:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3263:             } else {
                   3264:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3265:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3266:                 return '/adm/notfound.html';
                   3267:             }
1.477     raeburn  3268:         }
                   3269:     }
1.485     raeburn  3270:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3271:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3272:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3273:     }
                   3274:     return $fetchresult;
                   3275: }
                   3276: 
1.637     raeburn  3277: sub build_filepath {
                   3278:     my ($fpath) = @_;
                   3279:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3280:     unless ($fpath eq '') {
                   3281:         my @parts=split('/',$fpath);
                   3282:         foreach my $part (@parts) {
                   3283:             $filepath.= '/'.$part;
                   3284:             if ((-e $filepath)!=1) {
                   3285:                 mkdir($filepath,0777);
                   3286:             }
                   3287:         }
                   3288:     }
                   3289:     return $filepath;
                   3290: }
                   3291: 
                   3292: sub store_edited_file {
1.638     albertel 3293:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3294:     my $file = $primary_url;
                   3295:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3296:     my $fpath = '';
                   3297:     my $fname = $file;
                   3298:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3299:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3300:     my $filepath = &build_filepath($fpath);
                   3301:     open(my $fh,'>'.$filepath.'/'.$fname);
                   3302:     print $fh $content;
                   3303:     close($fh);
1.638     albertel 3304:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3305:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3306: 			  $home);
1.637     raeburn  3307:     if ($$fetchresult eq 'ok') {
                   3308:         return '/uploaded/'.$fpath.'/'.$fname;
                   3309:     } else {
1.638     albertel 3310:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3311: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3312:         return '/adm/notfound.html';
                   3313:     }
                   3314: }
                   3315: 
1.531     albertel 3316: sub clean_filename {
1.831     albertel 3317:     my ($fname,$args)=@_;
1.315     www      3318: # Replace Windows backslashes by forward slashes
1.257     www      3319:     $fname=~s/\\/\//g;
1.831     albertel 3320:     if (!$args->{'keep_path'}) {
                   3321:         # Get rid of everything but the actual filename
                   3322: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3323:     }
1.315     www      3324: # Replace spaces by underscores
                   3325:     $fname=~s/\s+/\_/g;
                   3326: # Replace all other weird characters by nothing
1.831     albertel 3327:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3328: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3329: # numbers
                   3330:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3331:     return $fname;
                   3332: }
1.1051    raeburn  3333: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3334: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3335: # image with the same aspect ratio as the original, but with dimensions which do 
                   3336: # not exceed $resizewidth and $resizeheight.
                   3337:  
1.984     neumanie 3338: sub resizeImage {
1.1051    raeburn  3339:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3340:     my $ima = Image::Magick->new;
                   3341:     my $resized;
                   3342:     if (-e $img_path) {
                   3343:         $ima->Read($img_path);
                   3344:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3345:             my $width = $ima->Get('width');
                   3346:             my $height = $ima->Get('height');
                   3347:             if ($width > $resizewidth) {
                   3348: 	        my $factor = $width/$resizewidth;
                   3349:                 my $newheight = $height/$factor;
                   3350:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3351:                 $resized = 1;
                   3352:             }
                   3353:         }
                   3354:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3355:             my $width = $ima->Get('width');
                   3356:             my $height = $ima->Get('height');
                   3357:             if ($height > $resizeheight) {
                   3358:                 my $factor = $height/$resizeheight;
                   3359:                 my $newwidth = $width/$factor;
                   3360:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3361:                 $resized = 1;
                   3362:             }
                   3363:         }
                   3364:         if ($resized) {
                   3365:             $ima->Write($img_path);
                   3366:         }
                   3367:     }
                   3368:     return;
1.977     amueller 3369: }
                   3370: 
1.608     albertel 3371: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3372: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3373: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3374: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3375: #                                    canceloverwrite, or ''. 
                   3376: #                   if 'coursedoc': upload to the current course
                   3377: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3378: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3379: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3380: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3381: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3382: #        $allfiles - reference to hash for embedded objects
                   3383: #        $codebase - reference to hash for codebase of java objects
                   3384: #        $desuname - username for permanent storage of uploaded file
                   3385: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3386: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3387: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3388: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3389: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3390: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3391: #                    from File::MMagic.
1.858     raeburn  3392: # 
1.686     albertel 3393: # output: url of file in userspace, or error: <message> 
                   3394: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3395: 
1.531     albertel 3396: sub userfileupload {
1.1090    raeburn  3397:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3398:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3399:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3400:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3401:     $fname=&clean_filename($fname);
1.1090    raeburn  3402:     # See if there is anything left
1.257     www      3403:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3404:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3405:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3406:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3407:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3408:         my $now = time;
1.1090    raeburn  3409:         my $filepath;
1.1095    raeburn  3410:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3411:              $filepath = 'tmp/helprequests/'.$now;
                   3412:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3413:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3414:                          '_'.$env{'user.domain'}.'/pending';
                   3415:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3416:             my ($docuname,$docudom);
                   3417:             if ($destudom) {
                   3418:                 $docudom = $destudom;
                   3419:             } else {
                   3420:                 $docudom = $env{'user.domain'};
                   3421:             }
                   3422:             if ($destuname) {
                   3423:                 $docuname = $destuname;
                   3424:             } else {
                   3425:                 $docuname = $env{'user.name'};
                   3426:             }
                   3427:             if (exists($env{'form.group'})) {
                   3428:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3429:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3430:             }
                   3431:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3432:             if ($context eq 'canceloverwrite') {
                   3433:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3434:                 if (-e  $tempfile) {
                   3435:                     my @info = stat($tempfile);
                   3436:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3437:                         unlink($tempfile);
                   3438:                     }
                   3439:                 }
                   3440:                 return;
1.523     raeburn  3441:             }
                   3442:         }
1.1090    raeburn  3443:         # Create the directory if not present
1.741     raeburn  3444:         my @parts=split(/\//,$filepath);
                   3445:         my $fullpath = $perlvar{'lonDaemons'};
                   3446:         for (my $i=0;$i<@parts;$i++) {
                   3447:             $fullpath .= '/'.$parts[$i];
                   3448:             if ((-e $fullpath)!=1) {
                   3449:                 mkdir($fullpath,0777);
                   3450:             }
                   3451:         }
                   3452:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   3453:         print $fh $env{'form.'.$formname};
                   3454:         close($fh);
1.1090    raeburn  3455:         if ($context eq 'existingfile') {
                   3456:             my @info = stat($fullpath.'/'.$fname);
                   3457:             return ($fullpath.'/'.$fname,$info[9]);
                   3458:         } else {
                   3459:             return $fullpath.'/'.$fname;
                   3460:         }
1.523     raeburn  3461:     }
1.995     raeburn  3462:     if ($subdir eq 'scantron') {
                   3463:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3464:     } else {
1.995     raeburn  3465:         $fname="$subdir/$fname";
                   3466:     }
1.1090    raeburn  3467:     if ($context eq 'coursedoc') {
1.638     albertel 3468: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3469: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3470:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3471:             return &finishuserfileupload($docuname,$docudom,
                   3472: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3473: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3474:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3475:         } else {
1.1172.2.21  raeburn  3476:             if ($env{'form.folder'}) {
                   3477:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3478:             }
1.638     albertel 3479:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3480: 				       $fname,$formname,$parser,
1.1095    raeburn  3481: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3482:         }
1.719     banghart 3483:     } elsif (defined($destuname)) {
                   3484:         my $docuname=$destuname;
                   3485:         my $docudom=$destudom;
1.860     raeburn  3486: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3487: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3488:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3489:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3490:     } else {
1.638     albertel 3491:         my $docuname=$env{'user.name'};
                   3492:         my $docudom=$env{'user.domain'};
1.1172.2.23  raeburn  3493:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3494:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3495:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3496:         }
1.860     raeburn  3497: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3498: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3499:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3500:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3501:     }
1.271     www      3502: }
                   3503: 
                   3504: sub finishuserfileupload {
1.860     raeburn  3505:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3506:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3507:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3508:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3509:   
1.860     raeburn  3510:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3511:     $file=$fname;
                   3512:     if ($fname=~m|/|) {
                   3513:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3514: 	$path.=$fnamepath.'/';
                   3515:     }
1.259     www      3516:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3517:     my $count;
                   3518:     for ($count=4;$count<=$#parts;$count++) {
                   3519:         $filepath.="/$parts[$count]";
                   3520:         if ((-e $filepath)!=1) {
                   3521: 	    mkdir($filepath,0777);
                   3522:         }
                   3523:     }
1.984     neumanie 3524: 
1.258     www      3525: # Save the file
                   3526:     {
1.701     albertel 3527: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   3528: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3529: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3530: 	    return '/adm/notfound.html';
                   3531: 	}
1.1090    raeburn  3532:         if ($context eq 'overwrite') {
1.1117    foxr     3533:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3534:             my $target = $filepath.'/'.$file;
                   3535:             if (-e $source) {
                   3536:                 my @info = stat($source);
                   3537:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3538:                     unless (&File::Copy::move($source,$target)) {
                   3539:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3540:                         return "Moving from $source failed";
                   3541:                     }
                   3542:                 } else {
                   3543:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3544:                 }
                   3545:             } else {
                   3546:                 return "Temporary file: $source missing";
                   3547:             }
                   3548:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3549: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3550: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3551: 	    return '/adm/notfound.html';
                   3552: 	}
1.570     albertel 3553: 	close(FH);
1.1051    raeburn  3554:         if ($resizewidth && $resizeheight) {
                   3555:             my $mm = new File::MMagic;
                   3556:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3557:             if ($mime_type =~ m{^image/}) {
                   3558: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3559:             }  
1.977     amueller 3560: 	}
1.258     www      3561:     }
1.1152    raeburn  3562:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3563:         if (ref($mimetype)) {
                   3564:             if ($$mimetype eq '') {
                   3565:                 my $mm = new File::MMagic;
                   3566:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3567:                 $$mimetype = $type;
                   3568:             }
                   3569:         }
                   3570:     }
1.637     raeburn  3571:     if ($parser eq 'parse') {
1.1152    raeburn  3572:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3573:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3574:                                                        $allfiles,$codebase);
                   3575:             unless ($parse_result eq 'ok') {
                   3576:                 &logthis('Failed to parse '.$filepath.$file.
                   3577: 	   	         ' for embedded media: '.$parse_result); 
                   3578:             }
1.637     raeburn  3579:         }
                   3580:     }
1.860     raeburn  3581:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3582:         my $input = $filepath.'/'.$file;
                   3583:         my $output = $filepath.'/'.'tn-'.$file;
                   3584:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3585:         system("convert -sample $thumbsize $input $output");
                   3586:         if (-e $filepath.'/'.'tn-'.$file) {
                   3587:             $fetchthumb  = 1; 
                   3588:         }
                   3589:     }
1.858     raeburn  3590:  
1.259     www      3591: # Notify homeserver to grep it
                   3592: #
1.984     neumanie 3593:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3594:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3595:     if ($fetchresult eq 'ok') {
1.860     raeburn  3596:         if ($fetchthumb) {
                   3597:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3598:             if ($thumbresult ne 'ok') {
                   3599:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3600:                          $docuhome.': '.$thumbresult);
                   3601:             }
                   3602:         }
1.259     www      3603: #
1.258     www      3604: # Return the URL to it
1.494     albertel 3605:         return '/uploaded/'.$path.$file;
1.263     www      3606:     } else {
1.494     albertel 3607:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3608: 		 ': '.$fetchresult);
1.263     www      3609:         return '/adm/notfound.html';
1.858     raeburn  3610:     }
1.493     albertel 3611: }
                   3612: 
1.637     raeburn  3613: sub extract_embedded_items {
1.961     raeburn  3614:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3615:     my @state = ();
1.1164    raeburn  3616:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3617:     my %javafiles = (
                   3618:                       codebase => '',
                   3619:                       code => '',
                   3620:                       archive => ''
                   3621:                     );
                   3622:     my %mediafiles = (
                   3623:                       src => '',
                   3624:                       movie => '',
                   3625:                      );
1.648     raeburn  3626:     my $p;
                   3627:     if ($content) {
                   3628:         $p = HTML::LCParser->new($content);
                   3629:     } else {
1.961     raeburn  3630:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3631:     }
1.641     albertel 3632:     while (my $t=$p->get_token()) {
1.640     albertel 3633: 	if ($t->[0] eq 'S') {
                   3634: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3635: 	    push(@state, $tagname);
1.648     raeburn  3636:             if (lc($tagname) eq 'allow') {
                   3637:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3638:             }
1.640     albertel 3639: 	    if (lc($tagname) eq 'img') {
                   3640: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3641: 	    }
1.886     albertel 3642: 	    if (lc($tagname) eq 'a') {
1.1172.2.24  raeburn  3643:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
                   3644: 		    &add_filetype($allfiles,$attr->{'href'},'href');
                   3645:                 }
1.886     albertel 3646: 	    }
1.645     raeburn  3647:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3648:                 my $src;
1.645     raeburn  3649:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3650:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3651:                 } else {
1.1164    raeburn  3652:                     if ($attr->{'src'} ne '') {
                   3653:                         $src = $attr->{'src'};
                   3654:                         &add_filetype($allfiles,$src,'src');
                   3655:                     }
                   3656:                 }
                   3657:                 my $text = $p->get_trimmed_text();
                   3658:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3659:                     my @swfargs = split(/,/,$1);
                   3660:                     foreach my $item (@swfargs) {
                   3661:                         $item =~ s/["']//g;
                   3662:                         $item =~ s/^\s+//;
                   3663:                         $item =~ s/\s+$//;
                   3664:                     }
                   3665:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3666:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3667:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3668:                         } else {
                   3669:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3670:                         }
                   3671:                     }
1.645     raeburn  3672:                 }
                   3673:             }
                   3674:             if (lc($tagname) eq 'link') {
                   3675:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3676:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3677:                 }
                   3678:             }
1.640     albertel 3679: 	    if (lc($tagname) eq 'object' ||
                   3680: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3681: 		foreach my $item (keys(%javafiles)) {
                   3682: 		    $javafiles{$item} = '';
                   3683: 		}
1.1164    raeburn  3684:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3685:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3686:                 }
1.640     albertel 3687: 	    }
                   3688: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3689: 		my $name = lc($attr->{'name'});
                   3690: 		foreach my $item (keys(%javafiles)) {
                   3691: 		    if ($name eq $item) {
                   3692: 			$javafiles{$item} = $attr->{'value'};
                   3693: 			last;
                   3694: 		    }
                   3695: 		}
1.1164    raeburn  3696:                 my $pathfrom;
1.640     albertel 3697: 		foreach my $item (keys(%mediafiles)) {
                   3698: 		    if ($name eq $item) {
1.1164    raeburn  3699:                         $pathfrom = $attr->{'value'};
                   3700:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3701: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3702: 			last;
                   3703: 		    }
                   3704: 		}
1.1164    raeburn  3705:                 if ($name eq 'flashvars') {
                   3706:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3707:                 }
                   3708:                 if ($pathfrom ne '') {
                   3709:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3710:                                          $pathfrom);
                   3711:                 }
1.640     albertel 3712: 	    }
                   3713: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3714: 		foreach my $item (keys(%javafiles)) {
                   3715: 		    if ($attr->{$item}) {
                   3716: 			$javafiles{$item} = $attr->{$item};
                   3717: 			last;
                   3718: 		    }
                   3719: 		}
                   3720: 		foreach my $item (keys(%mediafiles)) {
                   3721: 		    if ($attr->{$item}) {
                   3722: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3723: 			last;
                   3724: 		    }
                   3725: 		}
1.1164    raeburn  3726:                 if (lc($tagname) eq 'embed') {
                   3727:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3728:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3729:                                              $attr->{'src'});
                   3730:                     }
                   3731:                 }
1.640     albertel 3732: 	    }
1.1172.2.35  raeburn  3733:             if (lc($tagname) eq 'iframe') {
                   3734:                 my $src = $attr->{'src'} ;
                   3735:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   3736:                     &add_filetype($allfiles,$src,'src');
                   3737:                 } elsif ($src =~ m{^/}) {
                   3738:                     if ($env{'request.course.id'}) {
                   3739:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3740:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3741:                         my $url = &hreflocation('',$fullpath);
                   3742:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   3743:                             my $relpath = $1;
                   3744:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   3745:                                 &add_filetype($allfiles,$1,'src');
                   3746:                             }
                   3747:                         }
                   3748:                     }
                   3749:                 }
                   3750:             }
1.1164    raeburn  3751:             if ($t->[4] =~ m{/>$}) {
1.1172.2.35  raeburn  3752:                 pop(@state);
1.1164    raeburn  3753:             }
1.640     albertel 3754: 	} elsif ($t->[0] eq 'E') {
                   3755: 	    my ($tagname) = ($t->[1]);
                   3756: 	    if ($javafiles{'codebase'} ne '') {
                   3757: 		$javafiles{'codebase'} .= '/';
                   3758: 	    }  
                   3759: 	    if (lc($tagname) eq 'applet' ||
                   3760: 		lc($tagname) eq 'object' ||
                   3761: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3762: 		) {
                   3763: 		foreach my $item (keys(%javafiles)) {
                   3764: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3765: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3766: 			&add_filetype($allfiles,$file,$item);
                   3767: 		    }
                   3768: 		}
                   3769: 	    } 
                   3770: 	    pop @state;
                   3771: 	}
                   3772:     }
1.1164    raeburn  3773:     foreach my $id (sort(keys(%flashvars))) {
                   3774:         if ($shockwave{$id} ne '') {
                   3775:             my @pairs = split(/\&/,$flashvars{$id});
                   3776:             foreach my $pair (@pairs) {
                   3777:                 my ($key,$value) = split(/\=/,$pair);
                   3778:                 if ($key eq 'thumb') {
                   3779:                     &add_filetype($allfiles,$value,$key);
                   3780:                 } elsif ($key eq 'content') {
                   3781:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3782:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3783:                     if ($ext ne '') {
                   3784:                         &add_filetype($allfiles,$path.$value,$ext);
                   3785:                     }
                   3786:                 }
                   3787:             }
                   3788:         }
                   3789:     }
1.637     raeburn  3790:     return 'ok';
                   3791: }
                   3792: 
1.639     albertel 3793: sub add_filetype {
                   3794:     my ($allfiles,$file,$type)=@_;
                   3795:     if (exists($allfiles->{$file})) {
                   3796: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3797: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3798: 	}
                   3799:     } else {
                   3800: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3801:     }
                   3802: }
                   3803: 
1.1164    raeburn  3804: sub embedded_dependency {
                   3805:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3806:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3807:         if (($identifier ne '') &&
                   3808:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3809:             ($pathfrom ne '')) {
                   3810:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3811:             foreach my $dep (@{$related->{$identifier}}) {
                   3812:                 &add_filetype($allfiles,$path.$dep,'object');
                   3813:             }
                   3814:         }
                   3815:     }
                   3816:     return;
                   3817: }
                   3818: 
1.493     albertel 3819: sub removeuploadedurl {
1.984     neumanie 3820:     my ($url)=@_;	
                   3821:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3822:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3823: }
                   3824: 
                   3825: sub removeuserfile {
                   3826:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3827:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3828:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3829:     if ($result eq 'ok') {	
1.798     raeburn  3830:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3831:             my $metafile = $fname.'.meta';
                   3832:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3833: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3834:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3835:             my $sqlresult = 
1.823     albertel 3836:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3837:                                         'portfolio_metadata',$group,
                   3838:                                         'delete');
1.798     raeburn  3839:         }
                   3840:     }
                   3841:     return $result;
1.257     www      3842: }
1.15      www      3843: 
1.530     albertel 3844: sub mkdiruserfile {
                   3845:     my ($docuname,$docudom,$dir)=@_;
                   3846:     my $home=&homeserver($docuname,$docudom);
                   3847:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3848: }
                   3849: 
1.531     albertel 3850: sub renameuserfile {
                   3851:     my ($docuname,$docudom,$old,$new)=@_;
                   3852:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3853:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3854:                         &escape("$old").':'.&escape("$new"),$home);
                   3855:     if ($result eq 'ok') {
                   3856:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3857:             my $oldmeta = $old.'.meta';
                   3858:             my $newmeta = $new.'.meta';
                   3859:             my $metaresult = 
                   3860:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3861: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3862:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3863:             my $sqlresult = 
1.823     albertel 3864:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3865:                                         'portfolio_metadata',$group,
                   3866:                                         'delete');
1.798     raeburn  3867:         }
                   3868:     }
                   3869:     return $result;
1.531     albertel 3870: }
                   3871: 
1.14      www      3872: # ------------------------------------------------------------------------- Log
                   3873: 
                   3874: sub log {
                   3875:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3876:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3877: }
                   3878: 
                   3879: # ------------------------------------------------------------------ Course Log
1.352     www      3880: #
                   3881: # This routine flushes several buffers of non-mission-critical nature
                   3882: #
1.157     www      3883: 
                   3884: sub flushcourselogs {
1.352     www      3885:     &logthis('Flushing log buffers');
                   3886: #
                   3887: # course logs
                   3888: # This is a log of all transactions in a course, which can be used
                   3889: # for data mining purposes
                   3890: #
                   3891: # It also collects the courseid database, which lists last transaction
                   3892: # times and course titles for all courseids
                   3893: #
                   3894:     my %courseidbuffer=();
1.921     raeburn  3895:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3896:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3897: 		          &escape($courselogs{$crsid}),
                   3898: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3899: 	    delete $courselogs{$crsid};
                   3900:         } else {
                   3901:             &logthis('Failed to flush log buffer for '.$crsid);
                   3902:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3903:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3904:                         " exceeded maximum size, deleting.</font>");
                   3905:                delete $courselogs{$crsid};
                   3906:             }
1.352     www      3907:         }
1.920     raeburn  3908:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3909:             'description' => $coursedescrbuf{$crsid},
                   3910:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3911:             'type'        => $coursetypebuf{$crsid},
                   3912:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3913:         };
1.191     harris41 3914:     }
1.352     www      3915: #
                   3916: # Write course id database (reverse lookup) to homeserver of courses 
                   3917: # Is used in pickcourse
                   3918: #
1.840     albertel 3919:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3920:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3921:                                     $courseidbuffer{$crs_home},
                   3922:                                     $crs_home,'timeonly');
1.352     www      3923:     }
                   3924: #
                   3925: # File accesses
                   3926: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3927: #
1.449     matthew  3928:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3929:         if ($entry =~ /___count$/) {
                   3930:             my ($dom,$name);
1.807     albertel 3931:             ($dom,$name,undef)=
1.811     albertel 3932: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3933:             if (! defined($dom) || $dom eq '' || 
                   3934:                 ! defined($name) || $name eq '') {
1.620     albertel 3935:                 my $cid = $env{'request.course.id'};
                   3936:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3937:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3938:             }
1.450     matthew  3939:             my $value = $accesshash{$entry};
                   3940:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   3941:             my %temphash=($url => $value);
1.449     matthew  3942:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   3943:             if ($result eq 'ok') {
                   3944:                 delete $accesshash{$entry};
                   3945:             }
                   3946:         } else {
1.811     albertel 3947:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      3948:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  3949:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3950:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3951:                 delete $accesshash{$entry};
                   3952:             }
1.185     www      3953:         }
1.191     harris41 3954:     }
1.352     www      3955: #
                   3956: # Roles
                   3957: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   3958: #
1.800     albertel 3959:     foreach my $entry (keys(%userrolehash)) {
1.351     www      3960:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      3961: 	    split(/\:/,$entry);
                   3962:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      3963:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      3964:                 $rudom,$runame) eq 'ok') {
                   3965: 	    delete $userrolehash{$entry};
                   3966:         }
                   3967:     }
1.662     raeburn  3968: #
1.1172.2.90  raeburn  3969: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  3970: #
                   3971:     my %domrolebuffer = ();
1.1000    raeburn  3972:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 3973:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  3974:         if ($domrolebuffer{$rudom}) {
                   3975:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   3976:                       '='.&escape($domainrolehash{$entry});
                   3977:         } else {
                   3978:             $domrolebuffer{$rudom}.=&escape($entry).
                   3979:                       '='.&escape($domainrolehash{$entry});
                   3980:         }
                   3981:         delete $domainrolehash{$entry};
                   3982:     }
                   3983:     foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82  raeburn  3984:         my %servers;
                   3985:         if (defined(&domain($dom,'primary'))) {
                   3986:             my $primary=&domain($dom,'primary');
                   3987:             my $hostname=&hostname($primary);
                   3988:             $servers{$primary} = $hostname;
                   3989:         } else {
                   3990:             %servers = &get_servers($dom,'library');
                   3991:         }
1.841     albertel 3992: 	foreach my $tryserver (keys(%servers)) {
1.1172.2.82  raeburn  3993: 	    if (&reply('domroleput:'.$dom.':'.
                   3994: 	               $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   3995: 	        last;
                   3996: 	    } else {
1.841     albertel 3997: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   3998: 	    }
1.662     raeburn  3999:         }
                   4000:     }
1.186     www      4001:     $dumpcount++;
1.157     www      4002: }
                   4003: 
                   4004: sub courselog {
                   4005:     my $what=shift;
1.158     www      4006:     $what=time.':'.$what;
1.620     albertel 4007:     unless ($env{'request.course.id'}) { return ''; }
                   4008:     $coursedombuf{$env{'request.course.id'}}=
                   4009:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4010:     $coursenumbuf{$env{'request.course.id'}}=
                   4011:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4012:     $coursehombuf{$env{'request.course.id'}}=
                   4013:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4014:     $coursedescrbuf{$env{'request.course.id'}}=
                   4015:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4016:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4017:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4018:     $courseownerbuf{$env{'request.course.id'}}=
                   4019:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4020:     $coursetypebuf{$env{'request.course.id'}}=
                   4021:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4022:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4023: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4024:     } else {
1.620     albertel 4025: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4026:     }
1.620     albertel 4027:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4028: 	&flushcourselogs();
                   4029:     }
1.158     www      4030: }
                   4031: 
                   4032: sub courseacclog {
                   4033:     my $fnsymb=shift;
1.620     albertel 4034:     unless ($env{'request.course.id'}) { return ''; }
                   4035:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4036:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4037:         $what.=':POST';
1.583     matthew  4038:         # FIXME: Probably ought to escape things....
1.800     albertel 4039: 	foreach my $key (keys(%env)) {
                   4040:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4041:                 my $formitem = $1;
                   4042:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4043:                     $what.=':'.$formitem.'='.$env{$key};
                   4044:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   4045:                     $what.=':'.$formitem.'='.$env{$key};
                   4046:                 }
1.158     www      4047:             }
1.191     harris41 4048:         }
1.583     matthew  4049:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4050:         # FIXME: We should not be depending on a form parameter that someone
                   4051:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4052:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4053:             $what.= ':POST';
                   4054:             # FIXME: Probably ought to escape things....
                   4055:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4056:                                  'crsdiscuss') {
1.620     albertel 4057:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4058:             }
                   4059:         }
1.158     www      4060:     }
                   4061:     &courselog($what);
1.149     www      4062: }
                   4063: 
1.185     www      4064: sub countacc {
                   4065:     my $url=&declutter(shift);
1.458     matthew  4066:     return if (! defined($url) || $url eq '');
1.620     albertel 4067:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4068: #
                   4069: # Mark that this url was used in this course
                   4070: #
1.620     albertel 4071:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4072: #
                   4073: # Increase the access count for this resource in this child process
                   4074: #
1.281     www      4075:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4076:     $accesshash{$key}++;
1.185     www      4077: }
1.349     www      4078: 
1.361     www      4079: sub linklog {
                   4080:     my ($from,$to)=@_;
                   4081:     $from=&declutter($from);
                   4082:     $to=&declutter($to);
                   4083:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4084:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4085: }
1.1160    www      4086: 
                   4087: sub statslog {
                   4088:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4089:     if ($users<2) { return; }
                   4090:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4091:             'course'       => $env{'request.course.id'},
                   4092:             'sections'     => '"all"',
                   4093:             'num_students' => $users,
                   4094:             'part'         => $part,
                   4095:             'symb'         => $symb,
                   4096:             'mean_tries'   => $av_attempts,
                   4097:             'deg_of_diff'  => $degdiff});
                   4098:     foreach my $key (keys(%dynstore)) {
                   4099:         $accesshash{$key}=$dynstore{$key};
                   4100:     }
                   4101: }
1.361     www      4102:   
1.349     www      4103: sub userrolelog {
                   4104:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4105:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4106:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4107:        $userrolehash
                   4108:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4109:                     =$tend.':'.$tstart;
1.662     raeburn  4110:     }
1.1169    droeschl 4111:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4112:        $userrolehash
                   4113:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4114:                     =$tend.':'.$tstart;
                   4115:     }
1.1172.2.90  raeburn  4116:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4117:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4118:        $domainrolehash
                   4119:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4120:                     = $tend.':'.$tstart;
                   4121:     }
1.351     www      4122: }
                   4123: 
1.957     raeburn  4124: sub courserolelog {
                   4125:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  4126:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4127:         my $cdom = $1;
                   4128:         my $cnum = $2;
                   4129:         my $sec = $3;
                   4130:         my $namespace = 'rolelog';
                   4131:         my %storehash = (
                   4132:                            role    => $trole,
                   4133:                            start   => $tstart,
                   4134:                            end     => $tend,
                   4135:                            selfenroll => $selfenroll,
                   4136:                            context    => $context,
                   4137:                         );
                   4138:         if ($trole eq 'gr') {
                   4139:             $namespace = 'groupslog';
                   4140:             $storehash{'group'} = $sec;
                   4141:         } else {
                   4142:             $storehash{'section'} = $sec;
                   4143:         }
                   4144:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4145:                    $domain,$cnum,$cdom);
                   4146:         if (($trole ne 'st') || ($sec ne '')) {
                   4147:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4148:         }
                   4149:     }
                   4150:     return;
                   4151: }
                   4152: 
1.1172.2.9  raeburn  4153: sub domainrolelog {
                   4154:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4155:     if ($area =~ m{^/($match_domain)/$}) {
                   4156:         my $cdom = $1;
                   4157:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4158:         my $namespace = 'rolelog';
                   4159:         my %storehash = (
                   4160:                            role    => $trole,
                   4161:                            start   => $tstart,
                   4162:                            end     => $tend,
                   4163:                            context => $context,
                   4164:                         );
                   4165:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4166:                    $domain,$domconfiguser,$cdom);
                   4167:     }
                   4168:     return;
                   4169: 
                   4170: }
                   4171: 
                   4172: sub coauthorrolelog {
                   4173:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4174:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4175:         my $audom = $1;
                   4176:         my $auname = $2;
                   4177:         my $namespace = 'rolelog';
                   4178:         my %storehash = (
                   4179:                            role    => $trole,
                   4180:                            start   => $tstart,
                   4181:                            end     => $tend,
                   4182:                            context => $context,
                   4183:                         );
                   4184:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4185:                    $domain,$auname,$audom);
                   4186:     }
                   4187:     return;
                   4188: }
                   4189: 
1.351     www      4190: sub get_course_adv_roles {
1.948     raeburn  4191:     my ($cid,$codes) = @_;
1.620     albertel 4192:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4193:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4194:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4195:     my %nothide=();
1.800     albertel 4196:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4197:         if ($user !~ /:/) {
                   4198: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4199:         } else {
                   4200:             $nothide{$user}=1;
                   4201:         }
1.470     www      4202:     }
1.1172.2.23  raeburn  4203:     my @possdoms = ($coursehash{'domain'});
                   4204:     if ($coursehash{'checkforpriv'}) {
                   4205:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4206:     }
1.351     www      4207:     my %returnhash=();
                   4208:     my %dumphash=
                   4209:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4210:     my $now=time;
1.997     raeburn  4211:     my %privileged;
1.1000    raeburn  4212:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4213: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4214:         if (($tstart) && ($tstart<0)) { next; }
                   4215:         if (($tend) && ($tend<$now)) { next; }
                   4216:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4217:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4218: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  4219:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4220:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4221: 	if ($role eq 'cr') { next; }
1.948     raeburn  4222:         if ($codes) {
                   4223:             if ($section) { $role .= ':'.$section; }
                   4224:             if ($returnhash{$role}) {
                   4225:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4226:             } else {
                   4227:                 $returnhash{$role}=$username.':'.$domain;
                   4228:             }
1.351     www      4229:         } else {
1.988     raeburn  4230:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4231:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4232:             if ($returnhash{$key}) {
                   4233: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4234:             } else {
                   4235:                 $returnhash{$key}=$username.':'.$domain;
                   4236:             }
1.351     www      4237:         }
1.948     raeburn  4238:     }
1.400     www      4239:     return %returnhash;
                   4240: }
                   4241: 
                   4242: sub get_my_roles {
1.937     raeburn  4243:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4244:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4245:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4246:     my (%dumphash,%nothide);
1.1086    raeburn  4247:     if ($context eq 'userroles') {
1.1166    raeburn  4248:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4249:     } else {
1.1172.2.23  raeburn  4250:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4251:         if ($hidepriv) {
                   4252:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4253:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4254:                 if ($user !~ /:/) {
                   4255:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4256:                 } else {
                   4257:                     $nothide{$user} = 1;
                   4258:                 }
                   4259:             }
                   4260:         }
1.858     raeburn  4261:     }
1.400     www      4262:     my %returnhash=();
                   4263:     my $now=time;
1.999     raeburn  4264:     my %privileged;
1.800     albertel 4265:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4266:         my ($role,$tend,$tstart);
                   4267:         if ($context eq 'userroles') {
1.1149    raeburn  4268:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4269: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4270:         } else {
                   4271:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4272:         }
1.400     www      4273:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4274:         my $status = 'active';
1.939     raeburn  4275:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4276:             $status = 'previous';
                   4277:         } 
                   4278:         if (($tstart) && ($now<$tstart)) {
                   4279:             $status = 'future';
                   4280:         }
                   4281:         if (ref($types) eq 'ARRAY') {
                   4282:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4283:                 next;
                   4284:             } 
                   4285:         } else {
                   4286:             if ($status ne 'active') {
                   4287:                 next;
                   4288:             }
                   4289:         }
1.867     raeburn  4290:         my ($rolecode,$username,$domain,$section,$area);
                   4291:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  4292:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4293:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4294:         } else {
                   4295:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4296:         }
1.832     raeburn  4297:         if (ref($roledoms) eq 'ARRAY') {
                   4298:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4299:                 next;
                   4300:             }
                   4301:         }
                   4302:         if (ref($roles) eq 'ARRAY') {
                   4303:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4304:                 if ($role =~ /^cr\//) {
                   4305:                     if (!grep(/^cr$/,@{$roles})) {
                   4306:                         next;
                   4307:                     }
1.1104    raeburn  4308:                 } elsif ($role =~ /^gr\//) {
                   4309:                     if (!grep(/^gr$/,@{$roles})) {
                   4310:                         next;
                   4311:                     }
1.922     raeburn  4312:                 } else {
                   4313:                     next;
                   4314:                 }
1.832     raeburn  4315:             }
1.867     raeburn  4316:         }
1.937     raeburn  4317:         if ($hidepriv) {
1.1172.2.23  raeburn  4318:             my @privroles = ('dc','su');
1.999     raeburn  4319:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  4320:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4321:             } else {
1.1172.2.23  raeburn  4322:                 my $possdoms = [$domain];
                   4323:                 if (ref($roledoms) eq 'ARRAY') {
                   4324:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  4325:                 }
1.1172.2.23  raeburn  4326:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4327:                     if (!$nothide{$username.':'.$domain}) {
                   4328:                         next;
                   4329:                     }
                   4330:                 }
1.937     raeburn  4331:             }
                   4332:         }
1.933     raeburn  4333:         if ($withsec) {
                   4334:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4335:                 $tstart.':'.$tend;
                   4336:         } else {
                   4337:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4338:         }
1.832     raeburn  4339:     }
1.373     www      4340:     return %returnhash;
1.399     www      4341: }
                   4342: 
1.1172.2.89  raeburn  4343: sub get_all_adhocroles {
                   4344:     my ($dom) = @_;
                   4345:     my @roles_by_num = ();
                   4346:     my %domdefaults = &get_domain_defaults($dom);
                   4347:     my (%description,%access_in_dom,%access_info);
                   4348:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   4349:         my $count = 0;
                   4350:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   4351:         my %ordered;
                   4352:         foreach my $role (sort(keys(%domcurrent))) {
                   4353:             my ($order,$desc,$access_in_dom);
                   4354:             if (ref($domcurrent{$role}) eq 'HASH') {
                   4355:                 $order = $domcurrent{$role}{'order'};
                   4356:                 $desc = $domcurrent{$role}{'desc'};
                   4357:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   4358:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   4359:             }
                   4360:             if ($order eq '') {
                   4361:                 $order = $count;
                   4362:             }
                   4363:             $ordered{$order} = $role;
                   4364:             if ($desc ne '') {
                   4365:                 $description{$role} = $desc;
                   4366:             } else {
                   4367:                 $description{$role}= $role;
                   4368:             }
                   4369:             $count++;
                   4370:         }
                   4371:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   4372:             push(@roles_by_num,$ordered{$item});
                   4373:         }
                   4374:     }
                   4375:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   4376: }
                   4377: 
                   4378: sub get_my_adhocroles {
                   4379:     my ($cid,$checkreg) = @_;
                   4380:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   4381:     if ($env{'request.course.id'} eq $cid) {
                   4382:         $cdom = $env{'course.'.$cid.'.domain'};
                   4383:         $cnum = $env{'course.'.$cid.'.num'};
                   4384:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   4385:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   4386:         $cdom = $1;
                   4387:         $cnum = $2;
                   4388:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   4389:                                      $cdom,$cnum);
                   4390:     }
                   4391:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   4392:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   4393:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   4394:         if ($rosterhash{$user} ne '') {
                   4395:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   4396:             return ([],{}) if ($type eq 'auto');
                   4397:         }
                   4398:     }
                   4399:     if (($cdom ne '') && ($cnum ne ''))  {
1.1172.2.90  raeburn  4400:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89  raeburn  4401:             my $then=$env{'user.login.time'};
                   4402:             my $update=$env{'user.update.time'};
1.1172.2.90  raeburn  4403:             if (!$update) {
                   4404:                 $update = $then;
                   4405:             }
                   4406:             my @liveroles;
                   4407:             foreach my $role ('dh','da') {
                   4408:                 if ($env{"user.role.$role./$cdom/"}) {
                   4409:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
                   4410:                     my $limit = $update;
                   4411:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   4412:                         $limit = $then;
                   4413:                     }
                   4414:                     my $activerole = 1;
                   4415:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   4416:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   4417:                     if ($activerole) {
                   4418:                         push(@liveroles,$role);
                   4419:                     }
                   4420:                 }
                   4421:             }
                   4422:             if (@liveroles) {
1.1172.2.89  raeburn  4423:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
                   4424:                     my ($accessref,$accessinfo,%access_in_dom);
                   4425:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   4426:                     if (ref($roles_by_num) eq 'ARRAY') {
                   4427:                         if (@{$roles_by_num}) {
                   4428:                             my %settings;
                   4429:                             if ($env{'request.course.id'} eq $cid) {
                   4430:                                 foreach my $envkey (keys(%env)) {
                   4431:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   4432:                                         $settings{$1} = $env{$envkey};
                   4433:                                     }
                   4434:                                 }
                   4435:                             } else {
                   4436:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   4437:                             }
                   4438:                             my %setincrs;
                   4439:                             if ($settings{'internal.adhocaccess'}) {
                   4440:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   4441:                             }
                   4442:                             my @statuses;
                   4443:                             if ($env{'environment.inststatus'}) {
                   4444:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   4445:                             }
                   4446:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   4447:                             if (ref($accessref) eq 'HASH') {
                   4448:                                 %access_in_dom = %{$accessref};
                   4449:                             }
                   4450:                             foreach my $role (@{$roles_by_num}) {
                   4451:                                 my ($curraccess,@okstatus,@personnel);
                   4452:                                 if ($setincrs{$role}) {
                   4453:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   4454:                                     if ($curraccess eq 'status') {
                   4455:                                         @okstatus = split(/\&/,$rest);
                   4456:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4457:                                         @personnel = split(/\&/,$rest);
                   4458:                                     }
                   4459:                                 } else {
                   4460:                                     $curraccess = $access_in_dom{$role};
                   4461:                                     if (ref($accessinfo) eq 'HASH') {
                   4462:                                         if ($curraccess eq 'status') {
                   4463:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   4464:                                                 @okstatus = @{$accessinfo->{$role}};
                   4465:                                             }
                   4466:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4467:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   4468:                                                 @personnel = @{$accessinfo->{$role}};
                   4469:                                             }
                   4470:                                         }
                   4471:                                     }
                   4472:                                 }
                   4473:                                 if ($curraccess eq 'none') {
                   4474:                                     next;
                   4475:                                 } elsif ($curraccess eq 'all') {
                   4476:                                     push(@possroles,$role);
1.1172.2.90  raeburn  4477:                                 } elsif ($curraccess eq 'dh') {
                   4478:                                     if (grep(/^dh$/,@liveroles)) {
                   4479:                                         push(@possroles,$role);
                   4480:                                     } else {
                   4481:                                         next;
                   4482:                                     }
                   4483:                                 } elsif ($curraccess eq 'da') {
                   4484:                                     if (grep(/^da$/,@liveroles)) {
                   4485:                                         push(@possroles,$role);
                   4486:                                     } else {
                   4487:                                         next;
                   4488:                                     }
1.1172.2.89  raeburn  4489:                                 } elsif ($curraccess eq 'status') {
                   4490:                                     if (@okstatus) {
                   4491:                                         if (!@statuses) {
                   4492:                                             if (grep(/^default$/,@okstatus)) {
                   4493:                                                 push(@possroles,$role);
                   4494:                                             }
                   4495:                                         } else {
                   4496:                                             foreach my $status (@okstatus) {
                   4497:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   4498:                                                     push(@possroles,$role);
                   4499:                                                     last;
                   4500:                                                 }
                   4501:                                             }
                   4502:                                         }
                   4503:                                     }
                   4504:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4505:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   4506:                                         if ($curraccess eq 'exc') {
                   4507:                                             push(@possroles,$role);
                   4508:                                         }
                   4509:                                     } elsif ($curraccess eq 'inc') {
                   4510:                                         push(@possroles,$role);
                   4511:                                     }
                   4512:                                 }
                   4513:                             }
                   4514:                         }
                   4515:                     }
                   4516:                 }
                   4517:             }
                   4518:         }
                   4519:     }
                   4520:     unless (ref($description) eq 'HASH') {
                   4521:         if (ref($roles_by_num) eq 'ARRAY') {
                   4522:             my %desc;
                   4523:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   4524:             $description = \%desc;
                   4525:         } else {
                   4526:             $description = {};
                   4527:         }
                   4528:     }
                   4529:     return (\@possroles,$description);
                   4530: }
                   4531: 
1.399     www      4532: # ----------------------------------------------------- Frontpage Announcements
                   4533: #
                   4534: #
                   4535: 
                   4536: sub postannounce {
                   4537:     my ($server,$text)=@_;
1.844     albertel 4538:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4539:     unless ($text=~/\w/) { $text=''; }
                   4540:     return &reply('setannounce:'.&escape($text),$server);
                   4541: }
                   4542: 
                   4543: sub getannounce {
1.448     albertel 4544: 
                   4545:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4546: 	my $announcement='';
1.800     albertel 4547: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4548: 	close($fh);
1.399     www      4549: 	if ($announcement=~/\w/) { 
                   4550: 	    return 
                   4551:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4552:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4553: 	} else {
                   4554: 	    return '';
                   4555: 	}
                   4556:     } else {
                   4557: 	return '';
                   4558:     }
1.351     www      4559: }
1.353     www      4560: 
                   4561: # ---------------------------------------------------------- Course ID routines
                   4562: # Deal with domain's nohist_courseid.db files
                   4563: #
                   4564: 
                   4565: sub courseidput {
1.921     raeburn  4566:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4567:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4568:     my $outcome;
                   4569:     if ($caller eq 'timeonly') {
                   4570:         my $cids = '';
                   4571:         foreach my $item (keys(%$storehash)) {
                   4572:             $cids.=&escape($item).'&';
                   4573:         }
                   4574:         $cids=~s/\&$//;
                   4575:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4576:                           $coursehome);       
                   4577:     } else {
                   4578:         my $items = '';
                   4579:         foreach my $item (keys(%$storehash)) {
                   4580:             $items.= &escape($item).'='.
                   4581:                      &freeze_escape($$storehash{$item}).'&';
                   4582:         }
                   4583:         $items=~s/\&$//;
                   4584:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4585:                           $coursehome);
1.918     raeburn  4586:     }
                   4587:     if ($outcome eq 'unknown_cmd') {
                   4588:         my $what;
                   4589:         foreach my $cid (keys(%$storehash)) {
                   4590:             $what .= &escape($cid).'=';
1.921     raeburn  4591:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4592:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4593:             }
                   4594:             $what =~ s/\:$/&/;
                   4595:         }
                   4596:         $what =~ s/\&$//;  
                   4597:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4598:     } else {
                   4599:         return $outcome;
                   4600:     }
1.353     www      4601: }
                   4602: 
                   4603: sub courseiddump {
1.921     raeburn  4604:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4605:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4606:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38  raeburn  4607:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68  raeburn  4608:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  4609:     my $as_hash = 1;
                   4610:     my %returnhash;
                   4611:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4612:     my %libserv = &all_library();
                   4613:     foreach my $tryserver (keys(%libserv)) {
                   4614:         if ( (  $hostidflag == 1 
                   4615: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4616: 	     || (!defined($hostidflag)) ) {
                   4617: 
1.918     raeburn  4618: 	    if (($domfilter eq '') ||
                   4619: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  4620:                 my $rep;
                   4621:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   4622:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   4623:                         join(":", (&host_domain($tryserver), $sincefilter,
                   4624:                                 &escape($descfilter), &escape($instcodefilter),
                   4625:                                 &escape($ownerfilter), &escape($coursefilter),
                   4626:                                 &escape($typefilter), &escape($regexp_ok),
                   4627:                                 $as_hash, &escape($selfenrollonly),
                   4628:                                 &escape($catfilter), $showhidden, $caller,
                   4629:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   4630:                                 &escape($createdbefore), &escape($createdafter),
1.1172.2.68  raeburn  4631:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   4632:                                 $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22  raeburn  4633:                 } else {
                   4634:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4635:                              $sincefilter.':'.&escape($descfilter).':'.
                   4636:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   4637:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   4638:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   4639:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   4640:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   4641:                              &escape($cc_clone).':'.$cloneonly.':'.
                   4642:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68  raeburn  4643:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   4644:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22  raeburn  4645:                 }
                   4646: 
1.918     raeburn  4647:                 my @pairs=split(/\&/,$rep);
                   4648:                 foreach my $item (@pairs) {
                   4649:                     my ($key,$value)=split(/\=/,$item,2);
                   4650:                     $key = &unescape($key);
                   4651:                     next if ($key =~ /^error: 2 /);
                   4652:                     my $result = &thaw_unescape($value);
                   4653:                     if (ref($result) eq 'HASH') {
                   4654:                         $returnhash{$key}=$result;
                   4655:                     } else {
1.921     raeburn  4656:                         my @responses = split(/:/,$value);
                   4657:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4658:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4659:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4660:                         }
1.1008    raeburn  4661:                     }
1.353     www      4662:                 }
                   4663:             }
                   4664:         }
                   4665:     }
                   4666:     return %returnhash;
                   4667: }
                   4668: 
1.1055    raeburn  4669: sub courselastaccess {
                   4670:     my ($cdom,$cnum,$hostidref) = @_;
                   4671:     my %returnhash;
                   4672:     if ($cdom && $cnum) {
                   4673:         my $chome = &homeserver($cnum,$cdom);
                   4674:         if ($chome ne 'no_host') {
                   4675:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4676:             &extract_lastaccess(\%returnhash,$rep);
                   4677:         }
                   4678:     } else {
                   4679:         if (!$cdom) { $cdom=''; }
                   4680:         my %libserv = &all_library();
                   4681:         foreach my $tryserver (keys(%libserv)) {
                   4682:             if (ref($hostidref) eq 'ARRAY') {
                   4683:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4684:             } 
                   4685:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4686:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4687:                 &extract_lastaccess(\%returnhash,$rep);
                   4688:             }
                   4689:         }
                   4690:     }
                   4691:     return %returnhash;
                   4692: }
                   4693: 
                   4694: sub extract_lastaccess {
                   4695:     my ($returnhash,$rep) = @_;
                   4696:     if (ref($returnhash) eq 'HASH') {
                   4697:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4698:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4699:                  $rep eq '') {
                   4700:             my @pairs=split(/\&/,$rep);
                   4701:             foreach my $item (@pairs) {
                   4702:                 my ($key,$value)=split(/\=/,$item,2);
                   4703:                 $key = &unescape($key);
                   4704:                 next if ($key =~ /^error: 2 /);
                   4705:                 $returnhash->{$key} = &thaw_unescape($value);
                   4706:             }
                   4707:         }
                   4708:     }
                   4709:     return;
                   4710: }
                   4711: 
1.658     raeburn  4712: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4713: 
                   4714: sub dcmailput {
1.685     raeburn  4715:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4716:     my $status = &Apache::lonnet::critical(
1.740     www      4717:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4718:        &escape($message),$server);
1.662     raeburn  4719:     return $status;
                   4720: }
                   4721: 
1.658     raeburn  4722: sub dcmaildump {
                   4723:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4724:     my %returnhash=();
1.846     albertel 4725: 
                   4726:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4727:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4728:                                                          &escape($enddate).':';
                   4729: 	my @esc_senders=map { &escape($_)} @$senders;
                   4730: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4731: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4732:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4733:             if (($key) && ($value)) {
                   4734:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4735:             }
                   4736:         }
                   4737:     }
                   4738:     return %returnhash;
                   4739: }
1.662     raeburn  4740: # ---------------------------------------------------------- Domain roles
                   4741: 
                   4742: sub get_domain_roles {
                   4743:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4744:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4745:         $startdate = '.';
                   4746:     }
1.1018    raeburn  4747:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4748:         $enddate = '.';
                   4749:     }
1.922     raeburn  4750:     my $rolelist;
                   4751:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  4752:         $rolelist = join('&',@{$roles});
1.922     raeburn  4753:     }
1.662     raeburn  4754:     my %personnel = ();
1.841     albertel 4755: 
                   4756:     my %servers = &get_servers($dom,'library');
                   4757:     foreach my $tryserver (keys(%servers)) {
                   4758: 	%{$personnel{$tryserver}}=();
                   4759: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4760: 					    &escape($startdate).':'.
                   4761: 					    &escape($enddate).':'.
                   4762: 					    &escape($rolelist), $tryserver))) {
                   4763: 	    my ($key,$value) = split(/\=/,$line,2);
                   4764: 	    if (($key) && ($value)) {
                   4765: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4766: 	    }
                   4767: 	}
1.662     raeburn  4768:     }
                   4769:     return %personnel;
                   4770: }
1.658     raeburn  4771: 
1.1172.2.89  raeburn  4772: sub get_active_domroles {
                   4773:     my ($dom,$roles) = @_;
                   4774:     return () unless (ref($roles) eq 'ARRAY');
                   4775:     my $now = time;
                   4776:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   4777:     my %domroles;
                   4778:     foreach my $server (keys(%dompersonnel)) {
                   4779:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   4780:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   4781:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   4782:         }
                   4783:     }
                   4784:     return %domroles;
                   4785: }
                   4786: 
1.1057    www      4787: # ----------------------------------------------------------- Interval timing 
1.149     www      4788: 
1.1153    www      4789: {
                   4790: # Caches needed for speedup of navmaps
                   4791: # We don't want to cache this for very long at all (5 seconds at most)
                   4792: # 
                   4793: # The user for whom we cache
                   4794: my $cachedkey='';
                   4795: # The cached times for this user
                   4796: my %cachedtimes=();
                   4797: # When this was last done
1.1172.2.66  raeburn  4798: my $cachedtime='';
1.1153    www      4799: 
                   4800: sub load_all_first_access {
1.1172.2.93.4  1(raebur 4801:7):     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      4802:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.93.4  1(raebur 4803:7):         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   4804:7):         (!$ignorecache)) {
1.1154    raeburn  4805:         return;
                   4806:     }
                   4807:     $cachedtime=time;
                   4808:     $cachedkey=$uname.':'.$udom;
                   4809:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4810: }
                   4811: 
1.504     albertel 4812: sub get_first_access {
1.1172.2.93.4  1(raebur 4813:7):     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 4814:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4815:     if ($argsymb) { $symb=$argsymb; }
                   4816:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4817:     if ($argmap) { $map = $argmap; }
1.926     albertel 4818:     if ($type eq 'course') {
                   4819: 	$res='course';
                   4820:     } elsif ($type eq 'map') {
1.588     albertel 4821: 	$res=&symbread($map);
                   4822:     } else {
                   4823: 	$res=$symb;
                   4824:     }
1.1172.2.93.4  1(raebur 4825:7):     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      4826:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4827: }
                   4828: 
                   4829: sub set_first_access {
1.1162    raeburn  4830:     my ($type,$interval)=@_;
1.790     albertel 4831:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4832:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4833:     if ($type eq 'course') {
                   4834: 	$res='course';
                   4835:     } elsif ($type eq 'map') {
1.588     albertel 4836: 	$res=&symbread($map);
                   4837:     } else {
                   4838: 	$res=$symb;
                   4839:     }
1.1153    www      4840:     $cachedkey='';
1.1162    raeburn  4841:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4842:     if (!$firstaccess) {
1.1162    raeburn  4843:         my $start = time;
                   4844: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4845:                           $udom,$uname);
                   4846:         if ($putres eq 'ok') {
                   4847:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4848:                  $udom,$uname); 
                   4849:             &appenv(
                   4850:                      {
                   4851:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4852:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4853:                      }
                   4854:                   );
                   4855:         }
                   4856:         return $putres;
1.505     albertel 4857:     }
                   4858:     return 'already_set';
1.504     albertel 4859: }
1.1153    www      4860: }
1.1172.2.32  raeburn  4861: 
                   4862: sub checkout {
                   4863:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   4864:     my $now=time;
                   4865:     my $lonhost=$perlvar{'lonHostID'};
                   4866:     my $infostr=&escape(
                   4867:                  'CHECKOUTTOKEN&'.
                   4868:                  $tuname.'&'.
                   4869:                  $tudom.'&'.
                   4870:                  $tcrsid.'&'.
                   4871:                  $symb.'&'.
                   4872:                  $now.'&'.$ENV{'REMOTE_ADDR'});
                   4873:     my $token=&reply('tmpput:'.$infostr,$lonhost);
                   4874:     if ($token=~/^error\:/) {
                   4875:         &logthis("<font color=\"blue\">WARNING: ".
                   4876:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   4877:                  "</font>");
                   4878:         return '';
                   4879:     }
                   4880: 
                   4881:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   4882:     $token=~tr/a-z/A-Z/;
                   4883: 
                   4884:     my %infohash=('resource.0.outtoken' => $token,
                   4885:                   'resource.0.checkouttime' => $now,
                   4886:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
                   4887: 
                   4888:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   4889:        return '';
                   4890:     } else {
                   4891:         &logthis("<font color=\"blue\">WARNING: ".
                   4892:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   4893:                  "</font>");
                   4894:     }
                   4895: 
                   4896:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   4897:                          &escape('Checkout '.$infostr.' - '.
                   4898:                                                  $token)) ne 'ok') {
                   4899:         return '';
                   4900:     } else {
                   4901:         &logthis("<font color=\"blue\">WARNING: ".
                   4902:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   4903:                  "</font>");
                   4904:     }
                   4905:     return $token;
                   4906: }
                   4907: 
                   4908: # ------------------------------------------------------------ Check in an item
                   4909: 
                   4910: sub checkin {
                   4911:     my $token=shift;
                   4912:     my $now=time;
                   4913:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   4914:     $lonhost=~tr/A-Z/a-z/;
                   4915:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
                   4916:     $dtoken=~s/\W/\_/g;
                   4917:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                   4918:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   4919: 
                   4920:     unless (($tuname) && ($tudom)) {
                   4921:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   4922:         return '';
                   4923:     }
                   4924: 
                   4925:     unless (&allowed('mgr',$tcrsid)) {
                   4926:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   4927:                  $env{'user.name'}.' - '.$env{'user.domain'});
                   4928:         return '';
                   4929:     }
                   4930: 
                   4931:     my %infohash=('resource.0.intoken' => $token,
                   4932:                   'resource.0.checkintime' => $now,
                   4933:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
                   4934: 
                   4935:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   4936:        return '';
                   4937:     }
                   4938: 
                   4939:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   4940:                          &escape('Checkin - '.$token)) ne 'ok') {
                   4941:         return '';
                   4942:     }
                   4943: 
                   4944:     return ($symb,$tuname,$tudom,$tcrsid);
                   4945: }
                   4946: 
1.110     www      4947: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4948: 
                   4949: sub expirespread {
                   4950:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4951:     my $cid=$env{'request.course.id'}; 
1.110     www      4952:     if ($cid) {
                   4953:        my $now=time;
                   4954:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4955:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4956:                             $env{'course.'.$cid.'.num'}.
1.110     www      4957: 	        	    ':nohist_expirationdates:'.
                   4958:                             &escape($key).'='.$now,
1.620     albertel 4959:                             $env{'course.'.$cid.'.home'})
1.110     www      4960:     }
                   4961:     return 'ok';
1.14      www      4962: }
                   4963: 
1.109     www      4964: # ----------------------------------------------------- Devalidate Spreadsheets
                   4965: 
                   4966: sub devalidate {
1.325     www      4967:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4968:     my $cid=$env{'request.course.id'}; 
1.109     www      4969:     if ($cid) {
1.391     matthew  4970:         # delete the stored spreadsheets for
                   4971:         # - the student level sheet of this user in course's homespace
                   4972:         # - the assessment level sheet for this resource 
                   4973:         #   for this user in user's homespace
1.553     albertel 4974: 	# - current conditional state info
1.325     www      4975: 	my $key=$uname.':'.$udom.':';
1.109     www      4976:         my $status=
1.299     matthew  4977: 	    &del('nohist_calculatedsheets',
1.391     matthew  4978: 		 [$key.'studentcalc:'],
1.620     albertel 4979: 		 $env{'course.'.$cid.'.domain'},
                   4980: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4981: 		.' '.
                   4982: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4983: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4984:         unless ($status eq 'ok ok') {
                   4985:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4986:                     $uname.' at '.$udom.' for '.
1.109     www      4987: 		    $symb.': '.$status);
1.133     albertel 4988:         }
1.553     albertel 4989: 	&delenv('user.state.'.$cid);
1.109     www      4990:     }
                   4991: }
                   4992: 
1.265     albertel 4993: sub get_scalar {
                   4994:     my ($string,$end) = @_;
                   4995:     my $value;
                   4996:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4997: 	$value = $1;
                   4998:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4999: 	$value = $1;
                   5000:     }
                   5001:     return &unescape($value);
                   5002: }
                   5003: 
                   5004: sub array2str {
                   5005:   my (@array) = @_;
                   5006:   my $result=&arrayref2str(\@array);
                   5007:   $result=~s/^__ARRAY_REF__//;
                   5008:   $result=~s/__END_ARRAY_REF__$//;
                   5009:   return $result;
                   5010: }
                   5011: 
1.204     albertel 5012: sub arrayref2str {
                   5013:   my ($arrayref) = @_;
1.265     albertel 5014:   my $result='__ARRAY_REF__';
1.204     albertel 5015:   foreach my $elem (@$arrayref) {
1.265     albertel 5016:     if(ref($elem) eq 'ARRAY') {
                   5017:       $result.=&arrayref2str($elem).'&';
                   5018:     } elsif(ref($elem) eq 'HASH') {
                   5019:       $result.=&hashref2str($elem).'&';
                   5020:     } elsif(ref($elem)) {
                   5021:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5022:     } else {
                   5023:       $result.=&escape($elem).'&';
                   5024:     }
                   5025:   }
                   5026:   $result=~s/\&$//;
1.265     albertel 5027:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5028:   return $result;
                   5029: }
                   5030: 
1.168     albertel 5031: sub hash2str {
1.204     albertel 5032:   my (%hash) = @_;
                   5033:   my $result=&hashref2str(\%hash);
1.265     albertel 5034:   $result=~s/^__HASH_REF__//;
                   5035:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5036:   return $result;
                   5037: }
                   5038: 
                   5039: sub hashref2str {
                   5040:   my ($hashref)=@_;
1.265     albertel 5041:   my $result='__HASH_REF__';
1.800     albertel 5042:   foreach my $key (sort(keys(%$hashref))) {
                   5043:     if (ref($key) eq 'ARRAY') {
                   5044:       $result.=&arrayref2str($key).'=';
                   5045:     } elsif (ref($key) eq 'HASH') {
                   5046:       $result.=&hashref2str($key).'=';
                   5047:     } elsif (ref($key)) {
1.265     albertel 5048:       $result.='=';
1.800     albertel 5049:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5050:     } else {
1.1132    raeburn  5051: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5052:     }
                   5053: 
1.800     albertel 5054:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5055:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5056:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5057:       $result.=&hashref2str($hashref->{$key}).'&';
                   5058:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5059:        $result.='&';
1.800     albertel 5060:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5061:     } else {
1.800     albertel 5062:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5063:     }
                   5064:   }
1.168     albertel 5065:   $result=~s/\&$//;
1.265     albertel 5066:   $result .= '__END_HASH_REF__';
1.168     albertel 5067:   return $result;
                   5068: }
                   5069: 
                   5070: sub str2hash {
1.265     albertel 5071:     my ($string)=@_;
                   5072:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5073:     return %$hash;
                   5074: }
                   5075: 
                   5076: sub str2hashref {
1.168     albertel 5077:   my ($string) = @_;
1.265     albertel 5078: 
                   5079:   my %hash;
                   5080: 
                   5081:   if($string !~ /^__HASH_REF__/) {
                   5082:       if (! ($string eq '' || !defined($string))) {
                   5083: 	  $hash{'error'}='Not hash reference';
                   5084:       }
                   5085:       return (\%hash, $string);
                   5086:   }
                   5087: 
                   5088:   $string =~ s/^__HASH_REF__//;
                   5089: 
                   5090:   while($string !~ /^__END_HASH_REF__/) {
                   5091:       #key
                   5092:       my $key='';
                   5093:       if($string =~ /^__HASH_REF__/) {
                   5094:           ($key, $string)=&str2hashref($string);
                   5095:           if(defined($key->{'error'})) {
                   5096:               $hash{'error'}='Bad data';
                   5097:               return (\%hash, $string);
                   5098:           }
                   5099:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5100:           ($key, $string)=&str2arrayref($string);
                   5101:           if($key->[0] eq 'Array reference error') {
                   5102:               $hash{'error'}='Bad data';
                   5103:               return (\%hash, $string);
                   5104:           }
                   5105:       } else {
                   5106:           $string =~ s/^(.*?)=//;
1.267     albertel 5107: 	  $key=&unescape($1);
1.265     albertel 5108:       }
                   5109:       $string =~ s/^=//;
                   5110: 
                   5111:       #value
                   5112:       my $value='';
                   5113:       if($string =~ /^__HASH_REF__/) {
                   5114:           ($value, $string)=&str2hashref($string);
                   5115:           if(defined($value->{'error'})) {
                   5116:               $hash{'error'}='Bad data';
                   5117:               return (\%hash, $string);
                   5118:           }
                   5119:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5120:           ($value, $string)=&str2arrayref($string);
                   5121:           if($value->[0] eq 'Array reference error') {
                   5122:               $hash{'error'}='Bad data';
                   5123:               return (\%hash, $string);
                   5124:           }
                   5125:       } else {
                   5126: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5127:       }
                   5128:       $string =~ s/^&//;
                   5129: 
                   5130:       $hash{$key}=$value;
1.204     albertel 5131:   }
1.265     albertel 5132: 
                   5133:   $string =~ s/^__END_HASH_REF__//;
                   5134: 
                   5135:   return (\%hash, $string);
1.204     albertel 5136: }
                   5137: 
                   5138: sub str2array {
1.265     albertel 5139:     my ($string)=@_;
                   5140:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5141:     return @$array;
                   5142: }
                   5143: 
                   5144: sub str2arrayref {
1.204     albertel 5145:   my ($string) = @_;
1.265     albertel 5146:   my @array;
                   5147: 
                   5148:   if($string !~ /^__ARRAY_REF__/) {
                   5149:       if (! ($string eq '' || !defined($string))) {
                   5150: 	  $array[0]='Array reference error';
                   5151:       }
                   5152:       return (\@array, $string);
                   5153:   }
                   5154: 
                   5155:   $string =~ s/^__ARRAY_REF__//;
                   5156: 
                   5157:   while($string !~ /^__END_ARRAY_REF__/) {
                   5158:       my $value='';
                   5159:       if($string =~ /^__HASH_REF__/) {
                   5160:           ($value, $string)=&str2hashref($string);
                   5161:           if(defined($value->{'error'})) {
                   5162:               $array[0] ='Array reference error';
                   5163:               return (\@array, $string);
                   5164:           }
                   5165:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5166:           ($value, $string)=&str2arrayref($string);
                   5167:           if($value->[0] eq 'Array reference error') {
                   5168:               $array[0] ='Array reference error';
                   5169:               return (\@array, $string);
                   5170:           }
                   5171:       } else {
                   5172: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5173:       }
                   5174:       $string =~ s/^&//;
                   5175: 
                   5176:       push(@array, $value);
1.191     harris41 5177:   }
1.265     albertel 5178: 
                   5179:   $string =~ s/^__END_ARRAY_REF__//;
                   5180: 
                   5181:   return (\@array, $string);
1.168     albertel 5182: }
                   5183: 
1.167     albertel 5184: # -------------------------------------------------------------------Temp Store
                   5185: 
1.168     albertel 5186: sub tmpreset {
                   5187:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5188:   if (!$symb) {
                   5189:     $symb=&symbread();
1.620     albertel 5190:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5191:   }
                   5192:   $symb=escape($symb);
                   5193: 
1.620     albertel 5194:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5195:   $namespace=~s/\//\_/g;
                   5196:   $namespace=~s/\W//g;
                   5197: 
1.620     albertel 5198:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5199:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5200:   if ($domain eq 'public' && $stuname eq 'public') {
                   5201:       $stuname=$ENV{'REMOTE_ADDR'};
                   5202:   }
1.1117    foxr     5203:   my $path=LONCAPA::tempdir();
1.168     albertel 5204:   my %hash;
                   5205:   if (tie(%hash,'GDBM_File',
                   5206: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5207: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5208:     foreach my $key (keys(%hash)) {
1.180     albertel 5209:       if ($key=~ /:$symb/) {
1.168     albertel 5210: 	delete($hash{$key});
                   5211:       }
                   5212:     }
                   5213:   }
                   5214: }
                   5215: 
1.167     albertel 5216: sub tmpstore {
1.168     albertel 5217:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5218: 
                   5219:   if (!$symb) {
                   5220:     $symb=&symbread();
1.620     albertel 5221:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5222:   }
                   5223:   $symb=escape($symb);
                   5224: 
                   5225:   if (!$namespace) {
                   5226:     # I don't think we would ever want to store this for a course.
                   5227:     # it seems this will only be used if we don't have a course.
1.620     albertel 5228:     #$namespace=$env{'request.course.id'};
1.168     albertel 5229:     #if (!$namespace) {
1.620     albertel 5230:       $namespace=$env{'request.state'};
1.168     albertel 5231:     #}
                   5232:   }
                   5233:   $namespace=~s/\//\_/g;
                   5234:   $namespace=~s/\W//g;
1.620     albertel 5235:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5236:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5237:   if ($domain eq 'public' && $stuname eq 'public') {
                   5238:       $stuname=$ENV{'REMOTE_ADDR'};
                   5239:   }
1.168     albertel 5240:   my $now=time;
                   5241:   my %hash;
1.1117    foxr     5242:   my $path=LONCAPA::tempdir();
1.168     albertel 5243:   if (tie(%hash,'GDBM_File',
                   5244: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5245: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5246:     $hash{"version:$symb"}++;
                   5247:     my $version=$hash{"version:$symb"};
                   5248:     my $allkeys=''; 
                   5249:     foreach my $key (keys(%$storehash)) {
                   5250:       $allkeys.=$key.':';
1.591     albertel 5251:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5252:     }
                   5253:     $hash{"$version:$symb:timestamp"}=$now;
                   5254:     $allkeys.='timestamp';
                   5255:     $hash{"$version:keys:$symb"}=$allkeys;
                   5256:     if (untie(%hash)) {
                   5257:       return 'ok';
                   5258:     } else {
                   5259:       return "error:$!";
                   5260:     }
                   5261:   } else {
                   5262:     return "error:$!";
                   5263:   }
                   5264: }
1.167     albertel 5265: 
1.168     albertel 5266: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5267: 
1.168     albertel 5268: sub tmprestore {
                   5269:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5270: 
1.168     albertel 5271:   if (!$symb) {
                   5272:     $symb=&symbread();
1.620     albertel 5273:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5274:   }
                   5275:   $symb=escape($symb);
                   5276: 
1.620     albertel 5277:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5278: 
1.620     albertel 5279:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5280:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5281:   if ($domain eq 'public' && $stuname eq 'public') {
                   5282:       $stuname=$ENV{'REMOTE_ADDR'};
                   5283:   }
1.168     albertel 5284:   my %returnhash;
                   5285:   $namespace=~s/\//\_/g;
                   5286:   $namespace=~s/\W//g;
                   5287:   my %hash;
1.1117    foxr     5288:   my $path=LONCAPA::tempdir();
1.168     albertel 5289:   if (tie(%hash,'GDBM_File',
                   5290: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5291: 	  &GDBM_READER(),0640)) {
1.168     albertel 5292:     my $version=$hash{"version:$symb"};
                   5293:     $returnhash{'version'}=$version;
                   5294:     my $scope;
                   5295:     for ($scope=1;$scope<=$version;$scope++) {
                   5296:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5297:       my @keys=split(/:/,$vkeys);
                   5298:       my $key;
                   5299:       $returnhash{"$scope:keys"}=$vkeys;
                   5300:       foreach $key (@keys) {
1.591     albertel 5301: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   5302: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 5303:       }
                   5304:     }
1.168     albertel 5305:     if (!(untie(%hash))) {
                   5306:       return "error:$!";
                   5307:     }
                   5308:   } else {
                   5309:     return "error:$!";
                   5310:   }
                   5311:   return %returnhash;
1.167     albertel 5312: }
                   5313: 
1.9       www      5314: # ----------------------------------------------------------------------- Store
                   5315: 
                   5316: sub store {
1.1172.2.64  raeburn  5317:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5318:     my $home='';
                   5319: 
1.168     albertel 5320:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5321: 
1.213     www      5322:     $symb=&symbclean($symb);
1.122     albertel 5323:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5324: 
1.620     albertel 5325:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5326:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5327: 
                   5328:     &devalidate($symb,$stuname,$domain);
1.109     www      5329: 
                   5330:     $symb=escape($symb);
1.187     www      5331:     if (!$namespace) { 
1.620     albertel 5332:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5333:           return ''; 
                   5334:        } 
                   5335:     }
1.620     albertel 5336:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5337: 
                   5338:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5339:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   5340: 
1.12      www      5341:     my $namevalue='';
1.800     albertel 5342:     foreach my $key (keys(%$storehash)) {
                   5343:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5344:     }
1.12      www      5345:     $namevalue=~s/\&$//;
1.187     www      5346:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64  raeburn  5347:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      5348: }
                   5349: 
1.47      www      5350: # -------------------------------------------------------------- Critical Store
                   5351: 
                   5352: sub cstore {
1.1172.2.64  raeburn  5353:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5354:     my $home='';
                   5355: 
1.168     albertel 5356:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5357: 
1.213     www      5358:     $symb=&symbclean($symb);
1.122     albertel 5359:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5360: 
1.620     albertel 5361:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5362:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5363: 
                   5364:     &devalidate($symb,$stuname,$domain);
1.109     www      5365: 
                   5366:     $symb=escape($symb);
1.187     www      5367:     if (!$namespace) { 
1.620     albertel 5368:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5369:           return ''; 
                   5370:        } 
                   5371:     }
1.620     albertel 5372:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5373: 
                   5374:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5375:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 5376: 
1.47      www      5377:     my $namevalue='';
1.800     albertel 5378:     foreach my $key (keys(%$storehash)) {
                   5379:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5380:     }
1.47      www      5381:     $namevalue=~s/\&$//;
1.187     www      5382:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      5383:     return critical
1.1172.2.64  raeburn  5384:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      5385: }
                   5386: 
1.9       www      5387: # --------------------------------------------------------------------- Restore
                   5388: 
                   5389: sub restore {
1.124     www      5390:     my ($symb,$namespace,$domain,$stuname) = @_;
                   5391:     my $home='';
                   5392: 
1.168     albertel 5393:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5394: 
1.122     albertel 5395:     if (!$symb) {
1.1172.2.26  raeburn  5396:         return if ($namespace eq 'courserequests');
                   5397:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 5398:     } else {
1.1172.2.26  raeburn  5399:         unless ($namespace eq 'courserequests') {
                   5400:             $symb=&escape(&symbclean($symb));
                   5401:         }
1.122     albertel 5402:     }
1.188     www      5403:     if (!$namespace) { 
1.620     albertel 5404:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      5405:           return ''; 
                   5406:        } 
                   5407:     }
1.620     albertel 5408:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5409:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   5410:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 5411:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   5412: 
1.12      www      5413:     my %returnhash=();
1.800     albertel 5414:     foreach my $line (split(/\&/,$answer)) {
                   5415: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 5416:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 5417:     }
1.75      www      5418:     my $version;
                   5419:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 5420:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   5421:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 5422:        }
1.75      www      5423:     }
1.13      www      5424:     return %returnhash;
1.34      www      5425: }
                   5426: 
                   5427: # ---------------------------------------------------------- Course Description
1.1118    foxr     5428: #
                   5429: #  
1.34      www      5430: 
                   5431: sub coursedescription {
1.731     albertel 5432:     my ($courseid,$args)=@_;
1.34      www      5433:     $courseid=~s/^\///;
1.49      www      5434:     $courseid=~s/\_/\//g;
1.34      www      5435:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 5436:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 5437:     my $normalid=$cdomain.'_'.$cnum;
                   5438:     # need to always cache even if we get errors otherwise we keep 
                   5439:     # trying and trying and trying to get the course description.
                   5440:     my %envhash=();
                   5441:     my %returnhash=();
1.731     albertel 5442:     
                   5443:     my $expiretime=600;
                   5444:     if ($env{'request.course.id'} eq $normalid) {
                   5445: 	$expiretime=120;
                   5446:     }
                   5447: 
                   5448:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   5449:     if (!$args->{'freshen_cache'}
                   5450: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   5451: 	foreach my $key (keys(%env)) {
                   5452: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   5453: 	    my ($setting) = $1;
                   5454: 	    $returnhash{$setting} = $env{$key};
                   5455: 	}
                   5456: 	return %returnhash;
                   5457:     }
                   5458: 
1.1118    foxr     5459:     # get the data again
                   5460: 
1.731     albertel 5461:     if (!$args->{'one_time'}) {
                   5462: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   5463:     }
1.811     albertel 5464: 
1.34      www      5465:     if ($chome ne 'no_host') {
1.302     albertel 5466:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 5467:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     5468: 	   my $username = $env{'user.name'}; # Defult username
                   5469: 	   if(defined $args->{'user'}) {
                   5470: 	       $username = $args->{'user'};
                   5471: 	   }
1.129     albertel 5472:            $returnhash{'home'}= $chome;
                   5473: 	   $returnhash{'domain'} = $cdomain;
                   5474: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  5475:            if (!defined($returnhash{'type'})) {
                   5476:                $returnhash{'type'} = 'Course';
                   5477:            }
1.130     albertel 5478:            while (my ($name,$value) = each %returnhash) {
1.53      www      5479:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 5480:            }
1.270     www      5481:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     5482:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     5483: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      5484:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   5485:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   5486:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      5487:        }
                   5488:     }
1.731     albertel 5489:     if (!$args->{'one_time'}) {
1.949     raeburn  5490: 	&appenv(\%envhash);
1.731     albertel 5491:     }
1.302     albertel 5492:     return %returnhash;
1.461     www      5493: }
                   5494: 
1.1080    raeburn  5495: sub update_released_required {
                   5496:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   5497:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   5498:         $cid = $env{'request.course.id'};
                   5499:         $cdom = $env{'course.'.$cid.'.domain'};
                   5500:         $cnum = $env{'course.'.$cid.'.num'};
                   5501:         $chome = $env{'course.'.$cid.'.home'};
                   5502:     }
                   5503:     if ($needsrelease) {
                   5504:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   5505:         my $needsupdate;
                   5506:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   5507:             $needsupdate = 1;
                   5508:         } else {
                   5509:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   5510:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   5511:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   5512:                 $needsupdate = 1;
                   5513:             }
                   5514:         }
                   5515:         if ($needsupdate) {
                   5516:             my %needshash = (
                   5517:                              'internal.releaserequired' => $needsrelease,
                   5518:                             );
                   5519:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   5520:             if ($putresult eq 'ok') {
                   5521:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   5522:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   5523:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   5524:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   5525:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   5526:                 }
                   5527:             }
                   5528:         }
                   5529:     }
                   5530:     return;
                   5531: }
                   5532: 
1.461     www      5533: # -------------------------------------------------See if a user is privileged
                   5534: 
                   5535: sub privileged {
1.1172.2.23  raeburn  5536:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5537:     my $now = time;
1.1172.2.23  raeburn  5538:     my $roles;
                   5539:     if (ref($possroles) eq 'ARRAY') {
                   5540:         $roles = $possroles;
                   5541:     } else {
                   5542:         $roles = ['dc','su'];
                   5543:     }
                   5544:     if (ref($possdomains) eq 'ARRAY') {
                   5545:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   5546:         foreach my $dom (@{$possdomains}) {
                   5547:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   5548:                 (ref($privileged{$dom}) eq 'HASH')) {
                   5549:                 foreach my $role (@{$roles}) {
                   5550:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5551:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5552:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5553:                             return 1 unless (($end && $end < $now) ||
                   5554:                                              ($start && $start > $now));
                   5555:                         }
                   5556:                     }
                   5557:                 }
                   5558:             }
                   5559:         }
                   5560:     } else {
                   5561:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   5562:         my $now = time;
1.1170    droeschl 5563: 
1.1172.2.58  raeburn  5564:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 5565:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  5566:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   5567:                 return 1 unless ($tend && $tend < $now)
                   5568:                         or ($tstart && $tstart > $now);
1.1170    droeschl 5569:             }
1.1172.2.23  raeburn  5570:         }
                   5571:     }
1.461     www      5572:     return 0;
1.9       www      5573: }
1.1       albertel 5574: 
1.1172.2.23  raeburn  5575: sub privileged_by_domain {
                   5576:     my ($domains,$roles) = @_;
                   5577:     my %privileged = ();
                   5578:     my $cachetime = 60*60*24;
                   5579:     my $now = time;
                   5580:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   5581:         return %privileged;
                   5582:     }
                   5583:     foreach my $dom (@{$domains}) {
                   5584:         next if (ref($privileged{$dom}) eq 'HASH');
                   5585:         my $needroles;
                   5586:         foreach my $role (@{$roles}) {
                   5587:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   5588:             if (defined($cached)) {
                   5589:                 if (ref($result) eq 'HASH') {
                   5590:                     $privileged{$dom}{$role} = $result;
                   5591:                 }
                   5592:             } else {
                   5593:                 $needroles = 1;
                   5594:             }
                   5595:         }
                   5596:         if ($needroles) {
                   5597:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   5598:             $privileged{$dom} = {};
                   5599:             foreach my $server (keys(%dompersonnel)) {
                   5600:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   5601:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   5602:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   5603:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   5604:                         next if ($end && $end < $now);
                   5605:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   5606:                             $dompersonnel{$server}{$item};
                   5607:                     }
                   5608:                 }
                   5609:             }
                   5610:             if (ref($privileged{$dom}) eq 'HASH') {
                   5611:                 foreach my $role (@{$roles}) {
                   5612:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5613:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   5614:                     } else {
                   5615:                         my %hash = ();
                   5616:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   5617:                     }
                   5618:                 }
                   5619:             }
                   5620:         }
                   5621:     }
                   5622:     return %privileged;
                   5623: }
                   5624: 
1.103     harris41 5625: # -------------------------------------------------------- Get user privileges
1.11      www      5626: 
                   5627: sub rolesinit {
1.1169    droeschl 5628:     my ($domain, $username) = @_;
                   5629:     my %userroles = ('user.login.time' => time);
                   5630:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   5631: 
                   5632:     # firstaccess and timerinterval are related to timed maps/resources. 
                   5633:     # also, blocking can be triggered by an activating timer
                   5634:     # it's saved in the user's %env.
                   5635:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   5636:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   5637:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   5638:         %timerintchk, %timerintenv);
                   5639: 
1.1162    raeburn  5640:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 5641:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  5642:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   5643:     }
1.1169    droeschl 5644: 
1.1162    raeburn  5645:     foreach my $key (keys(%timerinterval)) {
                   5646:         my ($cid,$rest) = split(/\0/,$key);
                   5647:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   5648:     }
1.1169    droeschl 5649: 
1.11      www      5650:     my %allroles=();
1.1162    raeburn  5651:     my %allgroups=();
1.11      www      5652: 
1.1172.2.58  raeburn  5653:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 5654:         my $role = $rolesdump{$area};
                   5655:         $area =~ s/\_\w\w$//;
                   5656: 
                   5657:         my ($trole, $tend, $tstart, $group_privs);
                   5658: 
                   5659:         if ($role =~ /^cr/) {
                   5660:         # Custom role, defined by a user 
                   5661:         # e.g., user.role.cr/msu/smith/mynewrole
                   5662:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5663:                 $trole = $1;
                   5664:                 ($tend, $tstart) = split('_', $2);
                   5665:             } else {
                   5666:                 $trole = $role;
                   5667:             }
                   5668:         } elsif ($role =~ m|^gr/|) {
                   5669:         # Role of member in a group, defined within a course/community
                   5670:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5671:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5672:             next if $tstart eq '-1';
                   5673:             ($trole, $group_privs) = split(/\//, $trole);
                   5674:             $group_privs = &unescape($group_privs);
                   5675:         } else {
                   5676:         # Just a normal role, defined in roles.tab
                   5677:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5678:         }
                   5679: 
                   5680:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5681:                  $username);
                   5682:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5683: 
                   5684:         # role expired or not available yet?
                   5685:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5686:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5687: 
                   5688:         next if $area eq '' or $trole eq '';
                   5689: 
                   5690:         my $spec = "$trole.$area";
                   5691:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5692: 
                   5693:         if ($trole =~ /^cr\//) {
                   5694:         # Custom role, defined by a user
                   5695:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5696:         } elsif ($trole eq 'gr') {
                   5697:         # Role of a member in a group, defined within a course/community
                   5698:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5699:             next;
                   5700:         } else {
                   5701:         # Normal role, defined in roles.tab
                   5702:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5703:         }
                   5704: 
                   5705:         my $cid = $tdomain.'_'.$trest;
                   5706:         unless ($firstaccchk{$cid}) {
                   5707:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5708:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5709:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5710:                         $coursetimerstarts{$cid}{$item}; 
                   5711:                 }
                   5712:             }
                   5713:             $firstaccchk{$cid} = 1;
                   5714:         }
                   5715:         unless ($timerintchk{$cid}) {
                   5716:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5717:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5718:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5719:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5720:                 }
1.12      www      5721:             }
1.1169    droeschl 5722:             $timerintchk{$cid} = 1;
1.191     harris41 5723:         }
1.11      www      5724:     }
1.1169    droeschl 5725: 
1.1172.2.91  raeburn  5726:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   5727:                                                           \%allroles, \%allgroups);
1.1169    droeschl 5728:     $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91  raeburn  5729:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 5730: 
1.1162    raeburn  5731:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5732: }
                   5733: 
1.567     raeburn  5734: sub set_arearole {
1.1172.2.19  raeburn  5735:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   5736:     unless ($nolog) {
1.567     raeburn  5737: # log the associated role with the area
1.1172.2.19  raeburn  5738:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   5739:     }
1.743     albertel 5740:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5741: }
                   5742: 
                   5743: sub custom_roleprivs {
                   5744:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5745:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40  raeburn  5746:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 5747:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5748:         my ($rdummy,$roledef)=
                   5749:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5750:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5751:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5752:             if (defined($syspriv)) {
1.1043    raeburn  5753:                 if ($trest =~ /^$match_community$/) {
                   5754:                     $syspriv =~ s/bre\&S//; 
                   5755:                 }
1.567     raeburn  5756:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5757:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5758:             }
                   5759:             if ($tdomain ne '') {
                   5760:                 if (defined($dompriv)) {
                   5761:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5762:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5763:                 }
                   5764:                 if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89  raeburn  5765:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   5766:                         my $rolename = $1;
                   5767:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   5768:                     }
1.567     raeburn  5769:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5770:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5771:                 }
                   5772:             }
                   5773:         }
                   5774:     }
                   5775: }
                   5776: 
1.1172.2.89  raeburn  5777: sub course_adhocrole_privs {
                   5778:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   5779:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   5780:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   5781:         my (%currprivs,%storeprivs);
                   5782:         foreach my $item (split(/:/,$coursepriv)) {
                   5783:             my ($priv,$restrict) = split(/\&/,$item);
                   5784:             $currprivs{$priv} = $restrict;
                   5785:         }
                   5786:         my (%possadd,%possremove,%full);
                   5787:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   5788:             my ($priv,$restrict)=split(/\&/,$item);
                   5789:             $full{$priv} = $restrict;
                   5790:         }
                   5791:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   5792:              next if ($item eq '');
                   5793:              my ($rule,$rest) = split(/=/,$item);
                   5794:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   5795:              foreach my $priv (split(/:/,$rest)) {
                   5796:                  if ($priv ne '') {
                   5797:                      if ($rule eq 'off') {
                   5798:                          $possremove{$priv} = 1;
                   5799:                      } else {
                   5800:                          $possadd{$priv} = 1;
                   5801:                      }
                   5802:                  }
                   5803:              }
                   5804:          }
                   5805:          foreach my $priv (sort(keys(%full))) {
                   5806:              if (exists($currprivs{$priv})) {
                   5807:                  unless (exists($possremove{$priv})) {
                   5808:                      $storeprivs{$priv} = $currprivs{$priv};
                   5809:                  }
                   5810:              } elsif (exists($possadd{$priv})) {
                   5811:                  $storeprivs{$priv} = $full{$priv};
                   5812:              }
                   5813:          }
                   5814:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   5815:      }
                   5816:      return $coursepriv;
                   5817: }
                   5818: 
1.678     raeburn  5819: sub group_roleprivs {
                   5820:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   5821:     my $access = 1;
                   5822:     my $now = time;
                   5823:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   5824:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   5825:     if ($access) {
1.811     albertel 5826:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  5827:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   5828:     }
                   5829: }
1.567     raeburn  5830: 
                   5831: sub standard_roleprivs {
                   5832:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   5833:     if (defined($pr{$trole.':s'})) {
                   5834:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   5835:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   5836:     }
                   5837:     if ($tdomain ne '') {
                   5838:         if (defined($pr{$trole.':d'})) {
                   5839:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5840:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5841:         }
                   5842:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   5843:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   5844:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   5845:         }
                   5846:     }
                   5847: }
                   5848: 
                   5849: sub set_userprivs {
1.1064    raeburn  5850:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  5851:     my $author=0;
                   5852:     my $adv=0;
1.1172.2.91  raeburn  5853:     my $rar=0;
1.678     raeburn  5854:     my %grouproles = ();
                   5855:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  5856:         my @groupkeys; 
1.1000    raeburn  5857:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  5858:             push(@groupkeys,$role);
                   5859:         }
                   5860:         if (ref($groups_roles) eq 'HASH') {
                   5861:             foreach my $key (keys(%{$groups_roles})) {
                   5862:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   5863:                     push(@groupkeys,$key);
                   5864:                 }
                   5865:             }
                   5866:         }
                   5867:         if (@groupkeys > 0) {
                   5868:             foreach my $role (@groupkeys) {
                   5869:                 my ($trole,$area,$sec,$extendedarea);
                   5870:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   5871:                     $trole = $1;
                   5872:                     $area = $2;
                   5873:                     $sec = $3;
                   5874:                     $extendedarea = $area.$sec;
                   5875:                     if (exists($$allgroups{$area})) {
                   5876:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   5877:                             my $spec = $trole.'.'.$extendedarea;
                   5878:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  5879:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  5880:                         }
1.678     raeburn  5881:                     }
                   5882:                 }
                   5883:             }
                   5884:         }
                   5885:     }
1.800     albertel 5886:     foreach my $group (keys(%grouproles)) {
                   5887:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  5888:     }
1.800     albertel 5889:     foreach my $role (keys(%{$allroles})) {
                   5890:         my %thesepriv;
1.941     raeburn  5891:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 5892:         foreach my $item (split(/:/,$$allroles{$role})) {
                   5893:             if ($item ne '') {
                   5894:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  5895:                 if ($restrictions eq '') {
                   5896:                     $thesepriv{$privilege}='F';
                   5897:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   5898:                     $thesepriv{$privilege}.=$restrictions;
                   5899:                 }
                   5900:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91  raeburn  5901:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  5902:             }
                   5903:         }
                   5904:         my $thesestr='';
1.1104    raeburn  5905:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 5906: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   5907: 	}
                   5908:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  5909:     }
1.1172.2.91  raeburn  5910:     return ($author,$adv,$rar);
1.567     raeburn  5911: }
                   5912: 
1.994     raeburn  5913: sub role_status {
1.1104    raeburn  5914:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  5915:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40  raeburn  5916:         my ($one,$two) = split(m{\./},$rolekey,2);
                   5917:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  5918:         unless (!defined($$role) || $$role eq '') {
1.1172.2.40  raeburn  5919:             $$where = '/'.$two;
1.994     raeburn  5920:             $$trolecode=$$role.'.'.$$where;
                   5921:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   5922:             $$tstatus='is';
1.1104    raeburn  5923:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  5924:                 $$tstatus='future';
1.1034    raeburn  5925:                 if ($$tstart<$now) {
                   5926:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  5927:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  5928:                             my (%allroles,%allgroups,$group_privs,
                   5929:                                 %groups_roles,@rolecodes);
1.1002    raeburn  5930:                             my %userroles = (
                   5931:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   5932:                             );
1.1064    raeburn  5933:                             @rolecodes = ('cm'); 
1.1002    raeburn  5934:                             my $spec=$$role.'.'.$$where;
                   5935:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   5936:                             if ($$role =~ /^cr\//) {
                   5937:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  5938:                                 push(@rolecodes,'cr');
1.1002    raeburn  5939:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  5940:                                 push(@rolecodes,$$role);
1.1002    raeburn  5941:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   5942:                                                     $env{'user.name'});
1.1064    raeburn  5943:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  5944:                                 (undef,my $group_privs) = split(/\//,$trole);
                   5945:                                 $group_privs = &unescape($group_privs);
                   5946:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  5947:                                 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  5948:                                 &get_groups_roles($tdomain,$trest,
                   5949:                                                   \%course_roles,\@rolecodes,
                   5950:                                                   \%groups_roles);
1.1002    raeburn  5951:                             } else {
1.1064    raeburn  5952:                                 push(@rolecodes,$$role);
1.1002    raeburn  5953:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   5954:                             }
1.1172.2.91  raeburn  5955:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   5956:                                                                    \%groups_roles);
1.1064    raeburn  5957:                             &appenv(\%userroles,\@rolecodes);
1.1172.2.92  raeburn  5958:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  5959:                         }
                   5960:                     }
1.1034    raeburn  5961:                     $$tstatus = 'is';
1.1002    raeburn  5962:                 }
1.994     raeburn  5963:             }
                   5964:             if ($$tend) {
1.1104    raeburn  5965:                 if ($$tend<$update) {
1.994     raeburn  5966:                     $$tstatus='expired';
                   5967:                 } elsif ($$tend<$now) {
                   5968:                     $$tstatus='will_not';
                   5969:                 }
                   5970:             }
                   5971:         }
                   5972:     }
                   5973: }
                   5974: 
1.1104    raeburn  5975: sub get_groups_roles {
                   5976:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   5977:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   5978:                   (ref($rolecodes) eq 'ARRAY') && 
                   5979:                   (ref($groups_roles) eq 'HASH')); 
                   5980:     if (keys(%{$cdom_courseroles}) > 0) {
                   5981:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   5982:         if ($cdom ne '' && $cnum ne '') {
                   5983:             foreach my $key (keys(%{$cdom_courseroles})) {
                   5984:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   5985:                     my $crsrole = $1;
                   5986:                     my $crssec = $2;
                   5987:                     if ($crsrole =~ /^cr/) {
                   5988:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   5989:                             push(@{$rolecodes},'cr');
                   5990:                         }
                   5991:                     } else {
                   5992:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   5993:                             push(@{$rolecodes},$crsrole);
                   5994:                         }
                   5995:                     }
                   5996:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   5997:                     if ($crssec ne '') {
                   5998:                         $rolekey .= "/$crssec";
                   5999:                     }
                   6000:                     $rolekey .= './';
                   6001:                     $groups_roles->{$rolekey} = $rolecodes;
                   6002:                 }
                   6003:             }
                   6004:         }
                   6005:     }
                   6006:     return;
                   6007: }
                   6008: 
                   6009: sub delete_env_groupprivs {
                   6010:     my ($where,$courseroles,$possroles) = @_;
                   6011:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6012:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6013:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6014:         %{$courseroles->{$udom}} =
                   6015:             &get_my_roles('','','userroles',['active'],
                   6016:                           $possroles,[$udom],1);
                   6017:     }
                   6018:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6019:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6020:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6021:             my $area = '/'.$cdom.'/'.$cnum;
                   6022:             my $privkey = "user.priv.$crsrole.$area";
                   6023:             if ($crssec ne '') {
                   6024:                 $privkey .= '/'.$crssec;
                   6025:             }
                   6026:             $privkey .= ".$area/$group";
                   6027:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6028:         }
                   6029:     }
                   6030:     return;
                   6031: }
                   6032: 
1.994     raeburn  6033: sub check_adhoc_privs {
1.1172.2.86  raeburn  6034:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6035:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86  raeburn  6036:     if ($sec) {
                   6037:         $cckey .= '/'.$sec;
                   6038:     }
1.1172.2.9  raeburn  6039:     my $setprivs;
1.994     raeburn  6040:     if ($env{$cckey}) {
                   6041:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6042:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6043:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86  raeburn  6044:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6045:             $setprivs = 1;
1.994     raeburn  6046:         }
                   6047:     } else {
1.1172.2.87  raeburn  6048:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6049:         $setprivs = 1;
1.994     raeburn  6050:     }
1.1172.2.9  raeburn  6051:     return $setprivs;
1.994     raeburn  6052: }
                   6053: 
                   6054: sub set_adhoc_privileges {
1.1172.2.84  raeburn  6055: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86  raeburn  6056:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6057:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86  raeburn  6058:     if ($sec ne '') {
                   6059:         $area .= '/'.$sec;
                   6060:     }
1.994     raeburn  6061:     my $spec = $role.'.'.$area;
                   6062:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  6063:                                   $env{'user.name'},1);
1.1172.2.84  raeburn  6064:     my %rolehash = ();
1.1172.2.89  raeburn  6065:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6066:         my $rolename = $1;
1.1172.2.84  raeburn  6067:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89  raeburn  6068:         my %domdef = &get_domain_defaults($dcdom);
                   6069:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6070:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6071:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6072:             }
                   6073:         }
1.1172.2.84  raeburn  6074:     } else {
                   6075:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6076:     }
1.1172.2.91  raeburn  6077:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6078:     &appenv(\%userroles,[$role,'cm']);
1.1172.2.92  raeburn  6079:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088    raeburn  6080:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   6081:         &appenv( {'request.role'        => $spec,
                   6082:                   'request.role.domain' => $dcdom,
1.1172.2.89  raeburn  6083:                   'request.course.sec'  => $sec, 
1.1088    raeburn  6084:                  }
                   6085:                );
                   6086:         my $tadv=0;
                   6087:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6088:         &appenv({'request.role.adv'    => $tadv});
                   6089:     }
1.994     raeburn  6090: }
                   6091: 
1.12      www      6092: # --------------------------------------------------------------- get interface
                   6093: 
                   6094: sub get {
1.131     albertel 6095:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6096:    my $items='';
1.800     albertel 6097:    foreach my $item (@$storearr) {
                   6098:        $items.=&escape($item).'&';
1.191     harris41 6099:    }
1.12      www      6100:    $items=~s/\&$//;
1.620     albertel 6101:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6102:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6103:    my $uhome=&homeserver($uname,$udomain);
                   6104: 
1.133     albertel 6105:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6106:    my @pairs=split(/\&/,$rep);
1.273     albertel 6107:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6108:      return @pairs;
                   6109:    }
1.15      www      6110:    my %returnhash=();
1.42      www      6111:    my $i=0;
1.800     albertel 6112:    foreach my $item (@$storearr) {
                   6113:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6114:       $i++;
1.191     harris41 6115:    }
1.15      www      6116:    return %returnhash;
1.27      www      6117: }
                   6118: 
                   6119: # --------------------------------------------------------------- del interface
                   6120: 
                   6121: sub del {
1.133     albertel 6122:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6123:    my $items='';
1.800     albertel 6124:    foreach my $item (@$storearr) {
                   6125:        $items.=&escape($item).'&';
1.191     harris41 6126:    }
1.984     neumanie 6127: 
1.27      www      6128:    $items=~s/\&$//;
1.620     albertel 6129:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6130:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6131:    my $uhome=&homeserver($uname,$udomain);
                   6132:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6133: }
                   6134: 
                   6135: # -------------------------------------------------------------- dump interface
                   6136: 
1.1172.2.22  raeburn  6137: sub unserialize {
                   6138:     my ($rep, $escapedkeys) = @_;
                   6139: 
                   6140:     return {} if $rep =~ /^error/;
                   6141: 
                   6142:     my %returnhash=();
                   6143:     foreach my $item (split(/\&/,$rep)) {
                   6144:         my ($key, $value) = split(/=/, $item, 2);
                   6145:         $key = unescape($key) unless $escapedkeys;
                   6146:         next if $key =~ /^error: 2 /;
                   6147:         $returnhash{$key} = &thaw_unescape($value);
                   6148:     }
                   6149:     return \%returnhash;
                   6150: }
                   6151: 
                   6152: # see Lond::dump_with_regexp
                   6153: # if $escapedkeys hash keys won't get unescaped.
1.15      www      6154: sub dump {
1.1172.2.22  raeburn  6155:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 6156:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6157:     if (!$uname) { $uname=$env{'user.name'}; }
                   6158:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 6159: 
1.1172.2.55  raeburn  6160:     if ($regexp) {
                   6161:         $regexp=&escape($regexp);
                   6162:     } else {
                   6163:         $regexp='.';
                   6164:     }
1.1172.2.22  raeburn  6165:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   6166:         # user is hosted on this machine
1.1172.2.55  raeburn  6167:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  6168:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  6169:         return %{&unserialize($reply, $escapedkeys)};
                   6170:     }
1.1166    raeburn  6171:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 6172:     my @pairs=split(/\&/,$rep);
                   6173:     my %returnhash=();
1.1098    foxr     6174:     if (!($rep =~ /^error/ )) {
                   6175: 	foreach my $item (@pairs) {
                   6176: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  6177:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     6178: 	    next if ($key =~ /^error: 2 /);
                   6179: 	    $returnhash{$key}=&thaw_unescape($value);
                   6180: 	}
1.755     albertel 6181:     }
                   6182:     return %returnhash;
1.407     www      6183: }
                   6184: 
1.1098    foxr     6185: 
1.717     albertel 6186: # --------------------------------------------------------- dumpstore interface
                   6187: 
                   6188: sub dumpstore {
                   6189:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  6190:    # same as dump but keys must be escaped. They may contain colon separated
                   6191:    # lists of values that may themself contain colons (e.g. symbs).
                   6192:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 6193: }
                   6194: 
1.407     www      6195: # -------------------------------------------------------------- keys interface
                   6196: 
                   6197: sub getkeys {
                   6198:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 6199:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6200:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      6201:    my $uhome=&homeserver($uname,$udomain);
                   6202:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   6203:    my @keyarray=();
1.800     albertel 6204:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  6205:       next if ($key =~ /^error: 2 /);
1.800     albertel 6206:       push(@keyarray,&unescape($key));
1.407     www      6207:    }
                   6208:    return @keyarray;
1.318     matthew  6209: }
                   6210: 
1.319     matthew  6211: # --------------------------------------------------------------- currentdump
                   6212: sub currentdump {
1.328     matthew  6213:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 6214:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   6215:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   6216:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  6217:    my $uhome = &homeserver($sname,$sdom);
1.1172.2.50  raeburn  6218:    my $rep;
                   6219: 
                   6220:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   6221:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
                   6222:                    $courseid)));
                   6223:    } else {
                   6224:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6225:    }
                   6226: 
1.318     matthew  6227:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6228:    #
1.318     matthew  6229:    my %returnhash=();
1.319     matthew  6230:    #
1.1172.2.93.4  2(raebur 6231:7):    if ($rep eq 'unknown_cmd') { 
1.319     matthew  6232:        # an old lond will not know currentdump
                   6233:        # Do a dump and make it look like a currentdump
1.822     albertel 6234:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6235:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6236:        my %hash = @tmp;
                   6237:        @tmp=();
1.424     matthew  6238:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6239:    } else {
                   6240:        my @pairs=split(/\&/,$rep);
1.800     albertel 6241:        foreach my $pair (@pairs) {
                   6242:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6243:            my ($symb,$param) = split(/:/,$key);
                   6244:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6245:                                                         &thaw_unescape($value);
1.319     matthew  6246:        }
1.191     harris41 6247:    }
1.12      www      6248:    return %returnhash;
1.424     matthew  6249: }
                   6250: 
                   6251: sub convert_dump_to_currentdump{
                   6252:     my %hash = %{shift()};
                   6253:     my %returnhash;
                   6254:     # Code ripped from lond, essentially.  The only difference
                   6255:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6256:     # we might run in to problems with parameter names =~ /^v\./
                   6257:     while (my ($key,$value) = each(%hash)) {
                   6258:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6259: 	$symb  = &unescape($symb);
                   6260: 	$param = &unescape($param);
1.424     matthew  6261:         next if ($v eq 'version' || $symb eq 'keys');
                   6262:         next if (exists($returnhash{$symb}) &&
                   6263:                  exists($returnhash{$symb}->{$param}) &&
                   6264:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6265:         $returnhash{$symb}->{$param}=$value;
                   6266:         $returnhash{$symb}->{'v.'.$param}=$v;
                   6267:     }
                   6268:     #
                   6269:     # Remove all of the keys in the hashes which keep track of
                   6270:     # the version of the parameter.
                   6271:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   6272:         # use a foreach because we are going to delete from the hash.
                   6273:         foreach my $key (keys(%$param_hash)) {
                   6274:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   6275:         }
                   6276:     }
                   6277:     return \%returnhash;
1.12      www      6278: }
                   6279: 
1.627     albertel 6280: # ------------------------------------------------------ critical inc interface
                   6281: 
                   6282: sub cinc {
                   6283:     return &inc(@_,'critical');
                   6284: }
                   6285: 
1.449     matthew  6286: # --------------------------------------------------------------- inc interface
                   6287: 
                   6288: sub inc {
1.627     albertel 6289:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 6290:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6291:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  6292:     my $uhome=&homeserver($uname,$udomain);
                   6293:     my $items='';
                   6294:     if (! ref($store)) {
                   6295:         # got a single value, so use that instead
                   6296:         $items = &escape($store).'=&';
                   6297:     } elsif (ref($store) eq 'SCALAR') {
                   6298:         $items = &escape($$store).'=&';        
                   6299:     } elsif (ref($store) eq 'ARRAY') {
                   6300:         $items = join('=&',map {&escape($_);} @{$store});
                   6301:     } elsif (ref($store) eq 'HASH') {
                   6302:         while (my($key,$value) = each(%{$store})) {
                   6303:             $items.= &escape($key).'='.&escape($value).'&';
                   6304:         }
                   6305:     }
                   6306:     $items=~s/\&$//;
1.627     albertel 6307:     if ($critical) {
                   6308: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6309:     } else {
                   6310: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6311:     }
1.449     matthew  6312: }
                   6313: 
1.12      www      6314: # --------------------------------------------------------------- put interface
                   6315: 
                   6316: sub put {
1.134     albertel 6317:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6318:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6319:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6320:    my $uhome=&homeserver($uname,$udomain);
1.12      www      6321:    my $items='';
1.800     albertel 6322:    foreach my $item (keys(%$storehash)) {
                   6323:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6324:    }
1.12      www      6325:    $items=~s/\&$//;
1.134     albertel 6326:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      6327: }
                   6328: 
1.631     albertel 6329: # ------------------------------------------------------------ newput interface
                   6330: 
                   6331: sub newput {
                   6332:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   6333:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6334:    if (!$uname) { $uname=$env{'user.name'}; }
                   6335:    my $uhome=&homeserver($uname,$udomain);
                   6336:    my $items='';
                   6337:    foreach my $key (keys(%$storehash)) {
                   6338:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   6339:    }
                   6340:    $items=~s/\&$//;
                   6341:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   6342: }
                   6343: 
                   6344: # ---------------------------------------------------------  putstore interface
                   6345: 
1.524     raeburn  6346: sub putstore {
1.1172.2.59  raeburn  6347:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 6348:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6349:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  6350:    my $uhome=&homeserver($uname,$udomain);
                   6351:    my $items='';
1.715     albertel 6352:    foreach my $key (keys(%$storehash)) {
                   6353:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  6354:    }
1.715     albertel 6355:    $items=~s/\&$//;
1.716     albertel 6356:    my $esc_symb=&escape($symb);
                   6357:    my $esc_v=&escape($version);
1.715     albertel 6358:    my $reply =
1.716     albertel 6359:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 6360: 	      $uhome);
1.1172.2.59  raeburn  6361:    if (($tolog) && ($reply eq 'ok')) {
                   6362:        my $namevalue='';
                   6363:        foreach my $key (keys(%{$storehash})) {
                   6364:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   6365:        }
                   6366:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   6367:                      '&host='.&escape($perlvar{'lonHostID'}).
                   6368:                      '&version='.$esc_v.
                   6369:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   6370:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   6371:    }
1.715     albertel 6372:    if ($reply eq 'unknown_cmd') {
1.716     albertel 6373:        # gfall back to way things use to be done
1.715     albertel 6374:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   6375: 			    $uname);
1.524     raeburn  6376:    }
1.715     albertel 6377:    return $reply;
                   6378: }
                   6379: 
                   6380: sub old_putstore {
1.716     albertel 6381:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   6382:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6383:     if (!$uname) { $uname=$env{'user.name'}; }
                   6384:     my $uhome=&homeserver($uname,$udomain);
                   6385:     my %newstorehash;
1.800     albertel 6386:     foreach my $item (keys(%$storehash)) {
                   6387: 	my $key = $version.':'.&escape($symb).':'.$item;
                   6388: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 6389:     }
                   6390:     my $items='';
                   6391:     my %allitems = ();
1.800     albertel 6392:     foreach my $item (keys(%newstorehash)) {
                   6393: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 6394: 	    my $key = $1.':keys:'.$2;
                   6395: 	    $allitems{$key} .= $3.':';
                   6396: 	}
1.800     albertel 6397: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 6398:     }
1.800     albertel 6399:     foreach my $item (keys(%allitems)) {
                   6400: 	$allitems{$item} =~ s/\:$//;
                   6401: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 6402:     }
                   6403:     $items=~s/\&$//;
                   6404:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  6405: }
                   6406: 
1.47      www      6407: # ------------------------------------------------------ critical put interface
                   6408: 
                   6409: sub cput {
1.134     albertel 6410:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6411:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6412:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6413:    my $uhome=&homeserver($uname,$udomain);
1.47      www      6414:    my $items='';
1.800     albertel 6415:    foreach my $item (keys(%$storehash)) {
                   6416:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6417:    }
1.47      www      6418:    $items=~s/\&$//;
1.134     albertel 6419:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6420: }
                   6421: 
                   6422: # -------------------------------------------------------------- eget interface
                   6423: 
                   6424: sub eget {
1.133     albertel 6425:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6426:    my $items='';
1.800     albertel 6427:    foreach my $item (@$storearr) {
                   6428:        $items.=&escape($item).'&';
1.191     harris41 6429:    }
1.12      www      6430:    $items=~s/\&$//;
1.620     albertel 6431:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6432:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6433:    my $uhome=&homeserver($uname,$udomain);
                   6434:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6435:    my @pairs=split(/\&/,$rep);
                   6436:    my %returnhash=();
1.42      www      6437:    my $i=0;
1.800     albertel 6438:    foreach my $item (@$storearr) {
                   6439:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6440:       $i++;
1.191     harris41 6441:    }
1.12      www      6442:    return %returnhash;
                   6443: }
                   6444: 
1.667     albertel 6445: # ------------------------------------------------------------ tmpput interface
                   6446: sub tmpput {
1.802     raeburn  6447:     my ($storehash,$server,$context)=@_;
1.667     albertel 6448:     my $items='';
1.800     albertel 6449:     foreach my $item (keys(%$storehash)) {
                   6450: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 6451:     }
                   6452:     $items=~s/\&$//;
1.802     raeburn  6453:     if (defined($context)) {
                   6454:         $items .= ':'.&escape($context);
                   6455:     }
1.667     albertel 6456:     return &reply("tmpput:$items",$server);
                   6457: }
                   6458: 
                   6459: # ------------------------------------------------------------ tmpget interface
                   6460: sub tmpget {
1.688     albertel 6461:     my ($token,$server)=@_;
                   6462:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6463:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 6464:     my %returnhash;
1.1172.2.85  raeburn  6465:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   6466:         return %returnhash;
                   6467:     }
1.667     albertel 6468:     foreach my $item (split(/\&/,$rep)) {
                   6469: 	my ($key,$value)=split(/=/,$item);
                   6470: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   6471:     }
                   6472:     return %returnhash;
                   6473: }
                   6474: 
1.1113    raeburn  6475: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 6476: sub tmpdel {
                   6477:     my ($token,$server)=@_;
                   6478:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6479:     return &reply("tmpdel:$token",$server);
                   6480: }
                   6481: 
1.1172.2.13  raeburn  6482: # ------------------------------------------------------------ get_timebased_id
                   6483: 
                   6484: sub get_timebased_id {
                   6485:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   6486:         $maxtries) = @_;
                   6487:     my ($newid,$error,$dellock);
                   6488:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   6489:         return ('','ok','invalid call to get suffix');
                   6490:     }
                   6491: 
                   6492: # set defaults for any optional args for which values were not supplied
                   6493:     if ($who eq '') {
                   6494:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   6495:     }
                   6496:     if (!$locktries) {
                   6497:         $locktries = 3;
                   6498:     }
                   6499:     if (!$maxtries) {
                   6500:         $maxtries = 10;
                   6501:     }
                   6502: 
                   6503:     if (($cdom eq '') || ($cnum eq '')) {
                   6504:         if ($env{'request.course.id'}) {
                   6505:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6506:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6507:         }
                   6508:         if (($cdom eq '') || ($cnum eq '')) {
                   6509:             return ('','ok','call to get suffix not in course context');
                   6510:         }
                   6511:     }
                   6512: 
                   6513: # construct locking item
                   6514:     my $lockhash = {
                   6515:                       $prefix."\0".'locked_'.$keyid => $who,
                   6516:                    };
                   6517:     my $tries = 0;
                   6518: 
                   6519: # attempt to get lock on nohist_$namespace file
                   6520:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6521:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   6522:         $tries ++;
                   6523:         sleep 1;
                   6524:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6525:     }
                   6526: 
                   6527: # attempt to get unique identifier, based on current timestamp
                   6528:     if ($gotlock eq 'ok') {
                   6529:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   6530:         my $id = time;
                   6531:         $newid = $id;
1.1172.2.56  raeburn  6532:         if ($idtype eq 'addcode') {
                   6533:             $newid .= &sixnum_code();
                   6534:         }
1.1172.2.13  raeburn  6535:         my $idtries = 0;
                   6536:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   6537:             if ($idtype eq 'concat') {
                   6538:                 $newid = $id.$idtries;
1.1172.2.56  raeburn  6539:             } elsif ($idtype eq 'addcode') {
                   6540:                 $newid = $newid.&sixnum_code();
1.1172.2.13  raeburn  6541:             } else {
                   6542:                 $newid ++;
                   6543:             }
                   6544:             $idtries ++;
                   6545:         }
                   6546:         if (!exists($inuse{$prefix."\0".$newid})) {
                   6547:             my %new_item =  (
                   6548:                               $prefix."\0".$newid => $who,
                   6549:                             );
                   6550:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   6551:                                                  $cdom,$cnum);
                   6552:             if ($putresult ne 'ok') {
                   6553:                 undef($newid);
                   6554:                 $error = 'error saving new item: '.$putresult;
                   6555:             }
                   6556:         } else {
1.1172.2.56  raeburn  6557:              undef($newid);
1.1172.2.13  raeburn  6558:              $error = ('error: no unique suffix available for the new item ');
                   6559:         }
                   6560: #  remove lock
                   6561:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   6562:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   6563:     } else {
                   6564:         $error = "error: could not obtain lockfile\n";
                   6565:         $dellock = 'ok';
1.1172.2.58  raeburn  6566:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   6567:             $dellock = 'nolock';
                   6568:         }
1.1172.2.13  raeburn  6569:     }
                   6570:     return ($newid,$dellock,$error);
                   6571: }
                   6572: 
1.1172.2.56  raeburn  6573: sub sixnum_code {
                   6574:     my $code;
                   6575:     for (0..6) {
                   6576:         $code .= int( rand(9) );
                   6577:     }
                   6578:     return $code;
                   6579: }
                   6580: 
1.765     albertel 6581: # -------------------------------------------------- portfolio access checking
                   6582: 
                   6583: sub portfolio_access {
1.1172.2.77  raeburn  6584:     my ($requrl,$clientip) = @_;
1.765     albertel 6585:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77  raeburn  6586:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  6587:     if ($result) {
                   6588:         my %setters;
                   6589:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6590:             my ($startblock,$endblock) =
                   6591:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   6592:             if ($startblock && $endblock) {
                   6593:                 return 'B';
                   6594:             }
                   6595:         } else {
                   6596:             my ($startblock,$endblock) =
                   6597:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   6598:             if ($startblock && $endblock) {
                   6599:                 return 'B';
                   6600:             }
                   6601:         }
                   6602:     }
1.765     albertel 6603:     if ($result eq 'ok') {
1.766     albertel 6604:        return 'F';
1.765     albertel 6605:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 6606:        return 'A';
1.765     albertel 6607:     }
1.766     albertel 6608:     return '';
1.765     albertel 6609: }
                   6610: 
                   6611: sub get_portfolio_access {
1.1172.2.77  raeburn  6612:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 6613: 
                   6614:     if (!ref($access_hash)) {
                   6615: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   6616: 	my %access_controls = &get_access_controls($current_perms,$group,
                   6617: 						   $file_name);
                   6618: 	$access_hash = $access_controls{$file_name};
                   6619:     }
                   6620: 
1.1172.2.77  raeburn  6621:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 6622:     my $now = time;
                   6623:     if (ref($access_hash) eq 'HASH') {
                   6624:         foreach my $key (keys(%{$access_hash})) {
                   6625:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6626:             if ($start > $now) {
                   6627:                 next;
                   6628:             }
                   6629:             if ($end && $end<$now) {
                   6630:                 next;
                   6631:             }
                   6632:             if ($scope eq 'public') {
                   6633:                 $public = $key;
                   6634:                 last;
                   6635:             } elsif ($scope eq 'guest') {
                   6636:                 $guest = $key;
                   6637:             } elsif ($scope eq 'domains') {
                   6638:                 push(@domains,$key);
                   6639:             } elsif ($scope eq 'users') {
                   6640:                 push(@users,$key);
                   6641:             } elsif ($scope eq 'course') {
                   6642:                 push(@courses,$key);
                   6643:             } elsif ($scope eq 'group') {
                   6644:                 push(@groups,$key);
1.1172.2.77  raeburn  6645:             } elsif ($scope eq 'ip') {
                   6646:                 push(@ips,$key);
1.765     albertel 6647:             }
                   6648:         }
                   6649:         if ($public) {
                   6650:             return 'ok';
1.1172.2.77  raeburn  6651:         } elsif (@ips > 0) {
                   6652:             my $allowed;
                   6653:             foreach my $ipkey (@ips) {
                   6654:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   6655:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   6656:                         $allowed = 1;
                   6657:                         last;
                   6658:                     }
                   6659:                 }
                   6660:             }
                   6661:             if ($allowed) {
                   6662:                 return 'ok';
                   6663:             }
1.765     albertel 6664:         }
                   6665:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6666:             if ($guest) {
                   6667:                 return $guest;
                   6668:             }
                   6669:         } else {
                   6670:             if (@domains > 0) {
                   6671:                 foreach my $domkey (@domains) {
                   6672:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   6673:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   6674:                             return 'ok';
                   6675:                         }
                   6676:                     }
                   6677:                 }
                   6678:             }
                   6679:             if (@users > 0) {
                   6680:                 foreach my $userkey (@users) {
1.865     raeburn  6681:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   6682:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   6683:                             if (ref($item) eq 'HASH') {
                   6684:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   6685:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   6686:                                     return 'ok';
                   6687:                                 }
                   6688:                             }
                   6689:                         }
                   6690:                     } 
1.765     albertel 6691:                 }
                   6692:             }
                   6693:             my %roleshash;
                   6694:             my @courses_and_groups = @courses;
                   6695:             push(@courses_and_groups,@groups); 
                   6696:             if (@courses_and_groups > 0) {
                   6697:                 my (%allgroups,%allroles); 
                   6698:                 my ($start,$end,$role,$sec,$group);
                   6699:                 foreach my $envkey (%env) {
1.1060    raeburn  6700:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6701:                         my $cid = $2.'_'.$3; 
                   6702:                         if ($1 eq 'gr') {
                   6703:                             $group = $4;
                   6704:                             $allgroups{$cid}{$group} = $env{$envkey};
                   6705:                         } else {
                   6706:                             if ($4 eq '') {
                   6707:                                 $sec = 'none';
                   6708:                             } else {
                   6709:                                 $sec = $4;
                   6710:                             }
                   6711:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6712:                         }
1.811     albertel 6713:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6714:                         my $cid = $2.'_'.$3;
                   6715:                         if ($4 eq '') {
                   6716:                             $sec = 'none';
                   6717:                         } else {
                   6718:                             $sec = $4;
                   6719:                         }
                   6720:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6721:                     }
                   6722:                 }
                   6723:                 if (keys(%allroles) == 0) {
                   6724:                     return;
                   6725:                 }
                   6726:                 foreach my $key (@courses_and_groups) {
                   6727:                     my %content = %{$$access_hash{$key}};
                   6728:                     my $cnum = $content{'number'};
                   6729:                     my $cdom = $content{'domain'};
                   6730:                     my $cid = $cdom.'_'.$cnum;
                   6731:                     if (!exists($allroles{$cid})) {
                   6732:                         next;
                   6733:                     }    
                   6734:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   6735:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   6736:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   6737:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   6738:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   6739:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   6740:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   6741:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   6742:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   6743:                                         if (grep/^all$/,@sections) {
                   6744:                                             return 'ok';
                   6745:                                         } else {
                   6746:                                             if (grep/^$sec$/,@sections) {
                   6747:                                                 return 'ok';
                   6748:                                             }
                   6749:                                         }
                   6750:                                     }
                   6751:                                 }
                   6752:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   6753:                                     if (grep/^none$/,@groups) {
                   6754:                                         return 'ok';
                   6755:                                     }
                   6756:                                 } else {
                   6757:                                     if (grep/^all$/,@groups) {
                   6758:                                         return 'ok';
                   6759:                                     } 
                   6760:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   6761:                                         if (grep/^$group$/,@groups) {
                   6762:                                             return 'ok';
                   6763:                                         }
                   6764:                                     }
                   6765:                                 } 
                   6766:                             }
                   6767:                         }
                   6768:                     }
                   6769:                 }
                   6770:             }
                   6771:             if ($guest) {
                   6772:                 return $guest;
                   6773:             }
                   6774:         }
                   6775:     }
                   6776:     return;
                   6777: }
                   6778: 
                   6779: sub course_group_datechecker {
                   6780:     my ($dates,$now,$status) = @_;
                   6781:     my ($start,$end) = split(/\./,$dates);
                   6782:     if (!$start && !$end) {
                   6783:         return 'ok';
                   6784:     }
                   6785:     if (grep/^active$/,@{$status}) {
                   6786:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   6787:             return 'ok';
                   6788:         }
                   6789:     }
                   6790:     if (grep/^previous$/,@{$status}) {
                   6791:         if ($end > $now ) {
                   6792:             return 'ok';
                   6793:         }
                   6794:     }
                   6795:     if (grep/^future$/,@{$status}) {
                   6796:         if ($start > $now) {
                   6797:             return 'ok';
                   6798:         }
                   6799:     }
                   6800:     return; 
                   6801: }
                   6802: 
                   6803: sub parse_portfolio_url {
                   6804:     my ($url) = @_;
                   6805: 
                   6806:     my ($type,$udom,$unum,$group,$file_name);
                   6807:     
1.823     albertel 6808:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 6809: 	$type = 1;
                   6810:         $udom = $1;
                   6811:         $unum = $2;
                   6812:         $file_name = $3;
1.823     albertel 6813:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 6814: 	$type = 2;
                   6815:         $udom = $1;
                   6816:         $unum = $2;
                   6817:         $group = $3;
                   6818:         $file_name = $3.'/'.$4;
                   6819:     }
                   6820:     if (wantarray) {
                   6821: 	return ($type,$udom,$unum,$file_name,$group);
                   6822:     }
                   6823:     return $type;
                   6824: }
                   6825: 
                   6826: sub is_portfolio_url {
                   6827:     my ($url) = @_;
                   6828:     return scalar(&parse_portfolio_url($url));
                   6829: }
                   6830: 
1.798     raeburn  6831: sub is_portfolio_file {
                   6832:     my ($file) = @_;
1.820     raeburn  6833:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  6834:         return 1;
                   6835:     }
                   6836:     return;
                   6837: }
                   6838: 
1.976     raeburn  6839: sub usertools_access {
1.1084    raeburn  6840:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  6841:     my ($access,%tools);
                   6842:     if ($context eq '') {
                   6843:         $context = 'tools';
                   6844:     }
                   6845:     if ($context eq 'requestcourses') {
                   6846:         %tools = (
                   6847:                       official   => 1,
                   6848:                       unofficial => 1,
1.1006    raeburn  6849:                       community  => 1,
1.1172.2.37  raeburn  6850:                       textbook   => 1,
1.985     raeburn  6851:                  );
1.1172.2.9  raeburn  6852:     } elsif ($context eq 'requestauthor') {
                   6853:         %tools = (
                   6854:                       requestauthor => 1,
                   6855:                  );
1.985     raeburn  6856:     } else {
                   6857:         %tools = (
                   6858:                       aboutme   => 1,
                   6859:                       blog      => 1,
1.1172.2.6  raeburn  6860:                       webdav    => 1,
1.985     raeburn  6861:                       portfolio => 1,
                   6862:                  );
                   6863:     }
1.976     raeburn  6864:     return if (!defined($tools{$tool}));
                   6865: 
1.1172.2.35  raeburn  6866:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  6867:         $udom = $env{'user.domain'};
                   6868:         $uname = $env{'user.name'};
                   6869:     }
                   6870: 
1.978     raeburn  6871:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6872:         if ($action ne 'reload') {
1.985     raeburn  6873:             if ($context eq 'requestcourses') {
                   6874:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  6875:             } elsif ($context eq 'requestauthor') {
                   6876:                 return $env{'environment.canrequest.author'};
1.985     raeburn  6877:             } else {
                   6878:                 return $env{'environment.availabletools.'.$tool};
                   6879:             }
                   6880:         }
1.976     raeburn  6881:     }
                   6882: 
1.1172.2.9  raeburn  6883:     my ($toolstatus,$inststatus,$envkey);
                   6884:     if ($context eq 'requestauthor') {
                   6885:         $envkey = $context;
                   6886:     } else {
                   6887:         $envkey = $context.'.'.$tool;
                   6888:     }
1.976     raeburn  6889: 
1.985     raeburn  6890:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   6891:          ($action ne 'reload')) {
1.1172.2.9  raeburn  6892:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  6893:         $inststatus = $env{'environment.inststatus'};
                   6894:     } else {
1.1084    raeburn  6895:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  6896:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  6897:             $inststatus = $userenvref->{'inststatus'};
                   6898:         } else {
1.1172.2.9  raeburn  6899:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   6900:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  6901:             $inststatus = $userenv{'inststatus'};
                   6902:         }
1.976     raeburn  6903:     }
                   6904: 
                   6905:     if ($toolstatus ne '') {
                   6906:         if ($toolstatus) {
                   6907:             $access = 1;
                   6908:         } else {
                   6909:             $access = 0;
                   6910:         }
                   6911:         return $access;
                   6912:     }
                   6913: 
1.1084    raeburn  6914:     my ($is_adv,%domdef);
                   6915:     if (ref($is_advref) eq 'HASH') {
                   6916:         $is_adv = $is_advref->{'is_adv'};
                   6917:     } else {
                   6918:         $is_adv = &is_advanced_user($udom,$uname);
                   6919:     }
                   6920:     if (ref($domdefref) eq 'HASH') {
                   6921:         %domdef = %{$domdefref};
                   6922:     } else {
                   6923:         %domdef = &get_domain_defaults($udom);
                   6924:     }
1.976     raeburn  6925:     if (ref($domdef{$tool}) eq 'HASH') {
                   6926:         if ($is_adv) {
                   6927:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   6928:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   6929:                     $access = 1;
                   6930:                 } else {
                   6931:                     $access = 0;
                   6932:                 }
                   6933:                 return $access;
                   6934:             }
                   6935:         }
                   6936:         if ($inststatus ne '') {
                   6937:             my ($hasaccess,$hasnoaccess);
                   6938:             foreach my $affiliation (split(/:/,$inststatus)) {
                   6939:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   6940:                     if ($domdef{$tool}{$affiliation}) {
                   6941:                         $hasaccess = 1;
                   6942:                     } else {
                   6943:                         $hasnoaccess = 1;
                   6944:                     }
                   6945:                 }
                   6946:             }
                   6947:             if ($hasaccess || $hasnoaccess) {
                   6948:                 if ($hasaccess) {
                   6949:                     $access = 1;
                   6950:                 } elsif ($hasnoaccess) {
                   6951:                     $access = 0; 
                   6952:                 }
                   6953:                 return $access;
                   6954:             }
                   6955:         } else {
                   6956:             if ($domdef{$tool}{'default'} ne '') {
                   6957:                 if ($domdef{$tool}{'default'}) {
                   6958:                     $access = 1;
                   6959:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   6960:                     $access = 0;
                   6961:                 }
                   6962:                 return $access;
                   6963:             }
                   6964:         }
                   6965:     } else {
1.1172.2.6  raeburn  6966:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  6967:             $access = 1;
                   6968:         } else {
                   6969:             $access = 0;
                   6970:         }
1.976     raeburn  6971:         return $access;
                   6972:     }
                   6973: }
                   6974: 
1.1050    raeburn  6975: sub is_course_owner {
                   6976:     my ($cdom,$cnum,$udom,$uname) = @_;
                   6977:     if (($udom eq '') || ($uname eq '')) {
                   6978:         $udom = $env{'user.domain'};
                   6979:         $uname = $env{'user.name'};
                   6980:     }
                   6981:     unless (($udom eq '') || ($uname eq '')) {
                   6982:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   6983:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   6984:                 return 1;
                   6985:             } else {
                   6986:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   6987:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   6988:                     return 1;
                   6989:                 }
                   6990:             }
                   6991:         }
                   6992:     }
                   6993:     return;
                   6994: }
                   6995: 
1.976     raeburn  6996: sub is_advanced_user {
                   6997:     my ($udom,$uname) = @_;
1.1085    raeburn  6998:     if ($udom ne '' && $uname ne '') {
                   6999:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7000:             if (wantarray) {
                   7001:                 return ($env{'user.adv'},$env{'user.author'});
                   7002:             } else {
                   7003:                 return $env{'user.adv'};
                   7004:             }
1.1085    raeburn  7005:         }
                   7006:     }
1.976     raeburn  7007:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7008:     my %allroles;
1.1128    raeburn  7009:     my ($is_adv,$is_author);
1.976     raeburn  7010:     foreach my $role (keys(%roleshash)) {
                   7011:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7012:         my $area = '/'.$tdomain.'/'.$trest;
                   7013:         if ($sec ne '') {
                   7014:             $area .= '/'.$sec;
                   7015:         }
                   7016:         if (($area ne '') && ($trole ne '')) {
                   7017:             my $spec=$trole.'.'.$area;
                   7018:             if ($trole =~ /^cr\//) {
                   7019:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7020:             } elsif ($trole ne 'gr') {
                   7021:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7022:             }
1.1128    raeburn  7023:             if ($trole eq 'au') {
                   7024:                 $is_author = 1;
                   7025:             }
1.976     raeburn  7026:         }
                   7027:     }
                   7028:     foreach my $role (keys(%allroles)) {
                   7029:         last if ($is_adv);
                   7030:         foreach my $item (split(/:/,$allroles{$role})) {
                   7031:             if ($item ne '') {
                   7032:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7033:                 if ($privilege eq 'adv') {
                   7034:                     $is_adv = 1;
                   7035:                     last;
                   7036:                 }
                   7037:             }
                   7038:         }
                   7039:     }
1.1128    raeburn  7040:     if (wantarray) {
                   7041:         return ($is_adv,$is_author);
                   7042:     }
1.976     raeburn  7043:     return $is_adv;
                   7044: }
1.798     raeburn  7045: 
1.1035    raeburn  7046: sub check_can_request {
1.1036    raeburn  7047:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  7048:     my $canreq = 0;
                   7049:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7050:     my @options = ('approval','validate','autolimit');
                   7051:     my $optregex = join('|',@options);
                   7052:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7053:         foreach my $type (@{$types}) {
                   7054:             if (&usertools_access($env{'user.name'},
                   7055:                                   $env{'user.domain'},
                   7056:                                   $type,undef,'requestcourses')) {
                   7057:                 $canreq ++;
1.1036    raeburn  7058:                 if (ref($request_domains) eq 'HASH') {
                   7059:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   7060:                 }
1.1035    raeburn  7061:                 if ($dom eq $env{'user.domain'}) {
                   7062:                     $can_request->{$type} = 1;
                   7063:                 }
                   7064:             }
                   7065:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   7066:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7067:                 if (@curr > 0) {
1.1036    raeburn  7068:                     foreach my $item (@curr) {
                   7069:                         if (ref($request_domains) eq 'HASH') {
                   7070:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7071:                             if ($otherdom ne '') {
                   7072:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7073:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7074:                                         push(@{$request_domains->{$type}},$otherdom);
                   7075:                                     }
                   7076:                                 } else {
                   7077:                                     push(@{$request_domains->{$type}},$otherdom);
                   7078:                                 }
                   7079:                             }
                   7080:                         }
                   7081:                     }
                   7082:                     unless($dom eq $env{'user.domain'}) {
                   7083:                         $canreq ++;
1.1035    raeburn  7084:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7085:                             $can_request->{$type} = 1;
                   7086:                         }
                   7087:                     }
                   7088:                 }
                   7089:             }
                   7090:         }
                   7091:     }
                   7092:     return $canreq;
                   7093: }
                   7094: 
1.341     www      7095: # ---------------------------------------------- Custom access rule evaluation
                   7096: 
                   7097: sub customaccess {
                   7098:     my ($priv,$uri)=@_;
1.807     albertel 7099:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7100:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7101:     $udom = &LONCAPA::clean_domain($udom);
                   7102:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7103:     my $access=0;
1.800     albertel 7104:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7105: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7106: 	if ($type eq 'user') {
                   7107: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7108: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7109: 		if ($tdom) {
                   7110: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7111: 		}
1.896     albertel 7112: 		if ($tuname) {
                   7113: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7114: 		}
                   7115: 		$access=($effect eq 'allow');
                   7116: 		last;
                   7117: 	    }
                   7118: 	} else {
                   7119: 	    if ($role) {
                   7120: 		if ($role ne $urole) { next; }
                   7121: 	    }
                   7122: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7123: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7124: 		if ($tdom) {
                   7125: 		    if ($tdom ne $udom) { next; }
                   7126: 		}
                   7127: 		if ($tcrs) {
                   7128: 		    if ($tcrs ne $ucrs) { next; }
                   7129: 		}
                   7130: 		if ($tsec) {
                   7131: 		    if ($tsec ne $usec) { next; }
                   7132: 		}
                   7133: 		$access=($effect eq 'allow');
                   7134: 		last;
                   7135: 	    }
                   7136: 	    if ($realm eq '' && $role eq '') {
                   7137: 		$access=($effect eq 'allow');
                   7138: 	    }
1.402     bowersj2 7139: 	}
1.341     www      7140:     }
                   7141:     return $access;
                   7142: }
                   7143: 
1.103     harris41 7144: # ------------------------------------------------- Check for a user privilege
1.12      www      7145: 
                   7146: sub allowed {
1.1172.2.65  raeburn  7147:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 7148:     my $ver_orguri=$uri;
1.439     www      7149:     $uri=&deversion($uri);
1.152     www      7150:     my $orguri=$uri;
1.52      www      7151:     $uri=&declutter($uri);
1.809     raeburn  7152: 
1.810     raeburn  7153:     if ($priv eq 'evb') {
                   7154: # Evade communication block restrictions for specified role in a course
                   7155:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   7156:             return $1;
                   7157:         } else {
                   7158:             return;
                   7159:         }
                   7160:     }
                   7161: 
1.620     albertel 7162:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      7163: # Free bre access to adm and meta resources
1.1172.2.93.4  2(raebur 7164:7):     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$})) 
1.769     albertel 7165: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   7166: 	&& ($priv eq 'bre')) {
1.14      www      7167: 	return 'F';
1.159     www      7168:     }
                   7169: 
1.545     banghart 7170: # Free bre access to user's own portfolio contents
1.714     raeburn  7171:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  7172:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  7173: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  7174:         my %setters;
                   7175:         my ($startblock,$endblock) = 
                   7176:             &Apache::loncommon::blockcheck(\%setters,'port');
                   7177:         if ($startblock && $endblock) {
                   7178:             return 'B';
                   7179:         } else {
                   7180:             return 'F';
                   7181:         }
1.545     banghart 7182:     }
                   7183: 
1.762     raeburn  7184: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  7185:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   7186:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   7187:         if (exists($env{'request.course.id'})) {
                   7188:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7189:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7190:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   7191:                 my $courseprivid=$env{'request.course.id'};
                   7192:                 $courseprivid=~s/\_/\//;
                   7193:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   7194:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   7195:                     return $1; 
1.762     raeburn  7196:                 } else {
                   7197:                     if ($env{'request.course.sec'}) {
                   7198:                         $courseprivid.='/'.$env{'request.course.sec'};
                   7199:                     }
                   7200:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   7201:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   7202:                         return $2;
                   7203:                     }
1.714     raeburn  7204:                 }
                   7205:             }
                   7206:         }
                   7207:     }
                   7208: 
1.159     www      7209: # Free bre to public access
                   7210: 
                   7211:     if ($priv eq 'bre') {
1.238     www      7212:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 7213: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      7214:            return 'F'; 
                   7215:         }
1.238     www      7216:         if ($copyright eq 'priv') {
                   7217:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7218: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      7219: 		return '';
                   7220:             }
                   7221:         }
                   7222:         if ($copyright eq 'domain') {
                   7223:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7224: 	    unless (($env{'user.domain'} eq $1) ||
                   7225:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7226: 		return '';
                   7227:             }
1.262     matthew  7228:         }
1.620     albertel 7229:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7230:             # Library role, so allow browsing of resources in this domain.
                   7231:             return 'F';
1.238     www      7232:         }
1.341     www      7233:         if ($copyright eq 'custom') {
                   7234: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7235:         }
1.14      www      7236:     }
1.264     matthew  7237:     # Domain coordinator is trying to create a course
1.620     albertel 7238:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7239:         # uri is the requested domain in this case.
                   7240:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7241:         # a role of dc for the domain in question.
1.620     albertel 7242:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7243:     }
1.29      www      7244: 
1.52      www      7245:     my $thisallowed='';
                   7246:     my $statecond=0;
                   7247:     my $courseprivid='';
                   7248: 
1.1039    raeburn  7249:     my $ownaccess;
1.1043    raeburn  7250:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7251:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7252:         if ($uri eq '') {
                   7253:             $ownaccess = 1;
                   7254:         } else {
                   7255:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7256:                 my $udom = $env{'user.domain'};
                   7257:                 my $uname = $env{'user.name'};
                   7258:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7259:                     $ownaccess = 1;
1.1040    raeburn  7260:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7261:                     unless ($uri =~ m{\.\./}) {
                   7262:                         $ownaccess = 1;
                   7263:                     }
                   7264:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   7265:                     my $now = time;
                   7266:                     if ($uri =~ m{^([^/]+)/?$}) {
                   7267:                         my $adom = $1;
                   7268:                         foreach my $key (keys(%env)) {
1.1042    raeburn  7269:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  7270:                                 my ($start,$end) = split('.',$env{$key});
                   7271:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7272:                                     $ownaccess = 1;
                   7273:                                     last;
                   7274:                                 }
                   7275:                             }
                   7276:                         }
                   7277:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   7278:                         my $adom = $1;
                   7279:                         my $aname = $2;
1.1042    raeburn  7280:                         foreach my $role ('ca','aa') { 
                   7281:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   7282:                                 my ($start,$end) =
                   7283:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   7284:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7285:                                     $ownaccess = 1;
                   7286:                                     last;
                   7287:                                 }
1.1039    raeburn  7288:                             }
                   7289:                         }
                   7290:                     }
                   7291:                 }
                   7292:             }
                   7293:         }
                   7294:     }
                   7295: 
1.52      www      7296: # Course
                   7297: 
1.620     albertel 7298:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7299:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7300:             $thisallowed.=$1;
                   7301:         }
1.52      www      7302:     }
1.29      www      7303: 
1.52      www      7304: # Domain
                   7305: 
1.620     albertel 7306:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 7307:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7308:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7309:             $thisallowed.=$1;
                   7310:         }
1.12      www      7311:     }
1.52      www      7312: 
1.1141    raeburn  7313: # User who is not author or co-author might still be able to edit
                   7314: # resource of an author in the domain (e.g., if Domain Coordinator).
                   7315:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   7316:         (&allowed('mdc',$env{'request.course.id'}))) {
                   7317:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   7318:             $thisallowed.=$1;
                   7319:         }
                   7320:     }
                   7321: 
1.52      www      7322: # Course: uri itself is a course
1.66      www      7323:     my $courseuri=$uri;
                   7324:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      7325:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      7326: 
1.620     albertel 7327:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 7328:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7329:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7330:             $thisallowed.=$1;
                   7331:         }
1.12      www      7332:     }
1.29      www      7333: 
1.665     albertel 7334: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 7335: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 7336:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 7337: 	$thisallowed='';
1.671     raeburn  7338:         my ($match)=&is_on_map($uri);
                   7339:         if ($match) {
                   7340:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   7341:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65  raeburn  7342:                 my $value = $1;
                   7343:                 if ($noblockcheck) {
                   7344:                     $thisallowed.=$value;
1.1162    raeburn  7345:                 } else {
1.1172.2.65  raeburn  7346:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7347:                     if (@blockers > 0) {
                   7348:                         $thisallowed = 'B';
                   7349:                     } else {
                   7350:                         $thisallowed.=$value;
                   7351:                     }
1.1162    raeburn  7352:                 }
1.671     raeburn  7353:             }
                   7354:         } else {
1.705     albertel 7355:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  7356:             if ($refuri) {
                   7357:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  7358:                     $thisallowed='F';
1.671     raeburn  7359:                 } else {
                   7360:                     $refuri=&declutter($refuri);
                   7361:                     my ($match) = &is_on_map($refuri);
                   7362:                     if ($match) {
1.1172.2.65  raeburn  7363:                         if ($noblockcheck) {
1.1162    raeburn  7364:                             $thisallowed='F';
1.1172.2.65  raeburn  7365:                         } else {
                   7366:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7367:                             if (@blockers > 0) {
                   7368:                                 $thisallowed = 'B';
                   7369:                             } else {
                   7370:                                 $thisallowed='F';
                   7371:                             }
1.1162    raeburn  7372:                         }
1.671     raeburn  7373:                     }
1.669     raeburn  7374:                 }
1.671     raeburn  7375:             }
                   7376:         }
1.314     www      7377:     }
1.492     albertel 7378: 
1.766     albertel 7379:     if ($priv eq 'bre'
                   7380: 	&& $thisallowed ne 'F' 
                   7381: 	&& $thisallowed ne '2'
                   7382: 	&& &is_portfolio_url($uri)) {
1.1172.2.77  raeburn  7383: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 7384:     }
                   7385:     
1.52      www      7386: # Full access at system, domain or course-wide level? Exit.
1.29      www      7387:     if ($thisallowed=~/F/) {
                   7388: 	return 'F';
                   7389:     }
                   7390: 
1.52      www      7391: # If this is generating or modifying users, exit with special codes
1.29      www      7392: 
1.643     www      7393:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   7394: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 7395: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      7396: # no author name given, so this just checks on the general right to make a co-author in this domain
                   7397: 	    unless ($auname) { return $thisallowed; }
                   7398: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 7399: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   7400: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   7401: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   7402: 	}
1.52      www      7403: 	return $thisallowed;
                   7404:     }
                   7405: #
1.103     harris41 7406: # Gathered so far: system, domain and course wide privileges
1.52      www      7407: #
                   7408: # Course: See if uri or referer is an individual resource that is part of 
                   7409: # the course
                   7410: 
1.620     albertel 7411:     if ($env{'request.course.id'}) {
1.232     www      7412: 
1.620     albertel 7413:        $courseprivid=$env{'request.course.id'};
                   7414:        if ($env{'request.course.sec'}) {
                   7415:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      7416:        }
                   7417:        $courseprivid=~s/\_/\//;
                   7418:        my $checkreferer=1;
1.232     www      7419:        my ($match,$cond)=&is_on_map($uri);
                   7420:        if ($match) {
                   7421:            $statecond=$cond;
1.620     albertel 7422:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7423:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7424:                my $value = $1;
                   7425:                if ($priv eq 'bre') {
1.1172.2.65  raeburn  7426:                    if ($noblockcheck) {
1.1162    raeburn  7427:                        $thisallowed.=$value;
1.1172.2.65  raeburn  7428:                    } else {
                   7429:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7430:                        if (@blockers > 0) {
                   7431:                            $thisallowed = 'B';
                   7432:                        } else {
                   7433:                            $thisallowed.=$value;
                   7434:                        }
1.1162    raeburn  7435:                    }
                   7436:                } else {
                   7437:                    $thisallowed.=$value;
                   7438:                }
1.52      www      7439:                $checkreferer=0;
                   7440:            }
1.29      www      7441:        }
1.83      www      7442:        
1.148     www      7443:        if ($checkreferer) {
1.620     albertel 7444: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      7445:             unless ($refuri) {
1.800     albertel 7446:                 foreach my $key (keys(%env)) {
                   7447: 		    if ($key=~/^httpref\..*\*/) {
                   7448: 			my $pattern=$key;
1.156     www      7449:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      7450:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   7451:                         $pattern=~s/\//\\\//g;
1.152     www      7452:                         if ($orguri=~/$pattern/) {
1.800     albertel 7453: 			    $refuri=$env{$key};
1.148     www      7454:                         }
                   7455:                     }
1.191     harris41 7456:                 }
1.148     www      7457:             }
1.232     www      7458: 
1.148     www      7459:          if ($refuri) { 
1.152     www      7460: 	  $refuri=&declutter($refuri);
1.232     www      7461:           my ($match,$cond)=&is_on_map($refuri);
                   7462:             if ($match) {
                   7463:               my $refstatecond=$cond;
1.620     albertel 7464:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7465:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7466:                   my $value = $1;
                   7467:                   if ($priv eq 'bre') {
1.1172.2.65  raeburn  7468:                       if ($noblockcheck) {
1.1162    raeburn  7469:                           $thisallowed.=$value;
1.1172.2.65  raeburn  7470:                       } else {
                   7471:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7472:                           if (@blockers > 0) {
                   7473:                               $thisallowed = 'B';
                   7474:                           } else {
                   7475:                               $thisallowed.=$value;
                   7476:                           }
1.1162    raeburn  7477:                       }
                   7478:                   } else {
                   7479:                       $thisallowed.=$value;
                   7480:                   }
1.53      www      7481:                   $uri=$refuri;
                   7482:                   $statecond=$refstatecond;
1.52      www      7483:               }
                   7484:           }
1.148     www      7485:         }
1.29      www      7486:        }
1.52      www      7487:    }
1.29      www      7488: 
1.52      www      7489: #
1.103     harris41 7490: # Gathered now: all privileges that could apply, and condition number
1.52      www      7491: # 
                   7492: #
                   7493: # Full or no access?
                   7494: #
1.29      www      7495: 
1.52      www      7496:     if ($thisallowed=~/F/) {
                   7497: 	return 'F';
                   7498:     }
1.29      www      7499: 
1.52      www      7500:     unless ($thisallowed) {
                   7501:         return '';
                   7502:     }
1.29      www      7503: 
1.52      www      7504: # Restrictions exist, deal with them
                   7505: #
                   7506: #   C:according to course preferences
                   7507: #   R:according to resource settings
                   7508: #   L:unless locked
                   7509: #   X:according to user session state
                   7510: #
                   7511: 
                   7512: # Possibly locked functionality, check all courses
1.54      www      7513: # Locks might take effect only after 10 minutes cache expiration for other
                   7514: # courses, and 2 minutes for current course
1.52      www      7515: 
                   7516:     my $envkey;
                   7517:     if ($thisallowed=~/L/) {
1.1000    raeburn  7518:         foreach $envkey (keys(%env)) {
1.54      www      7519:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   7520:                my $courseid=$2;
                   7521:                my $roleid=$1.'.'.$2;
1.92      www      7522:                $courseid=~s/^\///;
1.54      www      7523:                my $expiretime=600;
1.620     albertel 7524:                if ($env{'request.role'} eq $roleid) {
1.54      www      7525: 		  $expiretime=120;
                   7526:                }
                   7527: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   7528:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 7529:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 7530: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      7531:                }
1.620     albertel 7532:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7533:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   7534: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   7535:                        &log($env{'user.domain'},$env{'user.name'},
                   7536:                             $env{'user.home'},
1.57      www      7537:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      7538:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7539:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7540: 		       return '';
                   7541:                    }
                   7542:                }
1.620     albertel 7543:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7544:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   7545: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   7546:                        &log($env{'user.domain'},$env{'user.name'},
                   7547:                             $env{'user.home'},
1.57      www      7548:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      7549:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7550:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7551: 		       return '';
                   7552:                    }
                   7553:                }
                   7554: 	   }
1.29      www      7555:        }
1.52      www      7556:     }
                   7557:    
                   7558: #
                   7559: # Rest of the restrictions depend on selected course
                   7560: #
                   7561: 
1.620     albertel 7562:     unless ($env{'request.course.id'}) {
1.766     albertel 7563: 	if ($thisallowed eq 'A') {
                   7564: 	    return 'A';
1.814     raeburn  7565:         } elsif ($thisallowed eq 'B') {
                   7566:             return 'B';
1.766     albertel 7567: 	} else {
                   7568: 	    return '1';
                   7569: 	}
1.52      www      7570:     }
1.29      www      7571: 
1.52      www      7572: #
                   7573: # Now user is definitely in a course
                   7574: #
1.53      www      7575: 
                   7576: 
                   7577: # Course preferences
                   7578: 
                   7579:    if ($thisallowed=~/C/) {
1.620     albertel 7580:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   7581:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   7582:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 7583: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  7584: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7585: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7586: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   7587: 			$env{'request.course.id'});
                   7588: 	   }
1.237     www      7589:            return '';
                   7590:        }
                   7591: 
1.620     albertel 7592:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 7593: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  7594: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7595: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   7596: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   7597: 			$env{'request.course.id'});
                   7598: 	   }
1.54      www      7599:            return '';
                   7600:        }
1.53      www      7601:    }
                   7602: 
                   7603: # Resource preferences
                   7604: 
                   7605:    if ($thisallowed=~/R/) {
1.620     albertel 7606:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 7607:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  7608: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7609: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7610: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   7611: 	   }
                   7612: 	   return '';
1.54      www      7613:        }
1.53      www      7614:    }
1.30      www      7615: 
1.246     www      7616: # Restricted by state or randomout?
1.30      www      7617: 
1.52      www      7618:    if ($thisallowed=~/X/) {
1.620     albertel 7619:       if ($env{'acc.randomout'}) {
1.579     albertel 7620: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 7621:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      7622:             return ''; 
                   7623:          }
1.247     www      7624:       }
                   7625:       if (&condval($statecond)) {
1.52      www      7626: 	 return '2';
                   7627:       } else {
                   7628:          return '';
                   7629:       }
                   7630:    }
1.30      www      7631: 
1.766     albertel 7632:     if ($thisallowed eq 'A') {
                   7633: 	return 'A';
1.814     raeburn  7634:     } elsif ($thisallowed eq 'B') {
                   7635:         return 'B';
1.766     albertel 7636:     }
1.52      www      7637:    return 'F';
1.232     www      7638: }
1.1162    raeburn  7639: 
1.1172.2.13  raeburn  7640: # ------------------------------------------- Check construction space access
                   7641: 
                   7642: sub constructaccess {
                   7643:     my ($url,$setpriv)=@_;
                   7644: 
                   7645: # We do not allow editing of previous versions of files
                   7646:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   7647: 
                   7648: # Get username and domain from URL
                   7649:     my ($ownername,$ownerdomain,$ownerhome);
                   7650: 
                   7651:     ($ownerdomain,$ownername) =
1.1172.2.83  raeburn  7652:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13  raeburn  7653: 
                   7654: # The URL does not really point to any authorspace, forget it
                   7655:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   7656: 
                   7657: # Now we need to see if the user has access to the authorspace of
                   7658: # $ownername at $ownerdomain
                   7659: 
                   7660:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   7661: # Real author for this?
                   7662:        $ownerhome = $env{'user.home'};
                   7663:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   7664:           return ($ownername,$ownerdomain,$ownerhome);
                   7665:        }
                   7666:     } else {
                   7667: # Co-author for this?
                   7668:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   7669:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   7670:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   7671:             return ($ownername,$ownerdomain,$ownerhome);
                   7672:         }
                   7673:     }
                   7674: 
                   7675: # We don't have any access right now. If we are not possibly going to do anything about this,
                   7676: # we might as well leave
                   7677:    unless ($setpriv) { return ''; }
                   7678: 
                   7679: # Backdoor access?
                   7680:     my $allowed=&allowed('eco',$ownerdomain);
                   7681: # Nope
                   7682:     unless ($allowed) { return ''; }
                   7683: # Looks like we may have access, but could be locked by the owner of the construction space
                   7684:     if ($allowed eq 'U') {
                   7685:         my %blocked=&get('environment',['domcoord.author'],
                   7686:                          $ownerdomain,$ownername);
                   7687: # Is blocked by owner
                   7688:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   7689:     }
                   7690:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   7691: # Grant temporary access
                   7692:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  7693:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  7694:         if (!$update) { $update = $then; }
                   7695:         my $refresh=$env{'user.refresh.time'};
                   7696:         if (!$refresh) { $refresh = $update; }
                   7697:         my $now = time;
                   7698:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   7699:                            $now,'ca','constructaccess');
                   7700:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   7701:         return($ownername,$ownerdomain,$ownerhome);
                   7702:     }
                   7703: # No business here
                   7704:     return '';
                   7705: }
                   7706: 
1.1172.2.66  raeburn  7707: # ----------------------------------------------------------- Content Blocking
                   7708: 
                   7709: {
                   7710: # Caches for faster Course Contents display where content blocking
                   7711: # is in operation (i.e., interval param set) for timed quiz.
                   7712: #
                   7713: # User for whom data are being temporarily cached.
                   7714: my $cacheduser='';
                   7715: # Cached blockers for this user (a hash of blocking items).
                   7716: my %cachedblockers=();
                   7717: # When the data were last cached.
                   7718: my $cachedlast='';
                   7719: 
                   7720: sub load_all_blockers {
                   7721:     my ($uname,$udom,$blocks)=@_;
                   7722:     if (($uname ne '') && ($udom ne '')) {
                   7723:         if (($cacheduser eq $uname.':'.$udom) &&
                   7724:             (abs($cachedlast-time)<5)) {
                   7725:             return;
                   7726:         }
                   7727:     }
                   7728:     $cachedlast=time;
                   7729:     $cacheduser=$uname.':'.$udom;
                   7730:     %cachedblockers = &get_commblock_resources($blocks);
                   7731: }
                   7732: 
1.1162    raeburn  7733: sub get_comm_blocks {
                   7734:     my ($cdom,$cnum) = @_;
                   7735:     if ($cdom eq '' || $cnum eq '') {
                   7736:         return unless ($env{'request.course.id'});
                   7737:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7738:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7739:     }
                   7740:     my %commblocks;
                   7741:     my $hashid=$cdom.'_'.$cnum;
                   7742:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   7743:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   7744:         %commblocks = %{$blocksref};
                   7745:     } else {
                   7746:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   7747:         my $cachetime = 600;
                   7748:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   7749:     }
                   7750:     return %commblocks;
                   7751: }
                   7752: 
1.1172.2.66  raeburn  7753: sub get_commblock_resources {
                   7754:     my ($blocks) = @_;
                   7755:     my %blockers = ();
                   7756:     return %blockers unless ($env{'request.course.id'});
                   7757:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  7758:     my %commblocks;
                   7759:     if (ref($blocks) eq 'HASH') {
                   7760:         %commblocks = %{$blocks};
                   7761:     } else {
                   7762:         %commblocks = &get_comm_blocks();
                   7763:     }
1.1172.2.66  raeburn  7764:     return %blockers unless (keys(%commblocks) > 0);
1.1163    raeburn  7765:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66  raeburn  7766:     return %blockers unless (ref($navmap));
                   7767:     my $now = time;
1.1162    raeburn  7768:     foreach my $block (keys(%commblocks)) {
                   7769:         if ($block =~ /^(\d+)____(\d+)$/) {
                   7770:             my ($start,$end) = ($1,$2);
                   7771:             if ($start <= $now && $end >= $now) {
                   7772:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7773:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7774:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66  raeburn  7775:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7776:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162    raeburn  7777:                             }
                   7778:                         }
                   7779:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66  raeburn  7780:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7781:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  7782:                             }
                   7783:                         }
                   7784:                     }
                   7785:                 }
                   7786:             }
                   7787:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   7788:             my $item = $1;
1.1163    raeburn  7789:             my @to_test;
1.1162    raeburn  7790:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7791:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.66  raeburn  7792:                     my @interval;
                   7793:                     my $type = 'map';
                   7794:                     if ($item eq 'course') {
                   7795:                         $type = 'course';
                   7796:                         @interval=&EXT("resource.0.interval");
                   7797:                     } else {
                   7798:                         if ($item =~ /___\d+___/) {
                   7799:                             $type = 'resource';
                   7800:                             @interval=&EXT("resource.0.interval",$item);
                   7801:                             if (ref($navmap)) {
                   7802:                                 my $res = $navmap->getBySymb($item);
                   7803:                                 push(@to_test,$res);
                   7804:                             }
1.1162    raeburn  7805:                         } else {
1.1172.2.66  raeburn  7806:                             my $mapsymb = &symbread($item,1);
                   7807:                             if ($mapsymb) {
                   7808:                                 if (ref($navmap)) {
                   7809:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   7810:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   7811:                                     foreach my $res (@to_test) {
                   7812:                                         my $symb = $res->symb();
                   7813:                                         next if ($symb eq $mapsymb);
                   7814:                                         if ($symb ne '') {
                   7815:                                             @interval=&EXT("resource.0.interval",$symb);
                   7816:                                             if ($interval[1] eq 'map') {
                   7817:                                                 last;
1.1162    raeburn  7818:                                             }
                   7819:                                         }
                   7820:                                     }
                   7821:                                 }
                   7822:                             }
                   7823:                         }
1.1172.2.66  raeburn  7824:                     }
1.1172.2.93.4  1(raebur 7825:7):                     if ($interval[0] =~ /^(\d+)/) {
                   7826:7):                         my $timelimit = $1;
1.1172.2.66  raeburn  7827:                         my $first_access;
                   7828:                         if ($type eq 'resource') {
                   7829:                             $first_access=&get_first_access($interval[1],$item);
                   7830:                         } elsif ($type eq 'map') {
                   7831:                             $first_access=&get_first_access($interval[1],undef,$item);
                   7832:                         } else {
                   7833:                             $first_access=&get_first_access($interval[1]);
                   7834:                         }
                   7835:                         if ($first_access) {
1.1172.2.93.4  1(raebur 7836:7):                             my $timesup = $first_access+$timelimit;
1.1172.2.66  raeburn  7837:                             if ($timesup > $now) {
                   7838:                                 my $activeblock;
                   7839:                                 foreach my $res (@to_test) {
                   7840:                                     if ($res->answerable()) {
                   7841:                                         $activeblock = 1;
                   7842:                                         last;
                   7843:                                     }
                   7844:                                 }
                   7845:                                 if ($activeblock) {
                   7846:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   7847:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7848:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   7849:                                          }
                   7850:                                     }
                   7851:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   7852:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7853:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  7854:                                         }
1.1162    raeburn  7855:                                     }
                   7856:                                 }
                   7857:                             }
                   7858:                         }
                   7859:                     }
                   7860:                 }
                   7861:             }
                   7862:         }
                   7863:     }
1.1172.2.66  raeburn  7864:     return %blockers;
1.1162    raeburn  7865: }
                   7866: 
1.1172.2.66  raeburn  7867: sub has_comm_blocking {
                   7868:     my ($priv,$symb,$uri,$blocks) = @_;
                   7869:     my @blockers;
                   7870:     return unless ($env{'request.course.id'});
                   7871:     return unless ($priv eq 'bre');
                   7872:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   7873:     return if ($env{'request.state'} eq 'construct');
                   7874:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   7875:     return unless (keys(%cachedblockers) > 0);
                   7876:     my (%possibles,@symbs);
                   7877:     if (!$symb) {
                   7878:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  7879:     }
1.1172.2.66  raeburn  7880:     if ($symb) {
                   7881:         @symbs = ($symb);
                   7882:     } elsif (keys(%possibles)) {
                   7883:         @symbs = keys(%possibles);
                   7884:     }
                   7885:     my $noblock;
                   7886:     foreach my $symb (@symbs) {
                   7887:         last if ($noblock);
                   7888:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   7889:         foreach my $block (keys(%cachedblockers)) {
                   7890:             if ($block =~ /^firstaccess____(.+)$/) {
                   7891:                 my $item = $1;
                   7892:                 if (($item eq $map) || ($item eq $symb)) {
                   7893:                     $noblock = 1;
                   7894:                     last;
                   7895:                 }
1.1162    raeburn  7896:             }
1.1172.2.66  raeburn  7897:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   7898:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   7899:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   7900:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   7901:                             push(@blockers,$block);
                   7902:                         }
                   7903:                     }
                   7904:                 }
                   7905:             }
                   7906:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   7907:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   7908:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   7909:                         push(@blockers,$block);
                   7910:                     }
                   7911:                 }
1.1162    raeburn  7912:             }
                   7913:         }
                   7914:     }
1.1172.2.66  raeburn  7915:     return if ($noblock);
                   7916:     return @blockers;
                   7917: }
1.1162    raeburn  7918: }
                   7919: 
1.1172.2.66  raeburn  7920: # -------------------------------- Deversion and split uri into path an filename
                   7921: 
1.1133    foxr     7922: #
1.1172.2.66  raeburn  7923: #   Removes the version from a URI and
1.1133    foxr     7924: #   splits it in to its filename and path to the filename.
                   7925: #   Seems like File::Basename could have done this more clearly.
                   7926: #   Parameters:
                   7927: #      $uri   - input URI
                   7928: #   Returns:
                   7929: #     Two element list consisting of 
                   7930: #     $pathname  - the URI up to and excluding the trailing /
                   7931: #     $filename  - The part of the URI following the last /
                   7932: #  NOTE:
                   7933: #    Another realization of this is simply:
                   7934: #    use File::Basename;
                   7935: #    ...
                   7936: #    $uri = shift;
                   7937: #    $filename = basename($uri);
                   7938: #    $path     = dirname($uri);
                   7939: #    return ($filename, $path);
                   7940: #
                   7941: #     The implementation below is probably faster however.
                   7942: #
1.710     albertel 7943: sub split_uri_for_cond {
                   7944:     my $uri=&deversion(&declutter(shift));
                   7945:     my @uriparts=split(/\//,$uri);
                   7946:     my $filename=pop(@uriparts);
                   7947:     my $pathname=join('/',@uriparts);
                   7948:     return ($pathname,$filename);
                   7949: }
1.232     www      7950: # --------------------------------------------------- Is a resource on the map?
                   7951: 
                   7952: sub is_on_map {
1.710     albertel 7953:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 7954:     #Trying to find the conditional for the file
1.620     albertel 7955:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 7956: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      7957:     if ($match) {
1.289     bowersj2 7958: 	return (1,$1);
                   7959:     } else {
1.434     www      7960: 	return (0,0);
1.289     bowersj2 7961:     }
1.12      www      7962: }
                   7963: 
1.427     www      7964: # --------------------------------------------------------- Get symb from alias
                   7965: 
                   7966: sub get_symb_from_alias {
                   7967:     my $symb=shift;
                   7968:     my ($map,$resid,$url)=&decode_symb($symb);
                   7969: # Already is a symb
                   7970:     if ($url) { return $symb; }
                   7971: # Must be an alias
                   7972:     my $aliassymb='';
                   7973:     my %bighash;
1.620     albertel 7974:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      7975:                             &GDBM_READER(),0640)) {
                   7976:         my $rid=$bighash{'mapalias_'.$symb};
                   7977: 	if ($rid) {
                   7978: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 7979: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   7980: 				    $resid,$bighash{'src_'.$rid});
1.427     www      7981: 	}
                   7982:         untie %bighash;
                   7983:     }
                   7984:     return $aliassymb;
                   7985: }
                   7986: 
1.12      www      7987: # ----------------------------------------------------------------- Define Role
                   7988: 
                   7989: sub definerole {
                   7990:   if (allowed('mcr','/')) {
1.1172.2.84  raeburn  7991:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 7992:     foreach my $role (split(':',$sysrole)) {
                   7993: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7994:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   7995:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   7996: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7997:                return "refused:s:$crole&$cqual"; 
                   7998:             }
                   7999:         }
1.191     harris41 8000:     }
1.800     albertel 8001:     foreach my $role (split(':',$domrole)) {
                   8002: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8003:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   8004:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   8005: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      8006:                return "refused:d:$crole&$cqual"; 
                   8007:             }
                   8008:         }
1.191     harris41 8009:     }
1.800     albertel 8010:     foreach my $role (split(':',$courole)) {
                   8011: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8012:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   8013:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   8014: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8015:                return "refused:c:$crole&$cqual"; 
                   8016:             }
                   8017:         }
1.191     harris41 8018:     }
1.1172.2.84  raeburn  8019:     my $uhome;
                   8020:     if (($uname ne '') && ($udom ne '')) {
                   8021:         $uhome = &homeserver($uname,$udom);
                   8022:         return $uhome if ($uhome eq 'no_host');
                   8023:     } else {
                   8024:         $uname = $env{'user.name'};
                   8025:         $udom = $env{'user.domain'};
                   8026:         $uhome = $env{'user.home'};
                   8027:     }
1.620     albertel 8028:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84  raeburn  8029:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      8030:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84  raeburn  8031:     return reply($command,$uhome);
1.12      www      8032:   } else {
                   8033:     return 'refused';
                   8034:   }
1.105     harris41 8035: }
                   8036: 
                   8037: # ---------------- Make a metadata query against the network of library servers
                   8038: 
                   8039: sub metadata_query {
1.1172.2.33  raeburn  8040:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 8041:     my %rhash;
1.845     albertel 8042:     my %libserv = &all_library();
1.244     matthew  8043:     my @server_list = (defined($server_array) ? @$server_array
                   8044:                                               : keys(%libserv) );
                   8045:     for my $server (@server_list) {
1.1172.2.33  raeburn  8046:         my $domains = '';
                   8047:         if (ref($domains_hash) eq 'HASH') {
                   8048:             $domains = $domains_hash->{$server};    
                   8049:         }
1.118     harris41 8050: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  8051: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 8052: 	    $rhash{$server}=$reply;
                   8053: 	}
                   8054: 	else {
                   8055: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  8056: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 8057: 			     $server);
                   8058: 	    $rhash{$server}=$reply;
                   8059: 	}
1.112     harris41 8060:     }
1.118     harris41 8061:     return \%rhash;
1.240     www      8062: }
                   8063: 
                   8064: # ----------------------------------------- Send log queries and wait for reply
                   8065: 
                   8066: sub log_query {
                   8067:     my ($uname,$udom,$query,%filters)=@_;
                   8068:     my $uhome=&homeserver($uname,$udom);
                   8069:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 8070:     my $uhost=&hostname($uhome);
1.800     albertel 8071:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      8072:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   8073:                        $uhome);
1.479     albertel 8074:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      8075:     return get_query_reply($queryid);
                   8076: }
                   8077: 
1.818     raeburn  8078: # -------------------------- Update MySQL table for portfolio file
                   8079: 
                   8080: sub update_portfolio_table {
1.821     raeburn  8081:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  8082:     if ($group ne '') {
                   8083:         $file_name =~s /^\Q$group\E//;
                   8084:     }
1.818     raeburn  8085:     my $homeserver = &homeserver($uname,$udom);
                   8086:     my $queryid=
1.821     raeburn  8087:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   8088:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  8089:     my $reply = &get_query_reply($queryid);
                   8090:     return $reply;
                   8091: }
                   8092: 
1.899     raeburn  8093: # -------------------------- Update MySQL allusers table
                   8094: 
                   8095: sub update_allusers_table {
                   8096:     my ($uname,$udom,$names) = @_;
                   8097:     my $homeserver = &homeserver($uname,$udom);
                   8098:     my $queryid=
                   8099:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   8100:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   8101:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   8102:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   8103:                'generation='.&escape($names->{'generation'}).'%%'.
                   8104:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   8105:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  8106:     return;
1.899     raeburn  8107: }
                   8108: 
1.508     raeburn  8109: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  8110: 
                   8111: sub fetch_enrollment_query {
1.511     raeburn  8112:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79  raeburn  8113:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  8114:     my $maxtries = 1;
1.508     raeburn  8115:     if ($context eq 'automated') {
                   8116:         $homeserver = $perlvar{'lonHostID'};
1.1172.2.79  raeburn  8117:         $sleep = 2;
                   8118:         $loopmax = 100;
1.547     raeburn  8119:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  8120:     } else {
                   8121:         $homeserver = &homeserver($cnum,$dom);
                   8122:     }
1.838     albertel 8123:     my $host=&hostname($homeserver);
1.506     raeburn  8124:     my $cmd = '';
1.1000    raeburn  8125:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 8126:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  8127:     }
                   8128:     $cmd =~ s/%%$//;
                   8129:     $cmd = &escape($cmd);
                   8130:     my $query = 'fetchenrollment';
1.620     albertel 8131:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  8132:     unless ($queryid=~/^\Q$host\E\_/) { 
                   8133:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   8134:         return 'error: '.$queryid;
                   8135:     }
1.1172.2.93  raeburn  8136:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8137:     my $tries = 1;
                   8138:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79  raeburn  8139:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8140:         $tries ++;
                   8141:     }
1.526     raeburn  8142:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 8143:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  8144:     } else {
1.901     albertel 8145:         my @responses = split(/:/,$reply);
1.1172.2.82  raeburn  8146:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 8147:             foreach my $line (@responses) {
                   8148:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  8149:                 $$replyref{$key} = $value;
                   8150:             }
                   8151:         } else {
1.1117    foxr     8152:             my $pathname = LONCAPA::tempdir();
1.800     albertel 8153:             foreach my $line (@responses) {
                   8154:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  8155:                 $$replyref{$key} = $value;
                   8156:                 if ($value > 0) {
1.800     albertel 8157:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   8158:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  8159:                         my $destname = $pathname.'/'.$filename;
                   8160:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  8161:                         if ($xml_classlist =~ /^error/) {
                   8162:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   8163:                         } else {
1.506     raeburn  8164:                             if ( open(FILE,">$destname") ) {
                   8165:                                 print FILE &unescape($xml_classlist);
                   8166:                                 close(FILE);
1.526     raeburn  8167:                             } else {
                   8168:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  8169:                             }
                   8170:                         }
                   8171:                     }
                   8172:                 }
                   8173:             }
                   8174:         }
                   8175:         return 'ok';
                   8176:     }
                   8177:     return 'error';
                   8178: }
                   8179: 
1.242     www      8180: sub get_query_reply {
1.1172.2.79  raeburn  8181:     my ($queryid,$sleep,$loopmax) = @_;
                   8182:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   8183:         $sleep = 0.2;
                   8184:     }
                   8185:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   8186:         $loopmax = 100;
                   8187:     }
1.1117    foxr     8188:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      8189:     my $reply='';
1.1172.2.79  raeburn  8190:     for (1..$loopmax) {
                   8191: 	sleep($sleep);
1.240     www      8192:         if (-e $replyfile.'.end') {
1.448     albertel 8193: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 8194: 		$reply = join('',<$fh>);
                   8195: 		close($fh);
1.240     www      8196: 	   } else { return 'error: reply_file_error'; }
1.242     www      8197:            return &unescape($reply);
                   8198: 	}
1.240     www      8199:     }
1.242     www      8200:     return 'timeout:'.$queryid;
1.240     www      8201: }
                   8202: 
                   8203: sub courselog_query {
1.241     www      8204: #
                   8205: # possible filters:
                   8206: # url: url or symb
                   8207: # username
                   8208: # domain
                   8209: # action: view, submit, grade
                   8210: # start: timestamp
                   8211: # end: timestamp
                   8212: #
1.240     www      8213:     my (%filters)=@_;
1.620     albertel 8214:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      8215:     if ($filters{'url'}) {
                   8216: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   8217:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   8218:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   8219:     }
1.620     albertel 8220:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8221:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      8222:     return &log_query($cname,$cdom,'courselog',%filters);
                   8223: }
                   8224: 
                   8225: sub userlog_query {
1.858     raeburn  8226: #
                   8227: # possible filters:
                   8228: # action: log check role
                   8229: # start: timestamp
                   8230: # end: timestamp
                   8231: #
1.240     www      8232:     my ($uname,$udom,%filters)=@_;
                   8233:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      8234: }
                   8235: 
1.506     raeburn  8236: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   8237: 
                   8238: sub auto_run {
1.508     raeburn  8239:     my ($cnum,$cdom) = @_;
1.876     raeburn  8240:     my $response = 0;
                   8241:     my $settings;
                   8242:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   8243:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   8244:         $settings = $domconfig{'autoenroll'};
                   8245:         if ($settings->{'run'} eq '1') {
                   8246:             $response = 1;
                   8247:         }
                   8248:     } else {
1.934     raeburn  8249:         my $homeserver;
                   8250:         if (&is_course($cdom,$cnum)) {
                   8251:             $homeserver = &homeserver($cnum,$cdom);
                   8252:         } else {
                   8253:             $homeserver = &domain($cdom,'primary');
                   8254:         }
                   8255:         if ($homeserver ne 'no_host') {
                   8256:             $response = &reply('autorun:'.$cdom,$homeserver);
                   8257:         }
1.876     raeburn  8258:     }
1.506     raeburn  8259:     return $response;
                   8260: }
1.776     albertel 8261: 
1.506     raeburn  8262: sub auto_get_sections {
1.508     raeburn  8263:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  8264:     my $homeserver;
                   8265:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   8266:         $homeserver = &homeserver($cnum,$cdom);
                   8267:     }
                   8268:     if (!defined($homeserver)) { 
                   8269:         if ($cdom =~ /^$match_domain$/) {
                   8270:             $homeserver = &domain($cdom,'primary');
                   8271:         }
                   8272:     }
                   8273:     my @secs;
                   8274:     if (defined($homeserver)) {
                   8275:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   8276:         unless ($response eq 'refused') {
                   8277:             @secs = split(/:/,$response);
                   8278:         }
1.506     raeburn  8279:     }
                   8280:     return @secs;
                   8281: }
1.776     albertel 8282: 
1.506     raeburn  8283: sub auto_new_course {
1.1099    raeburn  8284:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  8285:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  8286:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  8287:     return $response;
                   8288: }
1.776     albertel 8289: 
1.506     raeburn  8290: sub auto_validate_courseID {
1.508     raeburn  8291:     my ($cnum,$cdom,$inst_course_id) = @_;
                   8292:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  8293:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  8294:     return $response;
                   8295: }
1.776     albertel 8296: 
1.1007    raeburn  8297: sub auto_validate_instcode {
1.1020    raeburn  8298:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  8299:     my ($homeserver,$response);
                   8300:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8301:         $homeserver = &homeserver($cnum,$cdom);
                   8302:     }
                   8303:     if (!defined($homeserver)) {
                   8304:         if ($cdom =~ /^$match_domain$/) {
                   8305:             $homeserver = &domain($cdom,'primary');
                   8306:         }
                   8307:     }
1.1065    raeburn  8308:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   8309:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  8310:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   8311:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  8312: }
                   8313: 
1.506     raeburn  8314: sub auto_create_password {
1.873     raeburn  8315:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   8316:     my ($homeserver,$response);
1.506     raeburn  8317:     my $create_passwd = 0;
                   8318:     my $authchk = '';
1.873     raeburn  8319:     if ($udom =~ /^$match_domain$/) {
                   8320:         $homeserver = &domain($udom,'primary');
                   8321:     }
                   8322:     if ($homeserver eq '') {
                   8323:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8324:             $homeserver = &homeserver($cnum,$cdom);
                   8325:         }
                   8326:     }
                   8327:     if ($homeserver eq '') {
                   8328:         $authchk = 'nodomain';
1.506     raeburn  8329:     } else {
1.873     raeburn  8330:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   8331:         if ($response eq 'refused') {
                   8332:             $authchk = 'refused';
                   8333:         } else {
1.901     albertel 8334:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  8335:         }
1.506     raeburn  8336:     }
                   8337:     return ($authparam,$create_passwd,$authchk);
                   8338: }
                   8339: 
1.706     raeburn  8340: sub auto_photo_permission {
                   8341:     my ($cnum,$cdom,$students) = @_;
                   8342:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 8343:     my ($outcome,$perm_reqd,$conditions) = 
                   8344: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 8345:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8346: 	return (undef,undef);
                   8347:     }
1.706     raeburn  8348:     return ($outcome,$perm_reqd,$conditions);
                   8349: }
                   8350: 
                   8351: sub auto_checkphotos {
                   8352:     my ($uname,$udom,$pid) = @_;
                   8353:     my $homeserver = &homeserver($uname,$udom);
                   8354:     my ($result,$resulttype);
                   8355:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 8356: 				   &escape($uname).':'.&escape($pid),
                   8357: 				   $homeserver));
1.709     albertel 8358:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8359: 	return (undef,undef);
                   8360:     }
1.706     raeburn  8361:     if ($outcome) {
                   8362:         ($result,$resulttype) = split(/:/,$outcome);
                   8363:     } 
                   8364:     return ($result,$resulttype);
                   8365: }
                   8366: 
                   8367: sub auto_photochoice {
                   8368:     my ($cnum,$cdom) = @_;
                   8369:     my $homeserver = &homeserver($cnum,$cdom);
                   8370:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 8371: 						       &escape($cdom),
                   8372: 						       $homeserver)));
1.709     albertel 8373:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8374: 	return (undef,undef);
                   8375:     }
1.706     raeburn  8376:     return ($update,$comment);
                   8377: }
                   8378: 
                   8379: sub auto_photoupdate {
                   8380:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   8381:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 8382:     my $host=&hostname($homeserver);
1.706     raeburn  8383:     my $cmd = '';
                   8384:     my $maxtries = 1;
1.800     albertel 8385:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   8386:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  8387:     }
                   8388:     $cmd =~ s/%%$//;
                   8389:     $cmd = &escape($cmd);
                   8390:     my $query = 'institutionalphotos';
                   8391:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   8392:     unless ($queryid=~/^\Q$host\E\_/) {
                   8393:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   8394:         return 'error: '.$queryid;
                   8395:     }
                   8396:     my $reply = &get_query_reply($queryid);
                   8397:     my $tries = 1;
                   8398:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   8399:         $reply = &get_query_reply($queryid);
                   8400:         $tries ++;
                   8401:     }
                   8402:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   8403:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   8404:     } else {
                   8405:         my @responses = split(/:/,$reply);
                   8406:         my $outcome = shift(@responses); 
                   8407:         foreach my $item (@responses) {
                   8408:             my ($key,$value) = split(/=/,$item);
                   8409:             $$photo{$key} = $value;
                   8410:         }
                   8411:         return $outcome;
                   8412:     }
                   8413:     return 'error';
                   8414: }
                   8415: 
1.521     raeburn  8416: sub auto_instcode_format {
1.793     albertel 8417:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   8418: 	$cat_order) = @_;
1.521     raeburn  8419:     my $courses = '';
1.772     raeburn  8420:     my @homeservers;
1.521     raeburn  8421:     if ($caller eq 'global') {
1.841     albertel 8422: 	my %servers = &get_servers($codedom,'library');
                   8423: 	foreach my $tryserver (keys(%servers)) {
                   8424: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8425: 		push(@homeservers,$tryserver);
                   8426: 	    }
1.584     raeburn  8427:         }
1.1022    raeburn  8428:     } elsif ($caller eq 'requests') {
                   8429:         if ($codedom =~ /^$match_domain$/) {
                   8430:             my $chome = &domain($codedom,'primary');
                   8431:             unless ($chome eq 'no_host') {
                   8432:                 push(@homeservers,$chome);
                   8433:             }
                   8434:         }
1.521     raeburn  8435:     } else {
1.772     raeburn  8436:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  8437:     }
1.793     albertel 8438:     foreach my $code (keys(%{$instcodes})) {
                   8439:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  8440:     }
                   8441:     chop($courses);
1.772     raeburn  8442:     my $ok_response = 0;
                   8443:     my $response;
                   8444:     while (@homeservers > 0 && $ok_response == 0) {
                   8445:         my $server = shift(@homeservers); 
                   8446:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   8447:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   8448:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 8449: 		split(/:/,$response);
1.772     raeburn  8450:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   8451:             push(@{$codetitles},&str2array($codetitles_str));
                   8452:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   8453:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   8454:             $ok_response = 1;
                   8455:         }
                   8456:     }
                   8457:     if ($ok_response) {
1.521     raeburn  8458:         return 'ok';
1.772     raeburn  8459:     } else {
                   8460:         return $response;
1.521     raeburn  8461:     }
                   8462: }
                   8463: 
1.792     raeburn  8464: sub auto_instcode_defaults {
                   8465:     my ($domain,$returnhash,$code_order) = @_;
                   8466:     my @homeservers;
1.841     albertel 8467: 
                   8468:     my %servers = &get_servers($domain,'library');
                   8469:     foreach my $tryserver (keys(%servers)) {
                   8470: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8471: 	    push(@homeservers,$tryserver);
                   8472: 	}
1.792     raeburn  8473:     }
1.841     albertel 8474: 
1.792     raeburn  8475:     my $response;
1.841     albertel 8476:     foreach my $server (@homeservers) {
1.792     raeburn  8477:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 8478:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   8479: 	
                   8480: 	foreach my $pair (split(/\&/,$response)) {
                   8481: 	    my ($name,$value)=split(/\=/,$pair);
                   8482: 	    if ($name eq 'code_order') {
                   8483: 		@{$code_order} = split(/\&/,&unescape($value));
                   8484: 	    } else {
                   8485: 		$returnhash->{&unescape($name)}=&unescape($value);
                   8486: 	    }
                   8487: 	}
                   8488: 	return 'ok';
1.792     raeburn  8489:     }
1.841     albertel 8490: 
                   8491:     return $response;
1.1003    raeburn  8492: }
                   8493: 
                   8494: sub auto_possible_instcodes {
1.1007    raeburn  8495:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   8496:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   8497:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8498:         return;
                   8499:     }
1.1003    raeburn  8500:     my (@homeservers,$uhome);
                   8501:     if (defined(&domain($domain,'primary'))) {
                   8502:         $uhome=&domain($domain,'primary');
                   8503:         push(@homeservers,&domain($domain,'primary'));
                   8504:     } else {
                   8505:         my %servers = &get_servers($domain,'library');
                   8506:         foreach my $tryserver (keys(%servers)) {
                   8507:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8508:                 push(@homeservers,$tryserver);
                   8509:             }
                   8510:         }
                   8511:     }
                   8512:     my $response;
                   8513:     foreach my $server (@homeservers) {
                   8514:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   8515:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  8516:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   8517:             split(':',$response);
                   8518:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   8519:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  8520:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  8521:             my ($name,$value)=split('=',$item);
                   8522:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8523:         }
                   8524:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  8525:             my ($name,$value)=split('=',$item);
                   8526:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8527:         }
                   8528:         return 'ok';
                   8529:     }
                   8530:     return $response;
                   8531: }
1.792     raeburn  8532: 
1.1010    raeburn  8533: sub auto_courserequest_checks {
                   8534:     my ($dom) = @_;
1.1020    raeburn  8535:     my ($homeserver,%validations);
                   8536:     if ($dom =~ /^$match_domain$/) {
                   8537:         $homeserver = &domain($dom,'primary');
                   8538:     }
                   8539:     unless ($homeserver eq 'no_host') {
                   8540:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   8541:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8542:             my @items = split(/&/,$response);
                   8543:             foreach my $item (@items) {
                   8544:                 my ($key,$value) = split('=',$item);
                   8545:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   8546:             }
                   8547:         }
                   8548:     }
1.1010    raeburn  8549:     return %validations; 
                   8550: }
                   8551: 
1.1020    raeburn  8552: sub auto_courserequest_validation {
1.1172.2.43  raeburn  8553:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  8554:     my ($homeserver,$response);
                   8555:     if ($dom =~ /^$match_domain$/) {
                   8556:         $homeserver = &domain($dom,'primary');
                   8557:     }
1.1172.2.43  raeburn  8558:     unless ($homeserver eq 'no_host') {
                   8559:         my $customdata;
                   8560:         if (ref($custominfo) eq 'HASH') {
                   8561:             $customdata = &freeze_escape($custominfo);
                   8562:         }
1.1020    raeburn  8563:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  8564:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43  raeburn  8565:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   8566:                                     $customdata,$homeserver));
1.1020    raeburn  8567:     }
                   8568:     return $response;
                   8569: }
                   8570: 
1.777     albertel 8571: sub auto_validate_class_sec {
1.918     raeburn  8572:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  8573:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  8574:     my $ownerlist;
                   8575:     if (ref($owners) eq 'ARRAY') {
                   8576:         $ownerlist = join(',',@{$owners});
                   8577:     } else {
                   8578:         $ownerlist = $owners;
                   8579:     }
1.773     raeburn  8580:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  8581:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  8582:     return $response;
                   8583: }
                   8584: 
1.1172.2.38  raeburn  8585: sub auto_crsreq_update {
                   8586:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45  raeburn  8587:         $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38  raeburn  8588:     my ($homeserver,%crsreqresponse);
                   8589:     if ($cdom =~ /^$match_domain$/) {
                   8590:         $homeserver = &domain($cdom,'primary');
                   8591:     }
                   8592:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8593:         my $info;
                   8594:         if (ref($inbound) eq 'HASH') {
                   8595:             $info = &freeze_escape($inbound);
                   8596:         }
                   8597:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   8598:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   8599:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45  raeburn  8600:                             &escape($title).':'.&escape($code).':'.
                   8601:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38  raeburn  8602:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8603:             my @items = split(/&/,$response);
                   8604:             foreach my $item (@items) {
                   8605:                 my ($key,$value) = split('=',$item);
                   8606:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   8607:             }
                   8608:         }
                   8609:     }
                   8610:     return \%crsreqresponse;
                   8611: }
                   8612: 
1.1172.2.78  raeburn  8613: sub auto_export_grades {
                   8614:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   8615:     my ($homeserver,%exportresponse);
                   8616:     if ($cdom =~ /^$match_domain$/) {
                   8617:         $homeserver = &domain($cdom,'primary');
                   8618:     }
                   8619:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8620:         my $info;
                   8621:         if (ref($inforef) eq 'HASH') {
                   8622:             $info = &freeze_escape($inforef);
                   8623:         }
                   8624:         if (ref($gradesref) eq 'HASH') {
                   8625:             my $grades = &freeze_escape($gradesref);
                   8626:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   8627:                                 $info.':'.$grades,$homeserver);
                   8628:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   8629:                 my @items = split(/&/,$response);
                   8630:                 foreach my $item (@items) {
                   8631:                     my ($key,$value) = split('=',$item);
                   8632:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   8633:                 }
                   8634:             }
                   8635:         }
                   8636:     }
                   8637:     return \%exportresponse;
                   8638: }
                   8639: 
1.1172.2.68  raeburn  8640: sub check_instcode_cloning {
                   8641:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   8642:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8643:         return;
                   8644:     }
                   8645:     my $canclone;
                   8646:     if (@{$code_order} > 0) {
                   8647:         my $instcoderegexp ='^';
                   8648:         my @clonecodes = split(/\&/,$cloner);
                   8649:         foreach my $item (@{$code_order}) {
                   8650:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   8651:                 foreach my $pair (@clonecodes) {
                   8652:                     my ($key,$val) = split(/\=/,$pair,2);
                   8653:                     $val = &unescape($val);
                   8654:                     if ($key eq $item) {
                   8655:                         $instcoderegexp .= '('.$val.')';
                   8656:                         last;
                   8657:                     }
                   8658:                 }
                   8659:             } else {
                   8660:                 $instcoderegexp .= $codedefaults->{$item};
                   8661:             }
                   8662:         }
                   8663:         $instcoderegexp .= '$';
                   8664:         my (@from,@to);
                   8665:         eval {
                   8666:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8667:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8668:         };
                   8669:         if ((@from > 0) && (@to > 0)) {
                   8670:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8671:             if (!@diffs) {
                   8672:                 $canclone = 1;
                   8673:             }
                   8674:         }
                   8675:     }
                   8676:     return $canclone;
                   8677: }
                   8678: 
                   8679: sub default_instcode_cloning {
                   8680:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   8681:     my (%codedefaults,@code_order,$canclone);
                   8682:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   8683:         %codedefaults = %{$codedefaultsref};
                   8684:         @code_order = @{$codeorderref};
                   8685:     } elsif ($clonedom) {
                   8686:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   8687:     }
                   8688:     if (($domdefclone) && (@code_order)) {
                   8689:         my @clonecodes = split(/\+/,$domdefclone);
                   8690:         my $instcoderegexp ='^';
                   8691:         foreach my $item (@code_order) {
                   8692:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   8693:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   8694:             } else {
                   8695:                 $instcoderegexp .= $codedefaults{$item};
                   8696:             }
                   8697:         }
                   8698:         $instcoderegexp .= '$';
                   8699:         my (@from,@to);
                   8700:         eval {
                   8701:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8702:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8703:         };
                   8704:         if ((@from > 0) && (@to > 0)) {
                   8705:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8706:             if (!@diffs) {
                   8707:                 $canclone = 1;
                   8708:             }
                   8709:         }
                   8710:     }
                   8711:     return $canclone;
                   8712: }
                   8713: 
1.679     raeburn  8714: # ------------------------------------------------------- Course Group routines
                   8715: 
                   8716: sub get_coursegroups {
1.809     raeburn  8717:     my ($cdom,$cnum,$group,$namespace) = @_;
                   8718:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  8719: }
                   8720: 
1.679     raeburn  8721: sub modify_coursegroup {
                   8722:     my ($cdom,$cnum,$groupsettings) = @_;
                   8723:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   8724: }
                   8725: 
1.809     raeburn  8726: sub toggle_coursegroup_status {
                   8727:     my ($cdom,$cnum,$group,$action) = @_;
                   8728:     my ($from_namespace,$to_namespace);
                   8729:     if ($action eq 'delete') {
                   8730:         $from_namespace = 'coursegroups';
                   8731:         $to_namespace = 'deleted_groups';
                   8732:     } else {
                   8733:         $from_namespace = 'deleted_groups';
                   8734:         $to_namespace = 'coursegroups';
                   8735:     }
                   8736:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  8737:     if (my $tmp = &error(%curr_group)) {
                   8738:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   8739:         return ('read error',$tmp);
                   8740:     } else {
                   8741:         my %savedsettings = %curr_group; 
1.809     raeburn  8742:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  8743:         my $deloutcome;
                   8744:         if ($result eq 'ok') {
1.809     raeburn  8745:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  8746:         } else {
                   8747:             return ('write error',$result);
                   8748:         }
                   8749:         if ($deloutcome eq 'ok') {
                   8750:             return 'ok';
                   8751:         } else {
                   8752:             return ('delete error',$deloutcome);
                   8753:         }
                   8754:     }
                   8755: }
                   8756: 
1.679     raeburn  8757: sub modify_group_roles {
1.957     raeburn  8758:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  8759:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   8760:     my $role = 'gr/'.&escape($userprivs);
                   8761:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  8762:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  8763:     if ($result eq 'ok') {
                   8764:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   8765:     }
1.679     raeburn  8766:     return $result;
                   8767: }
                   8768: 
                   8769: sub modify_coursegroup_membership {
                   8770:     my ($cdom,$cnum,$membership) = @_;
                   8771:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   8772:     return $result;
                   8773: }
                   8774: 
1.682     raeburn  8775: sub get_active_groups {
                   8776:     my ($udom,$uname,$cdom,$cnum) = @_;
                   8777:     my $now = time;
                   8778:     my %groups = ();
                   8779:     foreach my $key (keys(%env)) {
1.811     albertel 8780:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  8781:             my ($start,$end) = split(/\./,$env{$key});
                   8782:             if (($end!=0) && ($end<$now)) { next; }
                   8783:             if (($start!=0) && ($start>$now)) { next; }
                   8784:             if ($1 eq $cdom && $2 eq $cnum) {
                   8785:                 $groups{$3} = $env{$key} ;
                   8786:             }
                   8787:         }
                   8788:     }
                   8789:     return %groups;
                   8790: }
                   8791: 
1.683     raeburn  8792: sub get_group_membership {
                   8793:     my ($cdom,$cnum,$group) = @_;
                   8794:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   8795: }
                   8796: 
                   8797: sub get_users_groups {
                   8798:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  8799:     my @usersgroups;
1.683     raeburn  8800:     my $cachetime=1800;
                   8801: 
                   8802:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  8803:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   8804:     if (defined($cached)) {
1.734     albertel 8805:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  8806:     } else {  
                   8807:         $grouplist = '';
1.816     raeburn  8808:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  8809:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  8810:         my $access_end = $env{'course.'.$courseid.
                   8811:                               '.default_enrollment_end_date'};
                   8812:         my $now = time;
                   8813:         foreach my $key (keys(%roleshash)) {
                   8814:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   8815:                 my $group = $1;
                   8816:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   8817:                     my $start = $2;
                   8818:                     my $end = $1;
                   8819:                     if ($start == -1) { next; } # deleted from group
                   8820:                     if (($start!=0) && ($start>$now)) { next; }
                   8821:                     if (($end!=0) && ($end<$now)) {
                   8822:                         if ($access_end && $access_end < $now) {
                   8823:                             if ($access_end - $end < 86400) {
                   8824:                                 push(@usersgroups,$group);
1.733     raeburn  8825:                             }
                   8826:                         }
1.817     raeburn  8827:                         next;
1.733     raeburn  8828:                     }
1.817     raeburn  8829:                     push(@usersgroups,$group);
1.683     raeburn  8830:                 }
                   8831:             }
                   8832:         }
1.817     raeburn  8833:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   8834:         $grouplist = join(':',@usersgroups);
                   8835:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  8836:     }
1.733     raeburn  8837:     return @usersgroups;
1.683     raeburn  8838: }
                   8839: 
                   8840: sub devalidate_getgroups_cache {
                   8841:     my ($udom,$uname,$cdom,$cnum)=@_;
                   8842:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 8843: 
1.683     raeburn  8844:     my $hashid="$udom:$uname:$courseid";
                   8845:     &devalidate_cache_new('getgroups',$hashid);
                   8846: }
                   8847: 
1.12      www      8848: # ------------------------------------------------------------------ Plain Text
                   8849: 
                   8850: sub plaintext {
1.988     raeburn  8851:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  8852:     if ($short =~ m{^cr/}) {
1.758     albertel 8853: 	return (split('/',$short))[-1];
                   8854:     }
1.742     raeburn  8855:     if (!defined($cid)) {
                   8856:         $cid = $env{'request.course.id'};
                   8857:     }
                   8858:     my %rolenames = (
1.1008    raeburn  8859:                       Course    => 'std',
                   8860:                       Community => 'alt1',
1.742     raeburn  8861:                     );
1.1037    raeburn  8862:     if ($cid ne '') {
                   8863:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   8864:             unless ($forcedefault) {
                   8865:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   8866:                 &Apache::lonlocal::mt_escape(\$roletext);
                   8867:                 return &Apache::lonlocal::mt($roletext);
                   8868:             }
                   8869:         }
                   8870:     }
                   8871:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   8872:         (defined($rolenames{$type})) && 
                   8873:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  8874:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  8875:     } elsif ($cid ne '') {
                   8876:         my $crstype = $env{'course.'.$cid.'.type'};
                   8877:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   8878:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   8879:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   8880:         }
1.742     raeburn  8881:     }
1.1037    raeburn  8882:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      8883: }
                   8884: 
                   8885: # ----------------------------------------------------------------- Assign Role
                   8886: 
                   8887: sub assignrole {
1.957     raeburn  8888:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   8889:         $context)=@_;
1.21      www      8890:     my $mrole;
                   8891:     if ($role =~ /^cr\//) {
1.393     www      8892:         my $cwosec=$url;
1.811     albertel 8893:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      8894: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  8895:            my $refused = 1;
                   8896:            if ($context eq 'requestcourses') {
                   8897:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   8898:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   8899:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   8900:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8901:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8902:                            if ($crsenv{'internal.courseowner'} eq
                   8903:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   8904:                                $refused = '';
                   8905:                            }
                   8906:                        }
                   8907:                    }
                   8908:                }
                   8909:            }
                   8910:            if ($refused) {
                   8911:                &logthis('Refused custom assignrole: '.
                   8912:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   8913:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   8914:                return 'refused';
                   8915:            }
1.104     www      8916:         }
1.21      www      8917:         $mrole='cr';
1.678     raeburn  8918:     } elsif ($role =~ /^gr\//) {
                   8919:         my $cwogrp=$url;
1.811     albertel 8920:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  8921:         unless (&allowed('mdg',$cwogrp)) {
                   8922:             &logthis('Refused group assignrole: '.
                   8923:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   8924:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   8925:             return 'refused';
                   8926:         }
                   8927:         $mrole='gr';
1.21      www      8928:     } else {
1.82      www      8929:         my $cwosec=$url;
1.811     albertel 8930:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  8931:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   8932:             my $refused;
                   8933:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   8934:                 if (!(&allowed('c'.$role,$url))) {
                   8935:                     $refused = 1;
                   8936:                 }
                   8937:             } else {
                   8938:                 $refused = 1;
                   8939:             }
1.947     raeburn  8940:             if ($refused) {
1.1045    raeburn  8941:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8942:                 if (!$selfenroll && $context eq 'course') {
                   8943:                     my %crsenv;
                   8944:                     if ($role eq 'cc' || $role eq 'co') {
                   8945:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8946:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   8947:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   8948:                                 if ($crsenv{'internal.courseowner'} eq 
                   8949:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8950:                                     $refused = '';
                   8951:                                 }
                   8952:                             }
                   8953:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   8954:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   8955:                                 if ($crsenv{'internal.courseowner'} eq 
                   8956:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8957:                                     $refused = '';
                   8958:                                 }
                   8959:                             }
                   8960:                         }
                   8961:                     }
                   8962:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  8963:                     $refused = '';
1.1017    raeburn  8964:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  8965:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  8966:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  8967:                         my $wrongcc;
                   8968:                         if ($cnum =~ /^$match_community$/) {
                   8969:                             $wrongcc = 1 if ($role eq 'cc');
                   8970:                         } else {
                   8971:                             $wrongcc = 1 if ($role eq 'co');
                   8972:                         }
                   8973:                         unless ($wrongcc) {
                   8974:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8975:                             if ($crsenv{'internal.courseowner'} eq 
                   8976:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   8977:                                 $refused = '';
                   8978:                             }
1.1017    raeburn  8979:                         }
                   8980:                     }
1.1172.2.9  raeburn  8981:                 } elsif ($context eq 'requestauthor') {
                   8982:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   8983:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   8984:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   8985:                             $refused = '';
                   8986:                         } else {
                   8987:                             my %domdefaults = &get_domain_defaults($udom);
                   8988:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   8989:                                 my $checkbystatus;
                   8990:                                 if ($env{'user.adv'}) {
                   8991:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   8992:                                     if ($disposition eq 'automatic') {
                   8993:                                         $refused = '';
                   8994:                                     } elsif ($disposition eq '') {
                   8995:                                         $checkbystatus = 1;
                   8996:                                     }
                   8997:                                 } else {
                   8998:                                     $checkbystatus = 1;
                   8999:                                 }
                   9000:                                 if ($checkbystatus) {
                   9001:                                     if ($env{'environment.inststatus'}) {
                   9002:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   9003:                                         foreach my $type (@inststatuses) {
                   9004:                                             if (($type ne '') &&
                   9005:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   9006:                                                 $refused = '';
                   9007:                                             }
                   9008:                                         }
                   9009:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   9010:                                         $refused = '';
                   9011:                                     }
                   9012:                                 }
                   9013:                             }
                   9014:                         }
                   9015:                     }
1.1017    raeburn  9016:                 }
                   9017:                 if ($refused) {
1.947     raeburn  9018:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   9019:                              ' '.$role.' '.$end.' '.$start.' by '.
                   9020: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   9021:                     return 'refused';
                   9022:                 }
1.932     raeburn  9023:             }
1.1131    raeburn  9024:         } elsif ($role eq 'au') {
                   9025:             if ($url ne '/'.$udom.'/') {
                   9026:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   9027:                          ' to assign author role for '.$uname.':'.$udom.
                   9028:                          ' in domain: '.$url.' refused (wrong domain).');
                   9029:                 return 'refused';
                   9030:             }
1.104     www      9031:         }
1.21      www      9032:         $mrole=$role;
                   9033:     }
1.620     albertel 9034:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      9035:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      9036:     if ($end) { $command.='_'.$end; }
1.21      www      9037:     if ($start) {
                   9038: 	if ($end) { 
1.81      www      9039:            $command.='_'.$start; 
1.21      www      9040:         } else {
1.81      www      9041:            $command.='_0_'.$start;
1.21      www      9042:         }
                   9043:     }
1.739     raeburn  9044:     my $origstart = $start;
                   9045:     my $origend = $end;
1.957     raeburn  9046:     my $delflag;
1.357     www      9047: # actually delete
                   9048:     if ($deleteflag) {
1.373     www      9049: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      9050: # modify command to delete the role
1.620     albertel 9051:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      9052:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 9053: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      9054: # set start and finish to negative values for userrolelog
                   9055:            $start=-1;
                   9056:            $end=-1;
1.957     raeburn  9057:            $delflag = 1;
1.357     www      9058:         }
                   9059:     }
                   9060: # send command
1.349     www      9061:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      9062: # log new user role if status is ok
1.349     www      9063:     if ($answer eq 'ok') {
1.663     raeburn  9064: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  9065:         if (($role eq 'cc') || ($role eq 'in') ||
                   9066:             ($role eq 'ep') || ($role eq 'ad') ||
                   9067:             ($role eq 'ta') || ($role eq 'st') ||
                   9068:             ($role=~/^cr/) || ($role eq 'gr') ||
                   9069:             ($role eq 'co')) {
1.1172.2.13  raeburn  9070: # for course roles, perform group memberships changes triggered by role change.
                   9071:             unless ($role =~ /^gr/) {
                   9072:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   9073:                                                  $origstart,$selfenroll,$context);
                   9074:             }
1.1172.2.9  raeburn  9075:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9076:                            $selfenroll,$context);
                   9077:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90  raeburn  9078:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   9079:                  ($role eq 'da')) {
1.1172.2.9  raeburn  9080:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9081:                            $context);
                   9082:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   9083:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9084:                              $context);
                   9085:         }
1.1053    raeburn  9086:         if ($role eq 'cc') {
                   9087:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   9088:         }
1.349     www      9089:     }
                   9090:     return $answer;
1.169     harris41 9091: }
                   9092: 
1.1053    raeburn  9093: sub autoupdate_coowners {
                   9094:     my ($url,$end,$start,$uname,$udom) = @_;
                   9095:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   9096:     if (($cdom ne '') && ($cnum ne '')) {
                   9097:         my $now = time;
                   9098:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   9099:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   9100:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   9101:             my $instcode = $coursehash{'internal.coursecode'};
                   9102:             if ($instcode ne '') {
1.1056    raeburn  9103:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   9104:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  9105:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  9106:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   9107:                         if ($result eq 'valid') {
                   9108:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  9109:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9110:                                     push(@newcoowners,$coowner);
                   9111:                                 }
                   9112:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   9113:                                     push(@newcoowners,$uname.':'.$udom);
                   9114:                                 }
                   9115:                                 @newcoowners = sort(@newcoowners);
                   9116:                             } else {
                   9117:                                 push(@newcoowners,$uname.':'.$udom);
                   9118:                             }
                   9119:                         } else {
                   9120:                             if ($coursehash{'internal.co-owners'}) {
                   9121:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9122:                                     unless ($coowner eq $uname.':'.$udom) {
                   9123:                                         push(@newcoowners,$coowner);
                   9124:                                     }
                   9125:                                 }
                   9126:                                 unless (@newcoowners > 0) {
                   9127:                                     $delcoowners = 1;
                   9128:                                     $coowners = '';
                   9129:                                 }
                   9130:                             }
                   9131:                         }
                   9132:                         if (@newcoowners || $delcoowners) {
                   9133:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   9134:                                             $delcoowners,@newcoowners);
                   9135:                         }
                   9136:                     }
                   9137:                 }
                   9138:             }
                   9139:         }
                   9140:     }
                   9141: }
                   9142: 
                   9143: sub store_coowners {
                   9144:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   9145:     my $cid = $cdom.'_'.$cnum;
                   9146:     my ($coowners,$delresult,$putresult);
                   9147:     if (@newcoowners) {
                   9148:         $coowners = join(',',@newcoowners);
                   9149:         my %coownershash = (
                   9150:                             'internal.co-owners' => $coowners,
                   9151:                            );
                   9152:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   9153:         if ($putresult eq 'ok') {
                   9154:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   9155:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   9156:             }
                   9157:         }
                   9158:     }
                   9159:     if ($delcoowners) {
                   9160:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   9161:         if ($delresult eq 'ok') {
                   9162:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   9163:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   9164:             }
                   9165:         }
                   9166:     }
                   9167:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   9168:         my %crsinfo =
                   9169:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   9170:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   9171:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   9172:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   9173:         }
                   9174:     }
                   9175: }
                   9176: 
1.169     harris41 9177: # -------------------------------------------------- Modify user authentication
1.197     www      9178: # Overrides without validation
                   9179: 
1.169     harris41 9180: sub modifyuserauth {
                   9181:     my ($udom,$uname,$umode,$upass)=@_;
                   9182:     my $uhome=&homeserver($uname,$udom);
1.197     www      9183:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   9184:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 9185:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9186:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 9187:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   9188: 		     &escape($upass),$uhome);
1.620     albertel 9189:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      9190:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   9191:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   9192:     &log($udom,,$uname,$uhome,
1.620     albertel 9193:         'Authentication changed by '.$env{'user.domain'}.', '.
                   9194:                                      $env{'user.name'}.', '.$umode.
1.197     www      9195:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 9196:     unless ($reply eq 'ok') {
1.197     www      9197:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 9198: 	return 'error: '.$reply;
                   9199:     }   
1.170     harris41 9200:     return 'ok';
1.80      www      9201: }
                   9202: 
1.81      www      9203: # --------------------------------------------------------------- Modify a user
1.80      www      9204: 
1.81      www      9205: sub modifyuser {
1.206     matthew  9206:     my ($udom,    $uname, $uid,
                   9207:         $umode,   $upass, $first,
                   9208:         $middle,  $last,  $gene,
1.1058    raeburn  9209:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 9210:     $udom= &LONCAPA::clean_domain($udom);
                   9211:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  9212:     my $showcandelete = 'none';
                   9213:     if (ref($candelete) eq 'ARRAY') {
                   9214:         if (@{$candelete} > 0) {
                   9215:             $showcandelete = join(', ',@{$candelete});
                   9216:         }
                   9217:     }
1.81      www      9218:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      9219:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  9220: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  9221:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   9222:                                      ' desiredhome not specified'). 
1.620     albertel 9223:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9224:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 9225:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  9226:     my $newuser;
                   9227:     if ($uhome eq 'no_host') {
                   9228:         $newuser = 1;
                   9229:     }
1.80      www      9230: # ----------------------------------------------------------------- Create User
1.406     albertel 9231:     if (($uhome eq 'no_host') && 
                   9232: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      9233:         my $unhome='';
1.844     albertel 9234:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  9235:             $unhome = $desiredhome;
1.620     albertel 9236: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   9237: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  9238:         } else { # load balancing routine for determining $unhome
1.81      www      9239:             my $loadm=10000000;
1.841     albertel 9240: 	    my %servers = &get_servers($udom,'library');
                   9241: 	    foreach my $tryserver (keys(%servers)) {
                   9242: 		my $answer=reply('load',$tryserver);
                   9243: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   9244: 		    $loadm=$answer;
                   9245: 		    $unhome=$tryserver;
                   9246: 		}
1.80      www      9247: 	    }
                   9248:         }
                   9249:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  9250: 	    return 'error: unable to find a home server for '.$uname.
                   9251:                    ' in domain '.$udom;
1.80      www      9252:         }
                   9253:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   9254:                          &escape($upass),$unhome);
                   9255: 	unless ($reply eq 'ok') {
                   9256:             return 'error: '.$reply;
                   9257:         }   
1.230     stredwic 9258:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      9259:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  9260: 	    return 'error: unable verify users home machine.';
1.80      www      9261:         }
1.209     matthew  9262:     }   # End of creation of new user
1.80      www      9263: # ---------------------------------------------------------------------- Add ID
                   9264:     if ($uid) {
                   9265:        $uid=~tr/A-Z/a-z/;
                   9266:        my %uidhash=&idrget($udom,$uname);
1.196     www      9267:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   9268:          && (!$forceid)) {
1.80      www      9269: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  9270: 	      return 'error: user id "'.$uid.'" does not match '.
                   9271:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      9272:           }
                   9273:        } else {
                   9274: 	  &idput($udom,($uname => $uid));
                   9275:        }
                   9276:     }
                   9277: # -------------------------------------------------------------- Add names, etc
1.313     matthew  9278:     my @tmp=&get('environment',
1.899     raeburn  9279: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  9280:                     'permanentemail','inststatus'],
1.134     albertel 9281: 		   $udom,$uname);
1.1075    raeburn  9282:     my (%names,%oldnames);
1.313     matthew  9283:     if ($tmp[0] =~ m/^error:.*/) { 
                   9284:         %names=(); 
                   9285:     } else {
                   9286:         %names = @tmp;
1.1075    raeburn  9287:         %oldnames = %names;
1.313     matthew  9288:     }
1.388     www      9289: #
1.1058    raeburn  9290: # If name, email and/or uid are blank (e.g., because an uploaded file
                   9291: # of users did not contain them), do not overwrite existing values
                   9292: # unless field is in $candelete array ref.  
                   9293: #
                   9294: 
                   9295:     my @fields = ('firstname','middlename','lastname','generation',
                   9296:                   'permanentemail','id');
                   9297:     my %newvalues;
                   9298:     if (ref($candelete) eq 'ARRAY') {
                   9299:         foreach my $field (@fields) {
                   9300:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   9301:                 if ($field eq 'firstname') {
                   9302:                     $names{$field} = $first;
                   9303:                 } elsif ($field eq 'middlename') {
                   9304:                     $names{$field} = $middle;
                   9305:                 } elsif ($field eq 'lastname') {
                   9306:                     $names{$field} = $last;
                   9307:                 } elsif ($field eq 'generation') { 
                   9308:                     $names{$field} = $gene;
                   9309:                 } elsif ($field eq 'permanentemail') {
                   9310:                     $names{$field} = $email;
                   9311:                 } elsif ($field eq 'id') {
                   9312:                     $names{$field}  = $uid;
                   9313:                 }
                   9314:             }
                   9315:         }
                   9316:     }
1.388     www      9317:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  9318:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      9319:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  9320:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      9321:     if ($email) {
                   9322:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  9323:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      9324:     }
1.899     raeburn  9325:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  9326:     if (defined($inststatus)) {
                   9327:         $names{'inststatus'} = '';
                   9328:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   9329:         if (ref($usertypes) eq 'HASH') {
                   9330:             my @okstatuses; 
                   9331:             foreach my $item (split(/:/,$inststatus)) {
                   9332:                 if (defined($usertypes->{$item})) {
                   9333:                     push(@okstatuses,$item);  
                   9334:                 }
                   9335:             }
                   9336:             if (@okstatuses) {
                   9337:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   9338:             }
                   9339:         }
                   9340:     }
1.1075    raeburn  9341:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  9342:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  9343:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  9344:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   9345:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   9346:     } else {
                   9347:         $logmsg .= ' during self creation';
                   9348:     }
1.1075    raeburn  9349:     my $changed;
                   9350:     if ($newuser) {
                   9351:         $changed = 1;
                   9352:     } else {
                   9353:         foreach my $field (@fields) {
                   9354:             if ($names{$field} ne $oldnames{$field}) {
                   9355:                 $changed = 1;
                   9356:                 last;
                   9357:             }
                   9358:         }
                   9359:     }
                   9360:     unless ($changed) {
                   9361:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   9362:         &logthis($logmsg);
                   9363:         return 'ok';
                   9364:     }
                   9365:     my $reply = &put('environment', \%names, $udom,$uname);
                   9366:     if ($reply ne 'ok') { 
                   9367:         return 'error: '.$reply;
                   9368:     }
1.1087    raeburn  9369:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   9370:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   9371:     }
1.1075    raeburn  9372:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   9373:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   9374:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  9375:     &logthis($logmsg);
1.134     albertel 9376:     return 'ok';
1.80      www      9377: }
                   9378: 
1.81      www      9379: # -------------------------------------------------------------- Modify student
1.80      www      9380: 
1.81      www      9381: sub modifystudent {
                   9382:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  9383:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76  raeburn  9384:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 9385:     if (!$cid) {
1.620     albertel 9386: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9387: 	    return 'not_in_class';
                   9388: 	}
1.80      www      9389:     }
                   9390: # --------------------------------------------------------------- Make the user
1.81      www      9391:     my $reply=&modifyuser
1.209     matthew  9392: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  9393:          $desiredhome,$email,$inststatus);
1.80      www      9394:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  9395:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  9396:     # student's environment
1.297     matthew  9397:     $uid = undef if (!$forceid);
1.455     albertel 9398:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  9399: 					$gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76  raeburn  9400:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  9401:     return $reply;
                   9402: }
                   9403: 
                   9404: sub modify_student_enrollment {
1.1172.2.23  raeburn  9405:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76  raeburn  9406:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 9407:     my ($cdom,$cnum,$chome);
                   9408:     if (!$cid) {
1.620     albertel 9409: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9410: 	    return 'not_in_class';
                   9411: 	}
1.620     albertel 9412: 	$cdom=$env{'course.'.$cid.'.domain'};
                   9413: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 9414:     } else {
                   9415: 	($cdom,$cnum)=split(/_/,$cid);
                   9416:     }
1.620     albertel 9417:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 9418:     if (!$chome) {
1.457     raeburn  9419: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  9420:     }
1.455     albertel 9421:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  9422:     # Make sure the user exists
1.81      www      9423:     my $uhome=&homeserver($uname,$udom);
                   9424:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9425: 	return 'error: no such user';
                   9426:     }
1.297     matthew  9427:     # Get student data if we were not given enough information
                   9428:     if (!defined($first)  || $first  eq '' || 
                   9429:         !defined($last)   || $last   eq '' || 
                   9430:         !defined($uid)    || $uid    eq '' || 
                   9431:         !defined($middle) || $middle eq '' || 
                   9432:         !defined($gene)   || $gene   eq '') {
1.294     matthew  9433:         # They did not supply us with enough data to enroll the student, so
                   9434:         # we need to pick up more information.
1.297     matthew  9435:         my %tmp = &get('environment',
1.294     matthew  9436:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  9437:                        ,$udom,$uname);
                   9438: 
1.800     albertel 9439:         #foreach my $key (keys(%tmp)) {
                   9440:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 9441:         #}
1.294     matthew  9442:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   9443:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   9444:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  9445:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  9446:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   9447:     }
1.556     albertel 9448:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  9449:     my $user = "$uname:$udom";
                   9450:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 9451:     my $reply=cput('classlist',
1.1148    raeburn  9452: 		   {$user => 
1.1172.2.76  raeburn  9453: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 9454: 		   $cdom,$cnum);
1.1148    raeburn  9455:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   9456:         &devalidate_getsection_cache($udom,$uname,$cid);
                   9457:     } else { 
1.81      www      9458: 	return 'error: '.$reply;
                   9459:     }
1.297     matthew  9460:     # Add student role to user
1.83      www      9461:     my $uurl='/'.$cid;
1.81      www      9462:     $uurl=~s/\_/\//g;
                   9463:     if ($usec) {
                   9464: 	$uurl.='/'.$usec;
                   9465:     }
1.1148    raeburn  9466:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   9467:                              $selfenroll,$context);
                   9468:     if ($result ne 'ok') {
                   9469:         if ($old_entry{$user} ne '') {
                   9470:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   9471:         } else {
                   9472:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   9473:         }
                   9474:     }
                   9475:     return $result; 
1.21      www      9476: }
                   9477: 
1.556     albertel 9478: sub format_name {
                   9479:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   9480:     my $name;
                   9481:     if ($first ne 'lastname') {
                   9482: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   9483:     } else {
                   9484: 	if ($lastname=~/\S/) {
                   9485: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   9486: 	    $name=~s/\s+,/,/;
                   9487: 	} else {
                   9488: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   9489: 	}
                   9490:     }
                   9491:     $name=~s/^\s+//;
                   9492:     $name=~s/\s+$//;
                   9493:     $name=~s/\s+/ /g;
                   9494:     return $name;
                   9495: }
                   9496: 
1.84      www      9497: # ------------------------------------------------- Write to course preferences
                   9498: 
                   9499: sub writecoursepref {
                   9500:     my ($courseid,%prefs)=@_;
                   9501:     $courseid=~s/^\///;
                   9502:     $courseid=~s/\_/\//g;
                   9503:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   9504:     my $chome=homeserver($cnum,$cdomain);
                   9505:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   9506: 	return 'error: no such course';
                   9507:     }
                   9508:     my $cstring='';
1.800     albertel 9509:     foreach my $pref (keys(%prefs)) {
                   9510: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 9511:     }
1.84      www      9512:     $cstring=~s/\&$//;
                   9513:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   9514: }
                   9515: 
                   9516: # ---------------------------------------------------------- Make/modify course
                   9517: 
                   9518: sub createcourse {
1.741     raeburn  9519:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  9520:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      9521:     $url=&declutter($url);
                   9522:     my $cid='';
1.1028    raeburn  9523:     if ($context eq 'requestcourses') {
                   9524:         my $can_create = 0;
                   9525:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   9526:         if ($udom eq $ownerdom) {
                   9527:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   9528:                                   $context)) {
                   9529:                 $can_create = 1;
                   9530:             }
                   9531:         } else {
                   9532:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   9533:                                            $category);
                   9534:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   9535:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   9536:                 if (@curr > 0) {
                   9537:                     my @options = qw(approval validate autolimit);
                   9538:                     my $optregex = join('|',@options);
                   9539:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   9540:                         $can_create = 1;
                   9541:                     }
                   9542:                 }
                   9543:             }
                   9544:         }
                   9545:         if ($can_create) {
                   9546:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   9547:                 unless (&allowed('ccc',$udom)) {
                   9548:                     return 'refused'; 
                   9549:                 }
1.1017    raeburn  9550:             }
                   9551:         } else {
                   9552:             return 'refused';
                   9553:         }
1.1028    raeburn  9554:     } elsif (!&allowed('ccc',$udom)) {
                   9555:         return 'refused';
1.84      www      9556:     }
1.1011    raeburn  9557: # --------------------------------------------------------------- Get Unique ID
                   9558:     my $uname;
                   9559:     if ($cnum =~ /^$match_courseid$/) {
                   9560:         my $chome=&homeserver($cnum,$udom,'true');
                   9561:         if (($chome eq '') || ($chome eq 'no_host')) {
                   9562:             $uname = $cnum;
                   9563:         } else {
1.1038    raeburn  9564:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9565:         }
                   9566:     } else {
1.1038    raeburn  9567:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9568:     }
                   9569:     return $uname if ($uname =~ /^error/);
                   9570: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  9571:     if (!defined($course_server)) {
                   9572:         if (defined(&domain($udom,'primary'))) {
                   9573:             $course_server = &domain($udom,'primary');
                   9574:         } else {
                   9575:             $course_server = $env{'user.home'}; 
                   9576:         }
                   9577:     }
                   9578:     my %host_servers =
                   9579:         &Apache::lonnet::get_servers($udom,'library');
                   9580:     unless ($host_servers{$course_server}) {
                   9581:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  9582:     }
1.84      www      9583: # ------------------------------------------------------------- Make the course
                   9584:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  9585:                       $course_server);
1.84      www      9586:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  9587:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      9588:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9589: 	return 'error: no such course';
                   9590:     }
1.271     www      9591: # ----------------------------------------------------------------- Course made
1.516     raeburn  9592: # log existence
1.1029    raeburn  9593:     my $now = time;
1.918     raeburn  9594:     my $newcourse = {
                   9595:                     $udom.'_'.$uname => {
1.921     raeburn  9596:                                      description => $description,
                   9597:                                      inst_code   => $inst_code,
                   9598:                                      owner       => $course_owner,
                   9599:                                      type        => $crstype,
1.1029    raeburn  9600:                                      creator     => $env{'user.name'}.':'.
                   9601:                                                     $env{'user.domain'},
                   9602:                                      created     => $now,
                   9603:                                      context     => $context,
1.918     raeburn  9604:                                                 },
                   9605:                     };
1.921     raeburn  9606:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      9607: # set toplevel url
1.271     www      9608:     my $topurl=$url;
                   9609:     unless ($nonstandard) {
                   9610: # ------------------------------------------ For standard courses, make top url
                   9611:         my $mapurl=&clutter($url);
1.278     www      9612:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 9613:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      9614: <map>
                   9615: <resource id="1" type="start"></resource>
                   9616: <resource id="2" src="$mapurl"></resource>
                   9617: <resource id="3" type="finish"></resource>
                   9618: <link index="1" from="1" to="2"></link>
                   9619: <link index="2" from="2" to="3"></link>
                   9620: </map>
                   9621: ENDINITMAP
                   9622:         $topurl=&declutter(
1.638     albertel 9623:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      9624:                           );
                   9625:     }
                   9626: # ----------------------------------------------------------- Write preferences
1.84      www      9627:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  9628:                      ('description'              => $description,
                   9629:                       'url'                      => $topurl,
                   9630:                       'internal.creator'         => $env{'user.name'}.':'.
                   9631:                                                     $env{'user.domain'},
                   9632:                       'internal.created'         => $now,
                   9633:                       'internal.creationcontext' => $context)
                   9634:                     );
1.84      www      9635:     return '/'.$udom.'/'.$uname;
                   9636: }
                   9637: 
1.1011    raeburn  9638: # ------------------------------------------------------------------- Create ID
                   9639: sub generate_coursenum {
1.1038    raeburn  9640:     my ($udom,$crstype) = @_;
1.1011    raeburn  9641:     my $domdesc = &domain($udom);
                   9642:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  9643:     my $first;
                   9644:     if ($crstype eq 'Community') {
                   9645:         $first = '0';
                   9646:     } else {
                   9647:         $first = int(1+rand(9)); 
                   9648:     } 
                   9649:     my $uname=$first.
1.1011    raeburn  9650:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9651:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9652:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9653: # ----------------------------------------------- Make sure that does not exist
                   9654:     my $uhome=&homeserver($uname,$udom,'true');
                   9655:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  9656:         if ($crstype eq 'Community') {
                   9657:             $first = '0';
                   9658:         } else {
                   9659:             $first = int(1+rand(9));
                   9660:         }
                   9661:         $uname=$first.
1.1011    raeburn  9662:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9663:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9664:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9665:         $uhome=&homeserver($uname,$udom,'true');
                   9666:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   9667:             return 'error: unable to generate unique course-ID';
                   9668:         }
                   9669:     }
                   9670:     return $uname;
                   9671: }
                   9672: 
1.813     albertel 9673: sub is_course {
1.1167    droeschl 9674:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   9675:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   9676: 
                   9677:     return unless $cdom and $cnum;
                   9678: 
                   9679:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   9680:         '.');
                   9681: 
1.1172.2.23  raeburn  9682:     return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167    droeschl 9683:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 9684: }
                   9685: 
1.1015    raeburn  9686: sub store_userdata {
                   9687:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  9688:     my $result;
1.1016    raeburn  9689:     if ($datakey ne '') {
1.1013    raeburn  9690:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  9691:             if ($udom eq '' || $uname eq '') {
                   9692:                 $udom = $env{'user.domain'};
                   9693:                 $uname = $env{'user.name'};
                   9694:             }
                   9695:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  9696:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   9697:                 $result = 'error: no_host';
                   9698:             } else {
                   9699:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   9700:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   9701: 
                   9702:                 my $namevalue='';
                   9703:                 foreach my $key (keys(%{$storehash})) {
                   9704:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   9705:                 }
                   9706:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  9707:                 unless ($namespace eq 'courserequests') {
                   9708:                     $datakey = &escape($datakey);
                   9709:                 }
1.1105    raeburn  9710:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   9711:                                   $namevalue,$uhome);
1.1013    raeburn  9712:             }
                   9713:         } else {
                   9714:             $result = 'error: data to store was not a hash reference'; 
                   9715:         }
                   9716:     } else {
                   9717:         $result= 'error: invalid requestkey'; 
                   9718:     }
                   9719:     return $result;
                   9720: }
                   9721: 
1.21      www      9722: # ---------------------------------------------------------- Assign Custom Role
                   9723: 
                   9724: sub assigncustomrole {
1.957     raeburn  9725:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9726:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  9727:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      9728: }
                   9729: 
                   9730: # ----------------------------------------------------------------- Revoke Role
                   9731: 
                   9732: sub revokerole {
1.957     raeburn  9733:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9734:     my $now=time;
1.965     raeburn  9735:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      9736: }
                   9737: 
                   9738: # ---------------------------------------------------------- Revoke Custom Role
                   9739: 
                   9740: sub revokecustomrole {
1.957     raeburn  9741:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9742:     my $now=time;
1.357     www      9743:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  9744:            $deleteflag,$selfenroll,$context);
1.17      www      9745: }
                   9746: 
1.533     banghart 9747: # ------------------------------------------------------------ Disk usage
1.535     albertel 9748: sub diskusage {
1.955     raeburn  9749:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   9750:     $directorypath =~ s/\/$//;
                   9751:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   9752:                        .&escape($getpropath).':'.&escape($uname).':'
                   9753:                        .&escape($udom),homeserver($uname,$udom));
                   9754:     if ($listing eq 'unknown_cmd') {
                   9755:         if ($getpropath) {
                   9756:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   9757:         }
                   9758:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   9759:     }
1.514     albertel 9760:     return $listing;
1.512     banghart 9761: }
                   9762: 
1.566     banghart 9763: sub is_locked {
1.1096    raeburn  9764:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 9765:     my @check;
                   9766:     my $is_locked;
1.1093    raeburn  9767:     push (@check,$file_name);
1.613     albertel 9768:     my %locked = &get('file_permissions',\@check,
1.620     albertel 9769: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 9770:     my ($tmp)=keys(%locked);
                   9771:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  9772:     
1.566     banghart 9773:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  9774:         $is_locked = 'false';
                   9775:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  9776:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  9777:                $is_locked = 'true';
1.1096    raeburn  9778:                if (ref($which) eq 'ARRAY') {
                   9779:                    push(@{$which},$entry);
                   9780:                } else {
                   9781:                    last;
                   9782:                }
1.745     raeburn  9783:            }
                   9784:        }
1.566     banghart 9785:     } else {
                   9786:         $is_locked = 'false';
                   9787:     }
1.1093    raeburn  9788:     return $is_locked;
1.566     banghart 9789: }
                   9790: 
1.759     albertel 9791: sub declutter_portfile {
                   9792:     my ($file) = @_;
1.833     albertel 9793:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 9794:     return $file;
                   9795: }
                   9796: 
1.559     banghart 9797: # ------------------------------------------------------------- Mark as Read Only
                   9798: 
                   9799: sub mark_as_readonly {
                   9800:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 9801:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9802:     my ($tmp)=keys(%current_permissions);
                   9803:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 9804:     foreach my $file (@{$files}) {
1.759     albertel 9805: 	$file = &declutter_portfile($file);
1.561     banghart 9806:         push(@{$current_permissions{$file}},$what);
1.559     banghart 9807:     }
1.613     albertel 9808:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9809:     return;
                   9810: }
                   9811: 
1.572     banghart 9812: # ------------------------------------------------------------Save Selected Files
                   9813: 
                   9814: sub save_selected_files {
                   9815:     my ($user, $path, @files) = @_;
                   9816:     my $filename = $user."savedfiles";
1.573     banghart 9817:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 9818:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 9819:     foreach my $file (@files) {
1.620     albertel 9820:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 9821:     }
                   9822:     foreach my $file (@other_files) {
1.574     banghart 9823:         print (OUT $file."\n");
1.572     banghart 9824:     }
1.574     banghart 9825:     close (OUT);
1.572     banghart 9826:     return 'ok';
                   9827: }
                   9828: 
1.574     banghart 9829: sub clear_selected_files {
                   9830:     my ($user) = @_;
                   9831:     my $filename = $user."savedfiles";
1.1117    foxr     9832:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 9833:     print (OUT undef);
                   9834:     close (OUT);
                   9835:     return ("ok");    
                   9836: }
                   9837: 
1.572     banghart 9838: sub files_in_path {
                   9839:     my ($user, $path) = @_;
                   9840:     my $filename = $user."savedfiles";
                   9841:     my %return_files;
1.1117    foxr     9842:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 9843:     while (my $line_in = <IN>) {
1.574     banghart 9844:         chomp ($line_in);
                   9845:         my @paths_and_file = split (m!/!, $line_in);
                   9846:         my $file_part = pop (@paths_and_file);
                   9847:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 9848:         $path_part.='/';
                   9849:         my $path_and_file = $path_part.$file_part;
                   9850:         if ($path_part eq $path) {
                   9851:             $return_files{$file_part}= 'selected';
                   9852:         }
                   9853:     }
1.574     banghart 9854:     close (IN);
                   9855:     return (\%return_files);
1.572     banghart 9856: }
                   9857: 
                   9858: # called in portfolio select mode, to show files selected NOT in current directory
                   9859: sub files_not_in_path {
                   9860:     my ($user, $path) = @_;
                   9861:     my $filename = $user."savedfiles";
                   9862:     my @return_files;
                   9863:     my $path_part;
1.1117    foxr     9864:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 9865:     while (my $line = <IN>) {
1.572     banghart 9866:         #ok, I know it's clunky, but I want it to work
1.800     albertel 9867:         my @paths_and_file = split(m|/|, $line);
                   9868:         my $file_part = pop(@paths_and_file);
                   9869:         chomp($file_part);
                   9870:         my $path_part = join('/', @paths_and_file);
1.572     banghart 9871:         $path_part .= '/';
                   9872:         my $path_and_file = $path_part.$file_part;
                   9873:         if ($path_part ne $path) {
1.800     albertel 9874:             push(@return_files, ($path_and_file));
1.572     banghart 9875:         }
                   9876:     }
1.800     albertel 9877:     close(OUT);
1.574     banghart 9878:     return (@return_files);
1.572     banghart 9879: }
                   9880: 
1.745     raeburn  9881: #----------------------------------------------Get portfolio file permissions
1.629     banghart 9882: 
1.745     raeburn  9883: sub get_portfile_permissions {
                   9884:     my ($domain,$user) = @_;
1.613     albertel 9885:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9886:     my ($tmp)=keys(%current_permissions);
                   9887:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9888:     return \%current_permissions;
                   9889: }
                   9890: 
                   9891: #---------------------------------------------Get portfolio file access controls
                   9892: 
1.749     raeburn  9893: sub get_access_controls {
1.745     raeburn  9894:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 9895:     my %access;
                   9896:     my $real_file = $file;
                   9897:     $file =~ s/\.meta$//;
1.745     raeburn  9898:     if (defined($file)) {
1.749     raeburn  9899:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   9900:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 9901:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  9902:             }
                   9903:         }
1.745     raeburn  9904:     } else {
1.749     raeburn  9905:         foreach my $key (keys(%{$current_permissions})) {
                   9906:             if ($key =~ /\0accesscontrol$/) {
                   9907:                 if (defined($group)) {
                   9908:                     if ($key !~ m-^\Q$group\E/-) {
                   9909:                         next;
                   9910:                     }
                   9911:                 }
                   9912:                 my ($fullpath) = split(/\0/,$key);
                   9913:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   9914:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   9915:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   9916:                     }
                   9917:                 }
                   9918:             }
                   9919:         }
                   9920:     }
                   9921:     return %access;
                   9922: }
                   9923: 
                   9924: sub modify_access_controls {
                   9925:     my ($file_name,$changes,$domain,$user)=@_;
                   9926:     my ($outcome,$deloutcome);
                   9927:     my %store_permissions;
                   9928:     my %new_values;
                   9929:     my %new_control;
                   9930:     my %translation;
                   9931:     my @deletions = ();
                   9932:     my $now = time;
                   9933:     if (exists($$changes{'activate'})) {
                   9934:         if (ref($$changes{'activate'}) eq 'HASH') {
                   9935:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   9936:             my $numnew = scalar(@newitems);
                   9937:             for (my $i=0; $i<$numnew; $i++) {
                   9938:                 my $newkey = $newitems[$i];
                   9939:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  9940:                 if ($newkey =~ /^\d+:/) { 
                   9941:                     $newkey =~ s/^(\d+)/$newid/;
                   9942:                     $translation{$1} = $newid;
                   9943:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   9944:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   9945:                     $translation{$1} = $newid;
                   9946:                 }
1.749     raeburn  9947:                 $new_values{$file_name."\0".$newkey} = 
                   9948:                                           $$changes{'activate'}{$newitems[$i]};
                   9949:                 $new_control{$newkey} = $now;
                   9950:             }
                   9951:         }
                   9952:     }
                   9953:     my %todelete;
                   9954:     my %changed_items;
                   9955:     foreach my $action ('delete','update') {
                   9956:         if (exists($$changes{$action})) {
                   9957:             if (ref($$changes{$action}) eq 'HASH') {
                   9958:                 foreach my $key (keys(%{$$changes{$action}})) {
                   9959:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   9960:                     if ($action eq 'delete') { 
                   9961:                         $todelete{$itemnum} = 1;
                   9962:                     } else {
                   9963:                         $changed_items{$itemnum} = $key;
                   9964:                     }
                   9965:                 }
1.745     raeburn  9966:             }
                   9967:         }
1.749     raeburn  9968:     }
                   9969:     # get lock on access controls for file.
                   9970:     my $lockhash = {
                   9971:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   9972:                                                        ':'.$env{'user.domain'},
                   9973:                    }; 
                   9974:     my $tries = 0;
                   9975:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9976:    
1.1172.2.79  raeburn  9977:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  9978:         $tries ++;
1.1172.2.79  raeburn  9979:         sleep(0.1);
1.749     raeburn  9980:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9981:     }
                   9982:     if ($gotlock eq 'ok') {
                   9983:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   9984:         my ($tmp)=keys(%curr_permissions);
                   9985:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   9986:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   9987:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   9988:             if (ref($curr_controls) eq 'HASH') {
                   9989:                 foreach my $control_item (keys(%{$curr_controls})) {
                   9990:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   9991:                     if (defined($todelete{$itemnum})) {
                   9992:                         push(@deletions,$file_name."\0".$control_item);
                   9993:                     } else {
                   9994:                         if (defined($changed_items{$itemnum})) {
                   9995:                             $new_control{$changed_items{$itemnum}} = $now;
                   9996:                             push(@deletions,$file_name."\0".$control_item);
                   9997:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   9998:                         } else {
                   9999:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   10000:                         }
                   10001:                     }
1.745     raeburn  10002:                 }
                   10003:             }
                   10004:         }
1.970     raeburn  10005:         my ($group);
                   10006:         if (&is_course($domain,$user)) {
                   10007:             ($group,my $file) = split(/\//,$file_name,2);
                   10008:         }
1.749     raeburn  10009:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   10010:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   10011:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   10012:         #  remove lock
                   10013:         my @del_lock = ($file_name."\0".'locked_access_records');
                   10014:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  10015:         my $sqlresult =
1.970     raeburn  10016:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  10017:                                     $group);
1.749     raeburn  10018:     } else {
                   10019:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  10020:     }
1.749     raeburn  10021:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  10022: }
                   10023: 
1.827     raeburn  10024: sub make_public_indefinitely {
                   10025:     my ($requrl) = @_;
                   10026:     my $now = time;
                   10027:     my $action = 'activate';
                   10028:     my $aclnum = 0;
                   10029:     if (&is_portfolio_url($requrl)) {
                   10030:         my (undef,$udom,$unum,$file_name,$group) =
                   10031:             &parse_portfolio_url($requrl);
                   10032:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   10033:         my %access_controls = &get_access_controls($current_perms,
                   10034:                                                    $group,$file_name);
                   10035:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   10036:             my ($num,$scope,$end,$start) = 
                   10037:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   10038:             if ($scope eq 'public') {
                   10039:                 if ($start <= $now && $end == 0) {
                   10040:                     $action = 'none';
                   10041:                 } else {
                   10042:                     $action = 'update';
                   10043:                     $aclnum = $num;
                   10044:                 }
                   10045:                 last;
                   10046:             }
                   10047:         }
                   10048:         if ($action eq 'none') {
                   10049:              return 'ok';
                   10050:         } else {
                   10051:             my %changes;
                   10052:             my $newend = 0;
                   10053:             my $newstart = $now;
                   10054:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   10055:             $changes{$action}{$newkey} = {
                   10056:                 type => 'public',
                   10057:                 time => {
                   10058:                     start => $newstart,
                   10059:                     end   => $newend,
                   10060:                 },
                   10061:             };
                   10062:             my ($outcome,$deloutcome,$new_values,$translation) =
                   10063:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   10064:             return $outcome;
                   10065:         }
                   10066:     } else {
                   10067:         return 'invalid';
                   10068:     }
                   10069: }
                   10070: 
1.745     raeburn  10071: #------------------------------------------------------Get Marked as Read Only
                   10072: 
                   10073: sub get_marked_as_readonly {
                   10074:     my ($domain,$user,$what,$group) = @_;
                   10075:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 10076:     my @readonly_files;
1.629     banghart 10077:     my $cmp1=$what;
                   10078:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  10079:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10080:         if (defined($group)) {
                   10081:             if ($file_name !~ m-^\Q$group\E/-) {
                   10082:                 next;
                   10083:             }
                   10084:         }
1.561     banghart 10085:         if (ref($value) eq "ARRAY"){
                   10086:             foreach my $stored_what (@{$value}) {
1.629     banghart 10087:                 my $cmp2=$stored_what;
1.759     albertel 10088:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  10089:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  10090:                 }
1.629     banghart 10091:                 if ($cmp1 eq $cmp2) {
1.561     banghart 10092:                     push(@readonly_files, $file_name);
1.745     raeburn  10093:                     last;
1.563     banghart 10094:                 } elsif (!defined($what)) {
                   10095:                     push(@readonly_files, $file_name);
1.745     raeburn  10096:                     last;
1.561     banghart 10097:                 }
                   10098:             }
1.745     raeburn  10099:         }
1.561     banghart 10100:     }
                   10101:     return @readonly_files;
                   10102: }
1.577     banghart 10103: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 10104: 
1.577     banghart 10105: sub get_marked_as_readonly_hash {
1.745     raeburn  10106:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 10107:     my %readonly_files;
1.745     raeburn  10108:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10109:         if (defined($group)) {
                   10110:             if ($file_name !~ m-^\Q$group\E/-) {
                   10111:                 next;
                   10112:             }
                   10113:         }
1.577     banghart 10114:         if (ref($value) eq "ARRAY"){
                   10115:             foreach my $stored_what (@{$value}) {
1.745     raeburn  10116:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 10117:                     foreach my $lock_descriptor(@{$stored_what}) {
                   10118:                         if ($lock_descriptor eq 'graded') {
                   10119:                             $readonly_files{$file_name} = 'graded';
                   10120:                         } elsif ($lock_descriptor eq 'handback') {
                   10121:                             $readonly_files{$file_name} = 'handback';
                   10122:                         } else {
                   10123:                             if (!exists($readonly_files{$file_name})) {
                   10124:                                 $readonly_files{$file_name} = 'locked';
                   10125:                             }
                   10126:                         }
1.745     raeburn  10127:                     }
1.750     banghart 10128:                 } 
1.577     banghart 10129:             }
                   10130:         } 
                   10131:     }
                   10132:     return %readonly_files;
                   10133: }
1.559     banghart 10134: # ------------------------------------------------------------ Unmark as Read Only
                   10135: 
                   10136: sub unmark_as_readonly {
1.629     banghart 10137:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   10138:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  10139:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 10140:     $file_name = &declutter_portfile($file_name);
1.634     albertel 10141:     my $symb_crs = $what;
                   10142:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  10143:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 10144:     my ($tmp)=keys(%current_permissions);
                   10145:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10146:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 10147:     foreach my $file (@readonly_files) {
1.759     albertel 10148: 	my $clean_file = &declutter_portfile($file);
                   10149: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 10150: 	my $current_locks = $current_permissions{$file};
1.563     banghart 10151:         my @new_locks;
                   10152:         my @del_keys;
                   10153:         if (ref($current_locks) eq "ARRAY"){
                   10154:             foreach my $locker (@{$current_locks}) {
1.632     albertel 10155:                 my $compare=$locker;
1.749     raeburn  10156:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  10157:                     $compare=join('',@{$locker});
1.746     raeburn  10158:                     if ($compare ne $symb_crs) {
                   10159:                         push(@new_locks, $locker);
                   10160:                     }
1.563     banghart 10161:                 }
                   10162:             }
1.650     albertel 10163:             if (scalar(@new_locks) > 0) {
1.563     banghart 10164:                 $current_permissions{$file} = \@new_locks;
                   10165:             } else {
                   10166:                 push(@del_keys, $file);
1.613     albertel 10167:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 10168:                 delete($current_permissions{$file});
1.563     banghart 10169:             }
                   10170:         }
1.561     banghart 10171:     }
1.613     albertel 10172:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10173:     return;
                   10174: }
1.512     banghart 10175: 
1.17      www      10176: # ------------------------------------------------------------ Directory lister
                   10177: 
                   10178: sub dirlist {
1.955     raeburn  10179:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      10180:     $uri=~s/^\///;
                   10181:     $uri=~s/\/$//;
1.253     stredwic 10182:     my ($udom, $uname);
1.955     raeburn  10183:     if ($getuserdir) {
1.253     stredwic 10184:         $udom = $userdomain;
                   10185:         $uname = $username;
1.955     raeburn  10186:     } else {
                   10187:         (undef,$udom,$uname)=split(/\//,$uri);
                   10188:         if(defined($userdomain)) {
                   10189:             $udom = $userdomain;
                   10190:         }
                   10191:         if(defined($username)) {
                   10192:             $uname = $username;
                   10193:         }
1.253     stredwic 10194:     }
1.955     raeburn  10195:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 10196: 
1.955     raeburn  10197:     $dirRoot = $perlvar{'lonDocRoot'};
                   10198:     if (defined($getpropath)) {
                   10199:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 10200:         $dirRoot =~ s/\/$//;
1.955     raeburn  10201:     } elsif (defined($getuserdir)) {
                   10202:         my $subdir=$uname.'__';
                   10203:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   10204:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   10205:                    ."/$udom/$subdir/$uname";
                   10206:     } elsif (defined($alternateRoot)) {
                   10207:         $dirRoot = $alternateRoot;
1.751     banghart 10208:     }
1.253     stredwic 10209: 
                   10210:     if($udom) {
                   10211:         if($uname) {
1.1135    raeburn  10212:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  10213:             if ($uhome eq 'no_host') {
                   10214:                 return ([],'no_host');
                   10215:             }
1.955     raeburn  10216:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  10217:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  10218:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  10219:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10220:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  10221:             } else {
                   10222:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10223:             }
1.605     matthew  10224:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10225:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  10226:                 @listing_results = split(/:/,$listing);
                   10227:             } else {
                   10228:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10229:             }
1.1135    raeburn  10230:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  10231:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10232:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10233:                 return ([],$listing);
                   10234:             } else {
                   10235:                 return (\@listing_results);
1.1135    raeburn  10236:             }
1.955     raeburn  10237:         } elsif(!$alternateRoot) {
1.1136    raeburn  10238:             my (%allusers,%listerror);
1.841     albertel 10239: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  10240:  	    foreach my $tryserver (keys(%servers)) {
                   10241:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   10242:                                   &escape($udom),$tryserver);
                   10243:                 if ($listing eq 'unknown_cmd') {
                   10244: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10245: 				      $udom, $tryserver);
                   10246:                 } else {
                   10247:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10248:                 }
1.841     albertel 10249: 		if ($listing eq 'unknown_cmd') {
                   10250: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10251: 				      $udom, $tryserver);
                   10252: 		    @listing_results = split(/:/,$listing);
                   10253: 		} else {
                   10254: 		    @listing_results =
                   10255: 			map { &unescape($_); } split(/:/,$listing);
                   10256: 		}
1.1136    raeburn  10257:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   10258:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10259:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10260:                     $listerror{$tryserver} = $listing;
                   10261:                 } else {
1.841     albertel 10262: 		    foreach my $line (@listing_results) {
                   10263: 			my ($entry) = split(/&/,$line,2);
                   10264: 			$allusers{$entry} = 1;
                   10265: 		    }
                   10266: 		}
1.253     stredwic 10267:             }
1.1136    raeburn  10268:             my @alluserslist=();
1.800     albertel 10269:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  10270:                 push(@alluserslist,$user.'&user');
1.253     stredwic 10271:             }
1.1172.2.80  raeburn  10272:             if (!%listerror) {
                   10273:                 # no errors
                   10274:                 return (\@alluserslist);
                   10275:             } elsif (scalar(keys(%servers)) == 1) {
                   10276:                 # one library server, one error
                   10277:                 my ($key) = keys(%listerror);
                   10278:                 return (\@alluserslist, $listerror{$key});
                   10279:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   10280:                 # con_lost indicates that we might miss data from at least one
                   10281:                 # library server
                   10282:                 return (\@alluserslist, 'con_lost');
                   10283:             } else {
                   10284:                 # multiple library servers and no con_lost -> data should be
                   10285:                 # complete.
                   10286:                 return (\@alluserslist);
                   10287:             }
                   10288: 
1.253     stredwic 10289:         } else {
1.1136    raeburn  10290:             return ([],'missing username');
1.253     stredwic 10291:         }
1.955     raeburn  10292:     } elsif(!defined($getpropath)) {
1.1136    raeburn  10293:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   10294:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   10295:         return (\@all_domains);
1.955     raeburn  10296:     } else {
1.1136    raeburn  10297:         return ([],'missing domain');
1.275     stredwic 10298:     }
                   10299: }
                   10300: 
                   10301: # --------------------------------------------- GetFileTimestamp
                   10302: # This function utilizes dirlist and returns the date stamp for
                   10303: # when it was last modified.  It will also return an error of -1
                   10304: # if an error occurs
                   10305: 
                   10306: sub GetFileTimestamp {
1.955     raeburn  10307:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 10308:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   10309:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  10310:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   10311:                                     undef,$getuserdir);
                   10312:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10313:         return -1;
                   10314:     }
                   10315:     if (ref($fileref) eq 'ARRAY') {
                   10316:         my @stats = split('&',$fileref->[0]);
1.375     matthew  10317:         # @stats contains first the filename, then the stat output
                   10318:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 10319:     } else {
                   10320:         return -1;
1.253     stredwic 10321:     }
1.26      www      10322: }
                   10323: 
1.712     albertel 10324: sub stat_file {
                   10325:     my ($uri) = @_;
1.787     albertel 10326:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 10327: 
1.955     raeburn  10328:     my ($udom,$uname,$file);
1.712     albertel 10329:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   10330: 	($udom,$uname,$file) =
1.811     albertel 10331: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 10332: 	$file = 'userfiles/'.$file;
                   10333:     }
                   10334:     if ($uri =~ m-^/res/-) {
                   10335: 	($udom,$uname) = 
1.807     albertel 10336: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 10337: 	$file = $uri;
                   10338:     }
                   10339: 
                   10340:     if (!$udom || !$uname || !$file) {
                   10341: 	# unable to handle the uri
                   10342: 	return ();
                   10343:     }
1.956     raeburn  10344:     my $getpropath;
                   10345:     if ($file =~ /^userfiles\//) {
                   10346:         $getpropath = 1;
                   10347:     }
1.1136    raeburn  10348:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   10349:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10350:         return ();
                   10351:     } else {
                   10352:         if (ref($listref) eq 'ARRAY') {
                   10353:             my @stats = split('&',$listref->[0]);
                   10354: 	    shift(@stats); #filename is first
                   10355: 	    return @stats;
                   10356:         }
1.712     albertel 10357:     }
                   10358:     return ();
                   10359: }
                   10360: 
1.26      www      10361: # -------------------------------------------------------- Value of a Condition
                   10362: 
1.713     albertel 10363: # gets the value of a specific preevaluated condition
                   10364: #    stored in the string  $env{user.state.<cid>}
                   10365: # or looks up a condition reference in the bighash and if if hasn't
                   10366: # already been evaluated recurses into docondval to get the value of
                   10367: # the condition, then memoizing it to 
                   10368: #   $env{user.state.<cid>.<condition>}
1.40      www      10369: sub directcondval {
                   10370:     my $number=shift;
1.620     albertel 10371:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 10372: 	&Apache::lonuserstate::evalstate();
                   10373:     }
1.713     albertel 10374:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   10375: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   10376:     } elsif ($number =~ /^_/) {
                   10377: 	my $sub_condition;
                   10378: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10379: 		&GDBM_READER(),0640)) {
                   10380: 	    $sub_condition=$bighash{'conditions'.$number};
                   10381: 	    untie(%bighash);
                   10382: 	}
                   10383: 	my $value = &docondval($sub_condition);
1.949     raeburn  10384: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 10385: 	return $value;
                   10386:     }
1.620     albertel 10387:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   10388:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      10389:     } else {
                   10390:        return 2;
                   10391:     }
                   10392: }
                   10393: 
1.713     albertel 10394: # get the collection of conditions for this resource
1.26      www      10395: sub condval {
                   10396:     my $condidx=shift;
1.54      www      10397:     my $allpathcond='';
1.713     albertel 10398:     foreach my $cond (split(/\|/,$condidx)) {
                   10399: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   10400: 	    $allpathcond.=
                   10401: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   10402: 	}
1.191     harris41 10403:     }
1.54      www      10404:     $allpathcond=~s/\|$//;
1.713     albertel 10405:     return &docondval($allpathcond);
                   10406: }
                   10407: 
                   10408: #evaluates an expression of conditions
                   10409: sub docondval {
                   10410:     my ($allpathcond) = @_;
                   10411:     my $result=0;
                   10412:     if ($env{'request.course.id'}
                   10413: 	&& defined($allpathcond)) {
                   10414: 	my $operand='|';
                   10415: 	my @stack;
                   10416: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   10417: 	    if ($chunk eq '(') {
                   10418: 		push @stack,($operand,$result);
                   10419: 	    } elsif ($chunk eq ')') {
                   10420: 		my $before=pop @stack;
                   10421: 		if (pop @stack eq '&') {
                   10422: 		    $result=$result>$before?$before:$result;
                   10423: 		} else {
                   10424: 		    $result=$result>$before?$result:$before;
                   10425: 		}
                   10426: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   10427: 		$operand=$chunk;
                   10428: 	    } else {
                   10429: 		my $new=directcondval($chunk);
                   10430: 		if ($operand eq '&') {
                   10431: 		    $result=$result>$new?$new:$result;
                   10432: 		} else {
                   10433: 		    $result=$result>$new?$result:$new;
                   10434: 		}
                   10435: 	    }
                   10436: 	}
1.26      www      10437:     }
                   10438:     return $result;
1.421     albertel 10439: }
                   10440: 
                   10441: # ---------------------------------------------------- Devalidate courseresdata
                   10442: 
                   10443: sub devalidatecourseresdata {
                   10444:     my ($coursenum,$coursedomain)=@_;
                   10445:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10446:     &devalidate_cache_new('courseres',$hashid);
1.28      www      10447: }
                   10448: 
1.763     www      10449: 
1.200     www      10450: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     10451: #
                   10452: #  Parameters:
                   10453: #      $coursenum    - Number of the course.
                   10454: #      $coursedomain - Domain at which the course was created.
                   10455: #  Returns:
                   10456: #     A hash of the course parameters along (I think) with timestamps
                   10457: #     and version info.
1.877     foxr     10458: 
1.624     albertel 10459: sub get_courseresdata {
                   10460:     my ($coursenum,$coursedomain)=@_;
1.200     www      10461:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   10462:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10463:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 10464:     my %dumpreply;
1.417     albertel 10465:     unless (defined($cached)) {
1.624     albertel 10466: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 10467: 	$result=\%dumpreply;
1.251     albertel 10468: 	my ($tmp) = keys(%dumpreply);
                   10469: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 10470: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 10471: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   10472: 	    return $tmp;
1.416     albertel 10473: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 10474: 	    $result=undef;
1.599     albertel 10475: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 10476: 	}
                   10477:     }
1.624     albertel 10478:     return $result;
                   10479: }
                   10480: 
1.633     albertel 10481: sub devalidateuserresdata {
                   10482:     my ($uname,$udom)=@_;
                   10483:     my $hashid="$udom:$uname";
                   10484:     &devalidate_cache_new('userres',$hashid);
                   10485: }
                   10486: 
1.624     albertel 10487: sub get_userresdata {
                   10488:     my ($uname,$udom)=@_;
                   10489:     #most student don\'t have any data set, check if there is some data
                   10490:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   10491: 
                   10492:     my $hashid="$udom:$uname";
                   10493:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   10494:     if (!defined($cached)) {
                   10495: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   10496: 	$result=\%resourcedata;
                   10497: 	&do_cache_new('userres',$hashid,$result,600);
                   10498:     }
                   10499:     my ($tmp)=keys(%$result);
                   10500:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   10501: 	return $result;
                   10502:     }
                   10503:     #error 2 occurs when the .db doesn't exist
                   10504:     if ($tmp!~/error: 2 /) {
1.1172.2.71  raeburn  10505:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   10506: 	    &logthis("<font color=\"blue\">WARNING:".
                   10507: 		     " Trying to get resource data for ".
                   10508: 		     $uname." at ".$udom.": ".
                   10509: 		     $tmp."</font>");
                   10510:         }
1.624     albertel 10511:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 10512: 	#&EXT_cache_set($udom,$uname);
                   10513: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 10514: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 10515:     }
                   10516:     return $tmp;
                   10517: }
1.879     foxr     10518: #----------------------------------------------- resdata - return resource data
                   10519: #  Purpose:
                   10520: #    Return resource data for either users or for a course.
                   10521: #  Parameters:
                   10522: #     $name      - Course/user name.
                   10523: #     $domain    - Name of the domain the user/course is registered on.
1.1172.2.93.4  1(raebur 10524:7): #     $type      - Type of thing $name is (must be 'course' or 'user')
1.879     foxr     10525: #     @which     - Array of names of resources desired.
                   10526: #  Returns:
                   10527: #     The value of the first reasource in @which that is found in the
                   10528: #     resource hash.
                   10529: #  Exceptional Conditions:
                   10530: #     If the $type passed in is not valid (not the string 'course' or 
                   10531: #     'user', an undefined  reference is returned.
                   10532: #     If none of the resources are found, an undef is returned
1.624     albertel 10533: sub resdata {
                   10534:     my ($name,$domain,$type,@which)=@_;
                   10535:     my $result;
                   10536:     if ($type eq 'course') {
                   10537: 	$result=&get_courseresdata($name,$domain);
                   10538:     } elsif ($type eq 'user') {
                   10539: 	$result=&get_userresdata($name,$domain);
                   10540:     }
                   10541:     if (!ref($result)) { return $result; }    
1.251     albertel 10542:     foreach my $item (@which) {
1.1172.2.93.4  1(raebur 10543:7):         if (ref($item) eq 'ARRAY') {
                   10544:7): 	    if (defined($result->{$item->[0]})) {
                   10545:7): 	        return [$result->{$item->[0]},$item->[1]];
                   10546:7): 	    }
                   10547:7):         }
1.250     albertel 10548:     }
1.291     albertel 10549:     return undef;
1.200     www      10550: }
                   10551: 
1.1172.2.93.4  2(raebur 10552:7): sub get_domain_ltitools {
                   10553:7):     my ($cdom) = @_;
                   10554:7):     my %ltitools;
                   10555:7):     my ($result,$cached)=&is_cached_new('ltitools',$cdom);
                   10556:7):     if (defined($cached)) {
                   10557:7):         if (ref($result) eq 'HASH') {
                   10558:7):             %ltitools = %{$result};
                   10559:7):         }
                   10560:7):     } else {
                   10561:7):         my %domconfig = &get_dom('configuration',['ltitools'],$cdom);
                   10562:7):         if (ref($domconfig{'ltitools'}) eq 'HASH') {
                   10563:7):             %ltitools = %{$domconfig{'ltitools'}};
                   10564:7):             my %encdomconfig = &get_dom('encconfig',['ltitools'],$cdom);
                   10565:7):             if (ref($encdomconfig{'ltitools'}) eq 'HASH') {
                   10566:7):                 foreach my $id (keys(%ltitools)) {
                   10567:7):                     if (ref($encdomconfig{'ltitools'}{$id}) eq 'HASH') {
                   10568:7):                         foreach my $item ('key','secret') {
                   10569:7):                             $ltitools{$id}{$item} = $encdomconfig{'ltitools'}{$id}{$item};
                   10570:7):                         }
                   10571:7):                     }
                   10572:7):                 }
                   10573:7):             }
                   10574:7):         }
                   10575:7):         my $cachetime = 24*60*60;
                   10576:7):         &do_cache_new('ltitools',$cdom,\%ltitools,$cachetime);
                   10577:7):     }
                   10578:7):     return %ltitools;
                   10579:7): }
                   10580:7): 
1.1172.2.31  raeburn  10581: sub get_numsuppfiles {
                   10582:     my ($cnum,$cdom,$ignorecache)=@_;
                   10583:     my $hashid=$cnum.':'.$cdom;
                   10584:     my ($suppcount,$cached);
                   10585:     unless ($ignorecache) {
                   10586:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   10587:     }
                   10588:     unless (defined($cached)) {
                   10589:         my $chome=&homeserver($cnum,$cdom);
                   10590:         unless ($chome eq 'no_host') {
                   10591:             ($suppcount,my $errors) = (0,0);
                   10592:             my $suppmap = 'supplemental.sequence';
                   10593:             ($suppcount,$errors) =
                   10594:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   10595:         }
                   10596:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   10597:     }
                   10598:     return $suppcount;
                   10599: }
                   10600: 
1.379     matthew  10601: #
                   10602: # EXT resource caching routines
                   10603: #
                   10604: 
                   10605: sub clear_EXT_cache_status {
1.383     albertel 10606:     &delenv('cache.EXT.');
1.379     matthew  10607: }
                   10608: 
                   10609: sub EXT_cache_status {
                   10610:     my ($target_domain,$target_user) = @_;
1.383     albertel 10611:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 10612:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  10613:         # We know already the user has no data
                   10614:         return 1;
                   10615:     } else {
                   10616:         return 0;
                   10617:     }
                   10618: }
                   10619: 
                   10620: sub EXT_cache_set {
                   10621:     my ($target_domain,$target_user) = @_;
1.383     albertel 10622:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  10623:     #&appenv({$cachename => time});
1.379     matthew  10624: }
                   10625: 
1.28      www      10626: # --------------------------------------------------------- Value of a Variable
1.58      www      10627: sub EXT {
1.715     albertel 10628: 
1.1172.2.28  raeburn  10629:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      10630:     unless ($varname) { return ''; }
1.218     albertel 10631:     #get real user name/domain, courseid and symb
                   10632:     my $courseid;
1.359     albertel 10633:     my $publicuser;
1.427     www      10634:     if ($symbparm) {
                   10635: 	$symbparm=&get_symb_from_alias($symbparm);
                   10636:     }
1.218     albertel 10637:     if (!($uname && $udom)) {
1.790     albertel 10638:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 10639:       if (!$symbparm) {	$symbparm=$cursymb; }
                   10640:     } else {
1.620     albertel 10641: 	$courseid=$env{'request.course.id'};
1.218     albertel 10642:     }
1.48      www      10643:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   10644:     my $rest;
1.320     albertel 10645:     if (defined($therest[0])) {
1.48      www      10646:        $rest=join('.',@therest);
                   10647:     } else {
                   10648:        $rest='';
                   10649:     }
1.320     albertel 10650: 
1.57      www      10651:     my $qualifierrest=$qualifier;
                   10652:     if ($rest) { $qualifierrest.='.'.$rest; }
                   10653:     my $spacequalifierrest=$space;
                   10654:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      10655:     if ($realm eq 'user') {
1.48      www      10656: # --------------------------------------------------------------- user.resource
                   10657: 	if ($space eq 'resource') {
1.651     albertel 10658: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   10659: 		  || defined($Apache::lonhomework::parsing_a_task))
                   10660: 		 &&
1.744     albertel 10661: 		 ($symbparm eq &symbread()) ) {	
                   10662: 		# if we are in the middle of processing the resource the
                   10663: 		# get the value we are planning on committing
                   10664:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   10665:                     return $Apache::lonhomework::results{$qualifierrest};
                   10666:                 } else {
                   10667:                     return $Apache::lonhomework::history{$qualifierrest};
                   10668:                 }
1.335     albertel 10669: 	    } else {
1.359     albertel 10670: 		my %restored;
1.620     albertel 10671: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 10672: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   10673: 		} else {
                   10674: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   10675: 		}
1.335     albertel 10676: 		return $restored{$qualifierrest};
                   10677: 	    }
1.48      www      10678: # ----------------------------------------------------------------- user.access
                   10679:         } elsif ($space eq 'access') {
1.218     albertel 10680: 	    # FIXME - not supporting calls for a specific user
1.48      www      10681:             return &allowed($qualifier,$rest);
                   10682: # ------------------------------------------ user.preferences, user.environment
                   10683:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 10684: 	    if (($uname eq $env{'user.name'}) &&
                   10685: 		($udom eq $env{'user.domain'})) {
                   10686: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 10687: 	    } else {
1.359     albertel 10688: 		my %returnhash;
                   10689: 		if (!$publicuser) {
                   10690: 		    %returnhash=&userenvironment($udom,$uname,
                   10691: 						 $qualifierrest);
                   10692: 		}
1.218     albertel 10693: 		return $returnhash{$qualifierrest};
                   10694: 	    }
1.48      www      10695: # ----------------------------------------------------------------- user.course
                   10696:         } elsif ($space eq 'course') {
1.218     albertel 10697: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10698:             return $env{join('.',('request.course',$qualifier))};
1.48      www      10699: # ------------------------------------------------------------------- user.role
                   10700:         } elsif ($space eq 'role') {
1.218     albertel 10701: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10702:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      10703:             if ($qualifier eq 'value') {
                   10704: 		return $role;
                   10705:             } elsif ($qualifier eq 'extent') {
                   10706:                 return $where;
                   10707:             }
                   10708: # ----------------------------------------------------------------- user.domain
                   10709:         } elsif ($space eq 'domain') {
1.218     albertel 10710:             return $udom;
1.48      www      10711: # ------------------------------------------------------------------- user.name
                   10712:         } elsif ($space eq 'name') {
1.218     albertel 10713:             return $uname;
1.48      www      10714: # ---------------------------------------------------- Any other user namespace
1.29      www      10715:         } else {
1.359     albertel 10716: 	    my %reply;
                   10717: 	    if (!$publicuser) {
                   10718: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   10719: 	    }
                   10720: 	    return $reply{$qualifierrest};
1.48      www      10721:         }
1.236     www      10722:     } elsif ($realm eq 'query') {
                   10723: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 10724:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   10725: 						[$spacequalifierrest]);
1.620     albertel 10726: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      10727:    } elsif ($realm eq 'request') {
1.48      www      10728: # ------------------------------------------------------------- request.browser
                   10729:         if ($space eq 'browser') {
1.1145    bisitz   10730:             return $env{'browser.'.$qualifier};
1.57      www      10731: # ------------------------------------------------------------ request.filename
                   10732:         } else {
1.620     albertel 10733:             return $env{'request.'.$spacequalifierrest};
1.29      www      10734:         }
1.28      www      10735:     } elsif ($realm eq 'course') {
1.48      www      10736: # ---------------------------------------------------------- course.description
1.620     albertel 10737:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      10738:     } elsif ($realm eq 'resource') {
1.165     www      10739: 
1.620     albertel 10740: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 10741: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   10742: 	}
1.693     albertel 10743: 
1.1172.2.30  raeburn  10744:         if ($qualifier eq '') {
                   10745: 	    if ($space eq 'title') {
                   10746: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   10747: 	        return &gettitle($symbparm);
                   10748: 	    }
1.693     albertel 10749: 	
1.1172.2.30  raeburn  10750: 	    if ($space eq 'map') {
                   10751: 	        my ($map) = &decode_symb($symbparm);
                   10752: 	        return &symbread($map);
                   10753: 	    }
                   10754:             if ($space eq 'maptitle') {
                   10755:                 my ($map) = &decode_symb($symbparm);
                   10756:                 return &gettitle($map);
                   10757:             }
                   10758: 	    if ($space eq 'filename') {
                   10759: 	        if ($symbparm) {
                   10760: 		    return &clutter((&decode_symb($symbparm))[2]);
                   10761: 	        }
                   10762: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 10763: 	    }
1.1172.2.30  raeburn  10764: 
                   10765:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   10766:                 if ($space eq 'visibleparts') {
                   10767:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   10768:                     my $item;
                   10769:                     if (ref($navmap)) {
                   10770:                         my $res = $navmap->getBySymb($symbparm);
                   10771:                         my $parts = $res->parts();
                   10772:                         if (ref($parts) eq 'ARRAY') {
                   10773:                             $item = join(',',@{$parts});
                   10774:                         }
                   10775:                         undef($navmap);
                   10776:                     }
                   10777:                     return $item;
                   10778:                 }
                   10779:             }
                   10780:         }
1.693     albertel 10781: 
                   10782: 	my ($section, $group, @groups);
1.593     albertel 10783: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  10784:         if (($courseid eq '') && ($cid)) {
                   10785:             $courseid = $cid;
                   10786:         }
                   10787: 	if (($symbparm && $courseid) && 
                   10788: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      10789: 
1.218     albertel 10790: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      10791: 
1.60      www      10792: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 10793: 	    my $symbp=$symbparm;
1.735     albertel 10794: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 10795: 
                   10796: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   10797: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   10798: 
1.620     albertel 10799: 	    if (($env{'user.name'} eq $uname) &&
                   10800: 		($env{'user.domain'} eq $udom)) {
                   10801: 		$section=$env{'request.course.sec'};
1.733     raeburn  10802:                 @groups = split(/:/,$env{'request.course.groups'});  
                   10803:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 10804: 	    } else {
1.539     albertel 10805: 		if (! defined($usection)) {
1.551     albertel 10806: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 10807: 		} else {
                   10808: 		    $section = $usection;
                   10809: 		}
1.733     raeburn  10810:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 10811: 	    }
                   10812: 
                   10813: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   10814: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   10815: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   10816: 
1.593     albertel 10817: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 10818: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 10819: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      10820: 
1.60      www      10821: # ----------------------------------------------------------- first, check user
1.624     albertel 10822: 
                   10823: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 10824: 				       ([$courselevelr,'resource'],
                   10825: 					[$courselevelm,'map'     ],
                   10826: 					[$courselevel, 'course'  ]));
1.931     albertel 10827: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      10828: 
1.594     albertel 10829: # ------------------------------------------------ second, check some of course
1.684     raeburn  10830:             my $coursereply;
1.691     raeburn  10831:             if (@groups > 0) {
                   10832:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   10833:                                        $mapparm,$spacequalifierrest);
1.927     albertel 10834:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  10835:             }
1.96      www      10836: 
1.684     raeburn  10837: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 10838: 				  $env{'course.'.$courseid.'.domain'},
                   10839: 				  'course',
                   10840: 				  ([$seclevelr,   'resource'],
                   10841: 				   [$seclevelm,   'map'     ],
                   10842: 				   [$seclevel,    'course'  ],
                   10843: 				   [$courselevelr,'resource']));
                   10844: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      10845: 
1.60      www      10846: # ------------------------------------------------------ third, check map parms
1.218     albertel 10847: 	    my %parmhash=();
                   10848: 	    my $thisparm='';
                   10849: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 10850: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 10851: 		    &GDBM_READER(),0640)) {
1.218     albertel 10852: 		$thisparm=$parmhash{$symbparm};
                   10853: 		untie(%parmhash);
                   10854: 	    }
1.927     albertel 10855: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 10856: 	}
1.594     albertel 10857: # ------------------------------------------ fourth, look in resource metadata
1.71      www      10858: 
1.218     albertel 10859: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 10860: 	my $filename;
                   10861: 	if (!$symbparm) { $symbparm=&symbread(); }
                   10862: 	if ($symbparm) {
1.409     www      10863: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 10864: 	} else {
1.620     albertel 10865: 	    $filename=$env{'request.filename'};
1.282     albertel 10866: 	}
                   10867: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 10868: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 10869: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 10870: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      10871: 
1.927     albertel 10872: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 10873: 	if ($symbparm && defined($courseid) && 
1.620     albertel 10874: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 10875: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   10876: 				     $env{'course.'.$courseid.'.domain'},
                   10877: 				     'course',
1.927     albertel 10878: 				     ([$courselevelm,'map'   ],
                   10879: 				      [$courselevel, 'course']));
                   10880: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 10881: 	}
1.145     www      10882: # ------------------------------------------------------------------ Cascade up
1.218     albertel 10883: 	unless ($space eq '0') {
1.336     albertel 10884: 	    my @parts=split(/_/,$space);
                   10885: 	    my $id=pop(@parts);
                   10886: 	    my $part=join('_',@parts);
                   10887: 	    if ($part eq '') { $part='0'; }
1.927     albertel 10888: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 10889: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  10890: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 10891: 	}
1.395     albertel 10892: 	if ($recurse) { return undef; }
                   10893: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 10894: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      10895: # ---------------------------------------------------- Any other user namespace
                   10896:     } elsif ($realm eq 'environment') {
                   10897: # ----------------------------------------------------------------- environment
1.620     albertel 10898: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   10899: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 10900: 	} else {
1.770     albertel 10901: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   10902: 		return '';
                   10903: 	    }
1.219     albertel 10904: 	    my %returnhash=&userenvironment($udom,$uname,
                   10905: 					    $spacequalifierrest);
                   10906: 	    return $returnhash{$spacequalifierrest};
                   10907: 	}
1.28      www      10908:     } elsif ($realm eq 'system') {
1.48      www      10909: # ----------------------------------------------------------------- system.time
                   10910: 	if ($space eq 'time') {
                   10911: 	    return time;
                   10912:         }
1.696     albertel 10913:     } elsif ($realm eq 'server') {
                   10914: # ----------------------------------------------------------------- system.time
                   10915: 	if ($space eq 'name') {
                   10916: 	    return $ENV{'SERVER_NAME'};
                   10917:         }
1.28      www      10918:     }
1.48      www      10919:     return '';
1.61      www      10920: }
                   10921: 
1.927     albertel 10922: sub get_reply {
                   10923:     my ($reply_value) = @_;
1.940     raeburn  10924:     if (ref($reply_value) eq 'ARRAY') {
                   10925:         if (wantarray) {
                   10926: 	    return @$reply_value;
                   10927:         }
                   10928:         return $reply_value->[0];
                   10929:     } else {
                   10930:         return $reply_value;
1.927     albertel 10931:     }
                   10932: }
                   10933: 
1.691     raeburn  10934: sub check_group_parms {
                   10935:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   10936:     my @groupitems = ();
                   10937:     my $resultitem;
1.927     albertel 10938:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  10939:     foreach my $group (@{$groups}) {
                   10940:         foreach my $level (@levels) {
1.927     albertel 10941:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   10942:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  10943:         }
                   10944:     }
                   10945:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   10946:                             $env{'course.'.$courseid.'.domain'},
                   10947:                                      'course',@groupitems);
                   10948:     return $coursereply;
                   10949: }
                   10950: 
                   10951: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  10952:     my ($courseid,@groups) = @_;
                   10953:     @groups = sort(@groups);
1.691     raeburn  10954:     return @groups;
                   10955: }
                   10956: 
1.395     albertel 10957: sub packages_tab_default {
                   10958:     my ($uri,$varname)=@_;
                   10959:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 10960: 
                   10961:     my (@extension,@specifics,$do_default);
                   10962:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 10963: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 10964: 	if ($pack_type eq 'default') {
                   10965: 	    $do_default=1;
                   10966: 	} elsif ($pack_type eq 'extension') {
                   10967: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 10968: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 10969: 	    # only look at packages defaults for packages that this id is
1.738     albertel 10970: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   10971: 	}
                   10972:     }
                   10973:     # first look for a package that matches the requested part id
                   10974:     foreach my $package (@specifics) {
                   10975: 	my (undef,$pack_type,$pack_part)=@{$package};
                   10976: 	next if ($pack_part ne $part);
                   10977: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10978: 	    return $packagetab{"$pack_type&$name&default"};
                   10979: 	}
                   10980:     }
                   10981:     # look for any possible matching non extension_ package
                   10982:     foreach my $package (@specifics) {
                   10983: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 10984: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10985: 	    return $packagetab{"$pack_type&$name&default"};
                   10986: 	}
1.585     albertel 10987: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 10988: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   10989: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 10990: 	}
                   10991:     }
1.738     albertel 10992:     # look for any posible extension_ match
                   10993:     foreach my $package (@extension) {
                   10994: 	my ($package,$pack_type)=@{$package};
                   10995: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10996: 	    return $packagetab{"$pack_type&$name&default"};
                   10997: 	}
                   10998: 	if (defined($packagetab{$package."&$name&default"})) {
                   10999: 	    return $packagetab{$package."&$name&default"};
                   11000: 	}
                   11001:     }
                   11002:     # look for a global default setting
                   11003:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11004: 	return $packagetab{"default&$name&default"};
                   11005:     }
1.395     albertel 11006:     return undef;
                   11007: }
                   11008: 
1.334     albertel 11009: sub add_prefix_and_part {
                   11010:     my ($prefix,$part)=@_;
                   11011:     my $keyroot;
                   11012:     if (defined($prefix) && $prefix !~ /^__/) {
                   11013: 	# prefix that has a part already
                   11014: 	$keyroot=$prefix;
                   11015:     } elsif (defined($prefix)) {
                   11016: 	# prefix that is missing a part
                   11017: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11018:     } else {
                   11019: 	# no prefix at all
                   11020: 	if (defined($part)) { $keyroot='_'.$part; }
                   11021:     }
                   11022:     return $keyroot;
                   11023: }
                   11024: 
1.71      www      11025: # ---------------------------------------------------------------- Get metadata
                   11026: 
1.599     albertel 11027: my %metaentry;
1.1070    www      11028: my %importedpartids;
1.71      www      11029: sub metadata {
1.176     www      11030:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      11031:     $uri=&declutter($uri);
1.288     albertel 11032:     # if it is a non metadata possible uri return quickly
1.529     albertel 11033:     if (($uri eq '') || 
                   11034: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.93.4  2(raebur 11035:7): 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108    raeburn  11036:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11037: 	return undef;
                   11038:     }
1.1172.2.49  raeburn  11039:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11040: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11041: 	return undef;
1.288     albertel 11042:     }
1.73      www      11043:     my $filename=$uri;
                   11044:     $uri=~s/\.meta$//;
1.172     www      11045: #
                   11046: # Is the metadata already cached?
1.177     www      11047: # Look at timestamp of caching
1.172     www      11048: # Everything is cached by the main uri, libraries are never directly cached
                   11049: #
1.428     albertel 11050:     if (!defined($liburi)) {
1.599     albertel 11051: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11052: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11053:     }
                   11054:     {
1.1069    www      11055: # Imported parts would go here
1.1070    www      11056:         my %importedids=();
                   11057:         my @origfileimportpartids=();
1.1069    www      11058:         my $importedparts=0;
1.172     www      11059: #
                   11060: # Is this a recursive call for a library?
                   11061: #
1.599     albertel 11062: #	if (! exists($metacache{$uri})) {
                   11063: #	    $metacache{$uri}={};
                   11064: #	}
1.924     albertel 11065: 	my $cachetime = 60*60;
1.171     www      11066:         if ($liburi) {
                   11067: 	    $liburi=&declutter($liburi);
                   11068:             $filename=$liburi;
1.401     bowersj2 11069:         } else {
1.599     albertel 11070: 	    &devalidate_cache_new('meta',$uri);
                   11071: 	    undef(%metaentry);
1.401     bowersj2 11072: 	}
1.140     www      11073:         my %metathesekeys=();
1.73      www      11074:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 11075: 	my $metastring;
1.1140    www      11076: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 11077: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 11078: 	    $metastring = 
1.929     albertel 11079: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 11080: 					  ('grade_target' => 'meta'));
                   11081: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  11082: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   11083:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 11084: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 11085: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 11086: 	    $metastring=&getfile($file);
1.489     albertel 11087: 	}
1.208     albertel 11088:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      11089:         my $token;
1.140     www      11090:         undef %metathesekeys;
1.71      www      11091:         while ($token=$parser->get_token) {
1.339     albertel 11092: 	    if ($token->[0] eq 'S') {
                   11093: 		if (defined($token->[2]->{'package'})) {
1.172     www      11094: #
                   11095: # This is a package - get package info
                   11096: #
1.339     albertel 11097: 		    my $package=$token->[2]->{'package'};
                   11098: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11099: 		    if (defined($token->[2]->{'id'})) { 
                   11100: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   11101: 		    }
1.599     albertel 11102: 		    if ($metaentry{':packages'}) {
                   11103: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 11104: 		    } else {
1.599     albertel 11105: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 11106: 		    }
1.736     albertel 11107: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 11108: 			my $part=$keyroot;
                   11109: 			$part=~s/^\_//;
1.736     albertel 11110: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   11111: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   11112: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 11113: 			    # ignore package.tab specified default values
                   11114:                             # here &package_tab_default() will fetch those
                   11115: 			    if ($subp eq 'default') { next; }
1.736     albertel 11116: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 11117: 			    my $unikey;
                   11118: 			    if ($pack =~ /_0$/) {
                   11119: 				$unikey='parameter_0_'.$name;
                   11120: 				$part=0;
                   11121: 			    } else {
                   11122: 				$unikey='parameter'.$keyroot.'_'.$name;
                   11123: 			    }
1.339     albertel 11124: 			    if ($subp eq 'display') {
                   11125: 				$value.=' [Part: '.$part.']';
                   11126: 			    }
1.599     albertel 11127: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 11128: 			    $metathesekeys{$unikey}=1;
1.599     albertel 11129: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11130: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 11131: 			    }
1.599     albertel 11132: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   11133: 				$metaentry{':'.$unikey}=
                   11134: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 11135: 			    }
1.339     albertel 11136: 			}
                   11137: 		    }
                   11138: 		} else {
1.172     www      11139: #
                   11140: # This is not a package - some other kind of start tag
1.339     albertel 11141: #
                   11142: 		    my $entry=$token->[1];
1.1068    www      11143: 		    my $unikey='';
1.175     www      11144: 
1.339     albertel 11145: 		    if ($entry eq 'import') {
1.175     www      11146: #
                   11147: # Importing a library here
1.339     albertel 11148: #
1.1067    www      11149:                         my $location=$parser->get_text('/import');
                   11150:                         my $dir=$filename;
                   11151:                         $dir=~s|[^/]*$||;
                   11152:                         $location=&filelocation($dir,$location);
1.1069    www      11153:                        
1.1068    www      11154:                         my $importmode=$token->[2]->{'importmode'};
                   11155:                         if ($importmode eq 'problem') {
1.1069    www      11156: # Import as problem/response
1.1068    www      11157:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11158:                         } elsif ($importmode eq 'part') {
                   11159: # Import as part(s)
1.1069    www      11160:                            $importedparts=1;
                   11161: # We need to get the original file and the imported file to get the part order correct
                   11162: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   11163: # Load and inspect original file
1.1070    www      11164:                            if ($#origfileimportpartids<0) {
                   11165:                               undef(%importedpartids);
                   11166:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11167:                               my $origfile=&getfile($origfilelocation);
                   11168:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11169:                            }
                   11170: 
1.1069    www      11171: # Load and inspect imported file
                   11172:                            my $impfile=&getfile($location);
                   11173:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11174:                            if ($#impfilepartids>=0) {
                   11175: # This problem had parts
1.1070    www      11176:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      11177:                            } else {
                   11178: # Importing by turning a single problem into a problem part
                   11179: # It gets the import-tags ID as part-ID
                   11180:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      11181:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      11182:                            }
1.1068    www      11183:                         } else {
                   11184: # Normal import
                   11185:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11186:                            if (defined($token->[2]->{'id'})) {
                   11187:                               $unikey.='_'.$token->[2]->{'id'};
                   11188:                            }
1.1067    www      11189:                         }
                   11190: 
1.339     albertel 11191: 			if ($depthcount<20) {
1.736     albertel 11192: 			    my $metadata = 
                   11193: 				&metadata($uri,'keys', $location,$unikey,
                   11194: 					  $depthcount+1);
                   11195: 			    foreach my $meta (split(',',$metadata)) {
                   11196: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   11197: 				$metathesekeys{$meta}=1;
1.339     albertel 11198: 			    }
1.1068    www      11199: 			
                   11200:                         }
1.1067    www      11201: 		    } else {
                   11202: #
                   11203: # Not importing, some other kind of non-package, non-library start tag
                   11204: # 
                   11205:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11206:                         if (defined($token->[2]->{'id'})) {
                   11207:                             $unikey.='_'.$token->[2]->{'id'};
                   11208:                         }
1.339     albertel 11209: 			if (defined($token->[2]->{'name'})) { 
                   11210: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   11211: 			}
                   11212: 			$metathesekeys{$unikey}=1;
1.736     albertel 11213: 			foreach my $param (@{$token->[3]}) {
                   11214: 			    $metaentry{':'.$unikey.'.'.$param} =
                   11215: 				$token->[2]->{$param};
1.339     albertel 11216: 			}
                   11217: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 11218: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 11219: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   11220: 		 # only ws inside the tag, and not in default, so use default
                   11221: 		 # as value
1.599     albertel 11222: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 11223: 			} elsif ( $internaltext =~ /\S/ ) {
                   11224: 		  # something interesting inside the tag
                   11225: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 11226: 			} else {
1.908     albertel 11227: 		  # no interesting values, don't set a default
1.339     albertel 11228: 			}
1.172     www      11229: # end of not-a-package not-a-library import
1.339     albertel 11230: 		    }
1.172     www      11231: # end of not-a-package start tag
1.339     albertel 11232: 		}
1.172     www      11233: # the next is the end of "start tag"
1.339     albertel 11234: 	    }
                   11235: 	}
1.483     albertel 11236: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 11237: 	$extension = lc($extension);
                   11238: 	if ($extension eq 'htm') { $extension='html'; }
                   11239: 
1.737     albertel 11240: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 11241: 	    #no specific packages #how's our extension
                   11242: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 11243: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 11244: 					 \%metathesekeys);
                   11245: 	}
1.883     albertel 11246: 
                   11247: 	if (!exists($metaentry{':packages'})
                   11248: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 11249: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 11250: 		#no specific packages well let's get default then
                   11251: 		if ($key!~/^default&/) { next; }
1.488     albertel 11252: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 11253: 					     \%metathesekeys);
                   11254: 	    }
                   11255: 	}
1.338     www      11256: # are there custom rights to evaluate
1.599     albertel 11257: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 11258: 
1.338     www      11259:     #
                   11260:     # Importing a rights file here
1.339     albertel 11261:     #
                   11262: 	    unless ($depthcount) {
1.599     albertel 11263: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 11264: 		my $dir=$filename;
                   11265: 		$dir=~s|[^/]*$||;
                   11266: 		$location=&filelocation($dir,$location);
1.736     albertel 11267: 		my $rights_metadata =
                   11268: 		    &metadata($uri,'keys',$location,'_rights',
                   11269: 			      $depthcount+1);
                   11270: 		foreach my $rights (split(',',$rights_metadata)) {
                   11271: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   11272: 		    $metathesekeys{$rights}=1;
1.339     albertel 11273: 		}
                   11274: 	    }
                   11275: 	}
1.737     albertel 11276: 	# uniqifiy package listing
                   11277: 	my %seen;
                   11278: 	my @uniq_packages =
                   11279: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   11280: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   11281: 
1.1070    www      11282:         if ($importedparts) {
                   11283: # We had imported parts and need to rebuild partorder
                   11284:            $metaentry{':partorder'}='';
                   11285:            $metathesekeys{'partorder'}=1;
                   11286:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   11287:                if ($origfileimportpartids[$index] eq 'part') {
                   11288: # original part, part of the problem
                   11289:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   11290:                } else {
                   11291: # we have imported parts at this position
                   11292:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   11293:                }
                   11294:            }
                   11295:            $metaentry{':partorder'}=~s/^\,//;
                   11296:         }
                   11297: 
1.737     albertel 11298: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 11299: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58  raeburn  11300: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 11301: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      11302: # this is the end of "was not already recently cached
1.71      www      11303:     }
1.599     albertel 11304:     return $metaentry{':'.$what};
1.261     albertel 11305: }
                   11306: 
1.488     albertel 11307: sub metadata_create_package_def {
1.483     albertel 11308:     my ($uri,$key,$package,$metathesekeys)=@_;
                   11309:     my ($pack,$name,$subp)=split(/\&/,$key);
                   11310:     if ($subp eq 'default') { next; }
                   11311:     
1.599     albertel 11312:     if (defined($metaentry{':packages'})) {
                   11313: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 11314:     } else {
1.599     albertel 11315: 	$metaentry{':packages'}=$package;
1.483     albertel 11316:     }
                   11317:     my $value=$packagetab{$key};
                   11318:     my $unikey;
                   11319:     $unikey='parameter_0_'.$name;
1.599     albertel 11320:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 11321:     $$metathesekeys{$unikey}=1;
1.599     albertel 11322:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11323: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 11324:     }
1.599     albertel 11325:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   11326: 	$metaentry{':'.$unikey}=
                   11327: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 11328:     }
                   11329: }
                   11330: 
1.261     albertel 11331: sub metadata_generate_part0 {
                   11332:     my ($metadata,$metacache,$uri) = @_;
                   11333:     my %allnames;
1.737     albertel 11334:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 11335: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 11336: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   11337: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 11338: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 11339: 	    $allnames{$name}=$part;
                   11340: 	  }
                   11341: 	}
                   11342:     }
                   11343:     foreach my $name (keys(%allnames)) {
                   11344:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 11345:       my $key=":parameter_0_$name";
1.261     albertel 11346:       $$metacache{"$key.part"}='0';
                   11347:       $$metacache{"$key.name"}=$name;
1.428     albertel 11348:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 11349: 					   $allnames{$name}.'_'.$name.
                   11350: 					   '.type'};
1.428     albertel 11351:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 11352: 			     '.display'};
1.644     www      11353:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 11354:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 11355:       $$metacache{"$key.display"}=$olddis;
                   11356:     }
1.71      www      11357: }
                   11358: 
1.764     albertel 11359: # ------------------------------------------------------ Devalidate title cache
                   11360: 
                   11361: sub devalidate_title_cache {
                   11362:     my ($url)=@_;
                   11363:     if (!$env{'request.course.id'}) { return; }
                   11364:     my $symb=&symbread($url);
                   11365:     if (!$symb) { return; }
                   11366:     my $key=$env{'request.course.id'}."\0".$symb;
                   11367:     &devalidate_cache_new('title',$key);
                   11368: }
                   11369: 
1.1014    droeschl 11370: # ------------------------------------------------- Get the title of a course
                   11371: 
                   11372: sub current_course_title {
                   11373:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   11374: }
1.301     www      11375: # ------------------------------------------------- Get the title of a resource
                   11376: 
                   11377: sub gettitle {
                   11378:     my $urlsymb=shift;
                   11379:     my $symb=&symbread($urlsymb);
1.534     albertel 11380:     if ($symb) {
1.620     albertel 11381: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 11382: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 11383: 	if (defined($cached)) { 
                   11384: 	    return $result;
                   11385: 	}
1.534     albertel 11386: 	my ($map,$resid,$url)=&decode_symb($symb);
                   11387: 	my $title='';
1.907     albertel 11388: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   11389: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   11390: 	} else {
                   11391: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11392: 		    &GDBM_READER(),0640)) {
                   11393: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   11394: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   11395: 		untie(%bighash);
                   11396: 	    }
1.534     albertel 11397: 	}
                   11398: 	$title=~s/\&colon\;/\:/gs;
                   11399: 	if ($title) {
1.1159    www      11400: # Remember both $symb and $title for dynamic metadata
                   11401:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      11402:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      11403: # Cache this title and then return it
1.599     albertel 11404: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 11405: 	}
                   11406: 	$urlsymb=$url;
                   11407:     }
                   11408:     my $title=&metadata($urlsymb,'title');
                   11409:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   11410:     return $title;
1.301     www      11411: }
1.613     albertel 11412: 
1.614     albertel 11413: sub get_slot {
                   11414:     my ($which,$cnum,$cdom)=@_;
                   11415:     if (!$cnum || !$cdom) {
1.790     albertel 11416: 	(undef,my $courseid)=&whichuser();
1.620     albertel 11417: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   11418: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 11419:     }
1.703     albertel 11420:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   11421:     my %slotinfo;
                   11422:     if (exists($remembered{$key})) {
                   11423: 	$slotinfo{$which} = $remembered{$key};
                   11424:     } else {
                   11425: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   11426: 	&Apache::lonhomework::showhash(%slotinfo);
                   11427: 	my ($tmp)=keys(%slotinfo);
                   11428: 	if ($tmp=~/^error:/) { return (); }
                   11429: 	$remembered{$key} = $slotinfo{$which};
                   11430:     }
1.616     albertel 11431:     if (ref($slotinfo{$which}) eq 'HASH') {
                   11432: 	return %{$slotinfo{$which}};
                   11433:     }
                   11434:     return $slotinfo{$which};
1.614     albertel 11435: }
1.1150    raeburn  11436: 
                   11437: sub get_reservable_slots {
                   11438:     my ($cnum,$cdom,$uname,$udom) = @_;
                   11439:     my $now = time;
                   11440:     my $reservable_info;
                   11441:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   11442:     if (exists($remembered{$key})) {
                   11443:         $reservable_info = $remembered{$key};
                   11444:     } else {
                   11445:         my %resv;
                   11446:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   11447:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   11448:         $reservable_info = \%resv;
                   11449:         $remembered{$key} = $reservable_info;
                   11450:     }
                   11451:     return $reservable_info;
                   11452: }
                   11453: 
                   11454: sub get_course_slots {
                   11455:     my ($cnum,$cdom) = @_;
                   11456:     my $hashid=$cnum.':'.$cdom;
                   11457:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   11458:     if (defined($cached)) {
                   11459:         if (ref($result) eq 'HASH') {
                   11460:             return %{$result};
                   11461:         }
                   11462:     } else {
                   11463:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   11464:         my ($tmp) = keys(%slots);
                   11465:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  11466:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  11467:             return %slots;
                   11468:         }
                   11469:     }
                   11470:     return;
                   11471: }
                   11472: 
                   11473: sub devalidate_slots_cache {
                   11474:     my ($cnum,$cdom)=@_;
                   11475:     my $hashid=$cnum.':'.$cdom;
                   11476:     &devalidate_cache_new('allslots',$hashid);
                   11477: }
                   11478: 
1.1172.2.8  raeburn  11479: sub get_coursechange {
                   11480:     my ($cdom,$cnum) = @_;
                   11481:     if ($cdom eq '' || $cnum eq '') {
                   11482:         return unless ($env{'request.course.id'});
                   11483:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   11484:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   11485:     }
                   11486:     my $hashid=$cdom.'_'.$cnum;
                   11487:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   11488:     if ((defined($cached)) && ($change ne '')) {
                   11489:         return $change;
                   11490:     } else {
                   11491:         my %crshash;
                   11492:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   11493:         if ($crshash{'internal.contentchange'} eq '') {
                   11494:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   11495:             if ($change eq '') {
                   11496:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   11497:                 $change = $crshash{'internal.created'};
                   11498:             }
                   11499:         } else {
                   11500:             $change = $crshash{'internal.contentchange'};
                   11501:         }
                   11502:         my $cachetime = 600;
                   11503:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   11504:     }
                   11505:     return $change;
                   11506: }
                   11507: 
                   11508: sub devalidate_coursechange_cache {
                   11509:     my ($cnum,$cdom)=@_;
                   11510:     my $hashid=$cnum.':'.$cdom;
                   11511:     &devalidate_cache_new('crschange',$hashid);
                   11512: }
                   11513: 
1.31      www      11514: # ------------------------------------------------- Update symbolic store links
                   11515: 
                   11516: sub symblist {
                   11517:     my ($mapname,%newhash)=@_;
1.438     www      11518:     $mapname=&deversion(&declutter($mapname));
1.31      www      11519:     my %hash;
1.620     albertel 11520:     if (($env{'request.course.fn'}) && (%newhash)) {
                   11521:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11522:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  11523: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 11524: 		next if ($url eq 'last_known'
                   11525: 			 && $env{'form.no_update_last_known'});
                   11526: 		$hash{declutter($url)}=&encode_symb($mapname,
                   11527: 						    $newhash{$url}->[1],
                   11528: 						    $newhash{$url}->[0]);
1.191     harris41 11529:             }
1.31      www      11530:             if (untie(%hash)) {
                   11531: 		return 'ok';
                   11532:             }
                   11533:         }
                   11534:     }
                   11535:     return 'error';
1.212     www      11536: }
                   11537: 
                   11538: # --------------------------------------------------------------- Verify a symb
                   11539: 
                   11540: sub symbverify {
1.1172.2.11  raeburn  11541:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      11542:     my $thisfn=$thisurl;
1.439     www      11543:     $thisfn=&declutter($thisfn);
1.215     www      11544: # direct jump to resource in page or to a sequence - will construct own symbs
                   11545:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   11546: # check URL part
1.409     www      11547:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      11548: 
1.431     www      11549:     unless ($url eq $thisfn) { return 0; }
1.213     www      11550: 
1.216     www      11551:     $symb=&symbclean($symb);
1.510     www      11552:     $thisurl=&deversion($thisurl);
1.439     www      11553:     $thisfn=&deversion($thisfn);
1.213     www      11554: 
                   11555:     my %bighash;
                   11556:     my $okay=0;
1.431     www      11557: 
1.620     albertel 11558:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11559:                             &GDBM_READER(),0640)) {
1.1172.2.13  raeburn  11560:         my $noclutter;
1.1032    raeburn  11561:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   11562:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  11563:             if ($map =~ m{^uploaded/.+\.page$}) {
                   11564:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   11565:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   11566:                 $noclutter = 1;
                   11567:             }
                   11568:         }
                   11569:         my $ids;
                   11570:         if ($noclutter) {
                   11571:             $ids=$bighash{'ids_'.$thisurl};
                   11572:         } else {
                   11573:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  11574:         }
1.1102    raeburn  11575:         unless ($ids) {
1.1172.2.13  raeburn  11576:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  11577:             $ids=$bighash{$idkey};
1.216     www      11578:         }
                   11579:         if ($ids) {
                   11580: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  11581:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   11582:                 $symb =~ s/\?.+$//;
                   11583:             }
1.800     albertel 11584: 	    foreach my $id (split(/\,/,$ids)) {
                   11585: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      11586:                if (
                   11587:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  11588:    eq $symb) {
1.1172.2.11  raeburn  11589:                    if (ref($encstate)) {
                   11590:                        $$encstate = $bighash{'encrypted_'.$id};
                   11591:                    }
1.1172.2.13  raeburn  11592:                    if (($env{'request.role.adv'}) ||
                   11593:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  11594:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  11595:                        $okay=1;
                   11596:                        last;
                   11597:                    }
                   11598:                }
                   11599:            }
1.216     www      11600:         }
1.213     www      11601: 	untie(%bighash);
                   11602:     }
                   11603:     return $okay;
1.31      www      11604: }
                   11605: 
1.210     www      11606: # --------------------------------------------------------------- Clean-up symb
                   11607: 
                   11608: sub symbclean {
                   11609:     my $symb=shift;
1.568     albertel 11610:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      11611: # remove version from map
                   11612:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      11613: 
1.210     www      11614: # remove version from URL
                   11615:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      11616: 
1.507     www      11617: # remove wrapper
                   11618: 
1.510     www      11619:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 11620:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      11621:     return $symb;
1.409     www      11622: }
                   11623: 
                   11624: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 11625: 
                   11626: sub encode_symb {
                   11627:     my ($map,$resid,$url)=@_;
                   11628:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   11629: }
1.409     www      11630: 
                   11631: sub decode_symb {
1.568     albertel 11632:     my $symb=shift;
                   11633:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   11634:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      11635:     return (&fixversion($map),$resid,&fixversion($url));
                   11636: }
                   11637: 
                   11638: sub fixversion {
                   11639:     my $fn=shift;
1.609     banghart 11640:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      11641:     my %bighash;
                   11642:     my $uri=&clutter($fn);
1.620     albertel 11643:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      11644: # is this cached?
1.599     albertel 11645:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      11646:     if (defined($cached)) { return $result; }
                   11647: # unfortunately not cached, or expired
1.620     albertel 11648:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      11649: 	    &GDBM_READER(),0640)) {
                   11650:  	if ($bighash{'version_'.$uri}) {
                   11651:  	    my $version=$bighash{'version_'.$uri};
1.444     www      11652:  	    unless (($version eq 'mostrecent') || 
                   11653: 		    ($version==&getversion($uri))) {
1.440     www      11654:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   11655:  	    }
                   11656:  	}
                   11657:  	untie %bighash;
1.413     www      11658:     }
1.599     albertel 11659:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      11660: }
                   11661: 
                   11662: sub deversion {
                   11663:     my $url=shift;
                   11664:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   11665:     return $url;
1.210     www      11666: }
                   11667: 
1.31      www      11668: # ------------------------------------------------------ Return symb list entry
                   11669: 
                   11670: sub symbread {
1.1172.2.66  raeburn  11671:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1172.2.54  raeburn  11672:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.66  raeburn  11673:     if (defined($env{$cache_str})) {
                   11674:         if ($ignorecachednull) {
                   11675:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   11676:         } else {
                   11677:             return $env{$cache_str};
                   11678:         }
                   11679:     }
1.242     www      11680: # no filename provided? try from environment
1.1172.2.54  raeburn  11681:     unless ($thisfn) {
1.620     albertel 11682:         if ($env{'request.symb'}) {
1.1172.2.13  raeburn  11683:             return $env{$cache_str}=&symbclean($env{'request.symb'});
                   11684:         }
                   11685:         $thisfn=$env{'request.filename'};
1.44      www      11686:     }
1.569     albertel 11687:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      11688: # is that filename actually a symb? Verify, clean, and return
                   11689:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 11690: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 11691: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 11692: 	}
1.242     www      11693:     }
1.44      www      11694:     $thisfn=declutter($thisfn);
1.31      www      11695:     my %hash;
1.37      www      11696:     my %bighash;
                   11697:     my $syval='';
1.620     albertel 11698:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  11699:         my $targetfn = $thisfn;
1.609     banghart 11700:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  11701:             $targetfn = 'adm/wrapper/'.$thisfn;
                   11702:         }
1.687     albertel 11703: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   11704: 	    $targetfn=$1;
                   11705: 	}
1.620     albertel 11706:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11707:                       &GDBM_READER(),0640)) {
1.481     raeburn  11708: 	    $syval=$hash{$targetfn};
1.37      www      11709:             untie(%hash);
                   11710:         }
                   11711: # ---------------------------------------------------------- There was an entry
                   11712:         if ($syval) {
1.601     albertel 11713: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 11714: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  11715: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11716: 		    #return $env{$cache_str}='';
1.601     albertel 11717: 		#}    
                   11718: 		#$syval.=$1;
                   11719: 	    #}
1.37      www      11720:         } else {
                   11721: # ------------------------------------------------------- Was not in symb table
1.620     albertel 11722:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11723:                             &GDBM_READER(),0640)) {
1.37      www      11724: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      11725:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      11726:               unless ($ids) { 
                   11727:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      11728:               }
                   11729:               unless ($ids) {
                   11730: # alias?
                   11731: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      11732:               }
1.37      www      11733:               if ($ids) {
                   11734: # ------------------------------------------------------------------- Has ID(s)
                   11735:                  my @possibilities=split(/\,/,$ids);
1.39      www      11736:                  if ($#possibilities==0) {
                   11737: # ----------------------------------------------- There is only one possibility
1.37      www      11738: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 11739: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11740: 						    $resid,$thisfn);
1.1172.2.66  raeburn  11741:                      if (ref($possibles) eq 'HASH') {
                   11742:                          $possibles->{$syval} = 1;
                   11743:                      }
                   11744:                      if ($checkforblock) {
                   11745:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   11746:                          if (@blockers) {
                   11747:                              $syval = '';
                   11748:                              return;
                   11749:                          }
                   11750:                      }
                   11751:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39      www      11752: # ------------------------------------------ There is more than one possibility
                   11753:                      my $realpossible=0;
1.800     albertel 11754:                      foreach my $id (@possibilities) {
                   11755: 			 my $file=$bighash{'src_'.$id};
1.1172.2.66  raeburn  11756:                          my $canaccess;
                   11757:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   11758:                              $canaccess = 1;
                   11759:                          } else {
                   11760:                              $canaccess = &allowed('bre',$file);
                   11761:                          }
                   11762:                          if ($canaccess) {
                   11763:          		     my ($mapid,$resid)=split(/\./,$id);
                   11764:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   11765:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11766:                                                              $resid,$thisfn);
                   11767:                                  if (ref($possibles) eq 'HASH') {
                   11768:                                      $possibles->{$syval} = 1;
                   11769:                                  }
                   11770:                                  if ($checkforblock) {
                   11771:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   11772:                                      unless (@blockers > 0) {
                   11773:                                          $syval = $poss_syval;
                   11774:                                          $realpossible++;
                   11775:                                      }
                   11776:                                  } else {
                   11777:                                      $syval = $poss_syval;
                   11778:                                      $realpossible++;
                   11779:                                  }
                   11780:                              }
1.39      www      11781: 			 }
1.191     harris41 11782:                      }
1.39      www      11783: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      11784:                  } else {
                   11785:                      $syval='';
1.37      www      11786:                  }
                   11787: 	      }
1.1172.2.66  raeburn  11788:               untie(%bighash);
1.481     raeburn  11789:            }
1.31      www      11790:         }
1.62      www      11791:         if ($syval) {
1.620     albertel 11792: 	    return $env{$cache_str}=$syval;
1.62      www      11793:         }
1.31      www      11794:     }
1.949     raeburn  11795:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11796:     return $env{$cache_str}='';
1.31      www      11797: }
                   11798: 
                   11799: # ---------------------------------------------------------- Return random seed
                   11800: 
1.32      www      11801: sub numval {
                   11802:     my $txt=shift;
                   11803:     $txt=~tr/A-J/0-9/;
                   11804:     $txt=~tr/a-j/0-9/;
                   11805:     $txt=~tr/K-T/0-9/;
                   11806:     $txt=~tr/k-t/0-9/;
                   11807:     $txt=~tr/U-Z/0-5/;
                   11808:     $txt=~tr/u-z/0-5/;
                   11809:     $txt=~s/\D//g;
1.564     albertel 11810:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      11811:     return int($txt);
1.368     albertel 11812: }
                   11813: 
1.484     albertel 11814: sub numval2 {
                   11815:     my $txt=shift;
                   11816:     $txt=~tr/A-J/0-9/;
                   11817:     $txt=~tr/a-j/0-9/;
                   11818:     $txt=~tr/K-T/0-9/;
                   11819:     $txt=~tr/k-t/0-9/;
                   11820:     $txt=~tr/U-Z/0-5/;
                   11821:     $txt=~tr/u-z/0-5/;
                   11822:     $txt=~s/\D//g;
                   11823:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11824:     my $total;
                   11825:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 11826:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 11827:     return int($total);
                   11828: }
                   11829: 
1.575     albertel 11830: sub numval3 {
                   11831:     use integer;
                   11832:     my $txt=shift;
                   11833:     $txt=~tr/A-J/0-9/;
                   11834:     $txt=~tr/a-j/0-9/;
                   11835:     $txt=~tr/K-T/0-9/;
                   11836:     $txt=~tr/k-t/0-9/;
                   11837:     $txt=~tr/U-Z/0-5/;
                   11838:     $txt=~tr/u-z/0-5/;
                   11839:     $txt=~s/\D//g;
                   11840:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11841:     my $total;
                   11842:     foreach my $val (@txts) { $total+=$val; }
                   11843:     if ($_64bit) { $total=(($total<<32)>>32); }
                   11844:     return $total;
                   11845: }
                   11846: 
1.675     albertel 11847: sub digest {
                   11848:     my ($data)=@_;
                   11849:     my $digest=&Digest::MD5::md5($data);
                   11850:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   11851:     my ($e,$f);
                   11852:     {
                   11853:         use integer;
                   11854:         $e=($a+$b);
                   11855:         $f=($c+$d);
                   11856:         if ($_64bit) {
                   11857:             $e=(($e<<32)>>32);
                   11858:             $f=(($f<<32)>>32);
                   11859:         }
                   11860:     }
                   11861:     if (wantarray) {
                   11862: 	return ($e,$f);
                   11863:     } else {
                   11864: 	my $g;
                   11865: 	{
                   11866: 	    use integer;
                   11867: 	    $g=($e+$f);
                   11868: 	    if ($_64bit) {
                   11869: 		$g=(($g<<32)>>32);
                   11870: 	    }
                   11871: 	}
                   11872: 	return $g;
                   11873:     }
                   11874: }
                   11875: 
1.368     albertel 11876: sub latest_rnd_algorithm_id {
1.675     albertel 11877:     return '64bit5';
1.366     albertel 11878: }
1.32      www      11879: 
1.503     albertel 11880: sub get_rand_alg {
                   11881:     my ($courseid)=@_;
1.790     albertel 11882:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 11883:     if ($courseid) {
1.620     albertel 11884: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 11885:     }
                   11886:     return &latest_rnd_algorithm_id();
                   11887: }
                   11888: 
1.562     albertel 11889: sub validCODE {
                   11890:     my ($CODE)=@_;
                   11891:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   11892:     return 0;
                   11893: }
                   11894: 
1.491     albertel 11895: sub getCODE {
1.620     albertel 11896:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 11897:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   11898: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   11899: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 11900: 	return $Apache::lonhomework::history{'resource.CODE'};
                   11901:     }
                   11902:     return undef;
                   11903: }
1.1133    foxr     11904: #
                   11905: #  Determines the random seed for a specific context:
                   11906: #
                   11907: # parameters:
                   11908: #   symb      - in course context the symb for the seed.
                   11909: #   course_id - The course id of the form domain_coursenum.
                   11910: #   domain    - Domain for the user.
                   11911: #   course    - Course for the user.
                   11912: #   cenv      - environment of the course.
                   11913: #
                   11914: # NOTE:
                   11915: #   All parameters are picked out of the environment if missing
                   11916: #   or not defined.
                   11917: #   If a symb cannot be determined the current time is used instead.
                   11918: #
                   11919: #  For a given well defined symb, courside, domain, username,
                   11920: #  and course environment, the seed is reproducible.
                   11921: #
1.31      www      11922: sub rndseed {
1.1133    foxr     11923:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 11924:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 11925:     if (!defined($symb)) {
1.366     albertel 11926: 	unless ($symb=$wsymb) { return time; }
                   11927:     }
1.1146    foxr     11928:     if (!defined $courseid) { 
                   11929: 	$courseid=$wcourseid; 
                   11930:     }
                   11931:     if (!defined $domain) { $domain=$wdomain; }
                   11932:     if (!defined $username) { $username=$wusername }
1.1133    foxr     11933: 
                   11934:     my $which;
                   11935:     if (defined($cenv->{'rndseed'})) {
                   11936: 	$which = $cenv->{'rndseed'};
                   11937:     } else {
                   11938: 	$which =&get_rand_alg($courseid);
                   11939:     }
1.491     albertel 11940:     if (defined(&getCODE())) {
1.675     albertel 11941: 	if ($which eq '64bit5') {
                   11942: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   11943: 	} elsif ($which eq '64bit4') {
1.575     albertel 11944: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   11945: 	} else {
                   11946: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   11947: 	}
1.675     albertel 11948:     } elsif ($which eq '64bit5') {
                   11949: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 11950:     } elsif ($which eq '64bit4') {
                   11951: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 11952:     } elsif ($which eq '64bit3') {
                   11953: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 11954:     } elsif ($which eq '64bit2') {
                   11955: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 11956:     } elsif ($which eq '64bit') {
                   11957: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   11958:     }
                   11959:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   11960: }
                   11961: 
                   11962: sub rndseed_32bit {
                   11963:     my ($symb,$courseid,$domain,$username)=@_;
                   11964:     {
                   11965: 	use integer;
                   11966: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   11967: 	my $symbseed=numval($symb) << 22;
                   11968: 	my $namechck=unpack("%32C*",$username) << 17;
                   11969: 	my $nameseed=numval($username) << 12;
                   11970: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   11971: 	my $courseseed=unpack("%32C*",$courseid);
                   11972: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 11973: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11974: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 11975: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 11976: 	return $num;
                   11977:     }
                   11978: }
                   11979: 
                   11980: sub rndseed_64bit {
                   11981:     my ($symb,$courseid,$domain,$username)=@_;
                   11982:     {
                   11983: 	use integer;
                   11984: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   11985: 	my $symbseed=numval($symb) << 10;
                   11986: 	my $namechck=unpack("%32S*",$username);
                   11987: 	
                   11988: 	my $nameseed=numval($username) << 21;
                   11989: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   11990: 	my $courseseed=unpack("%32S*",$courseid);
                   11991: 	
                   11992: 	my $num1=$symbchck+$symbseed+$namechck;
                   11993: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11994: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11995: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 11996: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 11997: 	return "$num1,$num2";
1.155     albertel 11998:     }
1.366     albertel 11999: }
                   12000: 
1.443     albertel 12001: sub rndseed_64bit2 {
                   12002:     my ($symb,$courseid,$domain,$username)=@_;
                   12003:     {
                   12004: 	use integer;
                   12005: 	# strings need to be an even # of cahracters long, it it is odd the
                   12006:         # last characters gets thrown away
                   12007: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12008: 	my $symbseed=numval($symb) << 10;
                   12009: 	my $namechck=unpack("%32S*",$username.' ');
                   12010: 	
                   12011: 	my $nameseed=numval($username) << 21;
1.501     albertel 12012: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12013: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12014: 	
                   12015: 	my $num1=$symbchck+$symbseed+$namechck;
                   12016: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12017: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12018: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 12019: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 12020: 	return "$num1,$num2";
                   12021:     }
                   12022: }
                   12023: 
                   12024: sub rndseed_64bit3 {
                   12025:     my ($symb,$courseid,$domain,$username)=@_;
                   12026:     {
                   12027: 	use integer;
                   12028: 	# strings need to be an even # of cahracters long, it it is odd the
                   12029:         # last characters gets thrown away
                   12030: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12031: 	my $symbseed=numval2($symb) << 10;
                   12032: 	my $namechck=unpack("%32S*",$username.' ');
                   12033: 	
                   12034: 	my $nameseed=numval2($username) << 21;
1.443     albertel 12035: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12036: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12037: 	
                   12038: 	my $num1=$symbchck+$symbseed+$namechck;
                   12039: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12040: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12041: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 12042: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12043: 	
1.503     albertel 12044: 	return "$num1:$num2";
1.443     albertel 12045:     }
                   12046: }
                   12047: 
1.575     albertel 12048: sub rndseed_64bit4 {
                   12049:     my ($symb,$courseid,$domain,$username)=@_;
                   12050:     {
                   12051: 	use integer;
                   12052: 	# strings need to be an even # of cahracters long, it it is odd the
                   12053:         # last characters gets thrown away
                   12054: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12055: 	my $symbseed=numval3($symb) << 10;
                   12056: 	my $namechck=unpack("%32S*",$username.' ');
                   12057: 	
                   12058: 	my $nameseed=numval3($username) << 21;
                   12059: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12060: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12061: 	
                   12062: 	my $num1=$symbchck+$symbseed+$namechck;
                   12063: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12064: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12065: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 12066: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12067: 	
1.575     albertel 12068: 	return "$num1:$num2";
                   12069:     }
                   12070: }
                   12071: 
1.675     albertel 12072: sub rndseed_64bit5 {
                   12073:     my ($symb,$courseid,$domain,$username)=@_;
                   12074:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   12075:     return "$num1:$num2";
                   12076: }
                   12077: 
1.366     albertel 12078: sub rndseed_CODE_64bit {
                   12079:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 12080:     {
1.366     albertel 12081: 	use integer;
1.443     albertel 12082: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 12083: 	my $symbseed=numval2($symb);
1.491     albertel 12084: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12085: 	my $CODEseed=numval(&getCODE());
1.443     albertel 12086: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 12087: 	my $num1=$symbseed+$CODEchck;
                   12088: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12089: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12090: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 12091: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12092: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 12093: 	return "$num1:$num2";
1.366     albertel 12094:     }
                   12095: }
                   12096: 
1.575     albertel 12097: sub rndseed_CODE_64bit4 {
                   12098:     my ($symb,$courseid,$domain,$username)=@_;
                   12099:     {
                   12100: 	use integer;
                   12101: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   12102: 	my $symbseed=numval3($symb);
                   12103: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12104: 	my $CODEseed=numval3(&getCODE());
                   12105: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12106: 	my $num1=$symbseed+$CODEchck;
                   12107: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12108: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12109: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 12110: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12111: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   12112: 	return "$num1:$num2";
                   12113:     }
                   12114: }
                   12115: 
1.675     albertel 12116: sub rndseed_CODE_64bit5 {
                   12117:     my ($symb,$courseid,$domain,$username)=@_;
                   12118:     my $code = &getCODE();
                   12119:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   12120:     return "$num1:$num2";
                   12121: }
                   12122: 
1.366     albertel 12123: sub setup_random_from_rndseed {
                   12124:     my ($rndseed)=@_;
1.503     albertel 12125:     if ($rndseed =~/([,:])/) {
1.1172.2.51  raeburn  12126: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   12127:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   12128:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   12129:         } else {
                   12130:             &Math::Random::random_set_seed($num1,$num2);
                   12131:         }
1.366     albertel 12132:     } else {
                   12133: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 12134:     }
1.36      albertel 12135: }
                   12136: 
1.474     albertel 12137: sub latest_receipt_algorithm_id {
1.835     albertel 12138:     return 'receipt3';
1.474     albertel 12139: }
                   12140: 
1.480     www      12141: sub recunique {
                   12142:     my $fucourseid=shift;
                   12143:     my $unique;
1.835     albertel 12144:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   12145: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12146: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      12147:     } else {
                   12148: 	$unique=$perlvar{'lonReceipt'};
                   12149:     }
                   12150:     return unpack("%32C*",$unique);
                   12151: }
                   12152: 
                   12153: sub recprefix {
                   12154:     my $fucourseid=shift;
                   12155:     my $prefix;
1.835     albertel 12156:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   12157: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12158: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      12159:     } else {
                   12160: 	$prefix=$perlvar{'lonHostID'};
                   12161:     }
                   12162:     return unpack("%32C*",$prefix);
                   12163: }
                   12164: 
1.76      www      12165: sub ireceipt {
1.474     albertel 12166:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 12167: 
                   12168:     my $return =&recprefix($fucourseid).'-';
                   12169: 
                   12170:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   12171: 	$env{'request.state'} eq 'construct') {
                   12172: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   12173: 	return $return;
                   12174:     }
                   12175: 
1.76      www      12176:     my $cuname=unpack("%32C*",$funame);
                   12177:     my $cudom=unpack("%32C*",$fudom);
                   12178:     my $cucourseid=unpack("%32C*",$fucourseid);
                   12179:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      12180:     my $cunique=&recunique($fucourseid);
1.474     albertel 12181:     my $cpart=unpack("%32S*",$part);
1.835     albertel 12182:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   12183: 
1.790     albertel 12184: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 12185: 			       
                   12186: 	$return.= ($cunique%$cuname+
                   12187: 		   $cunique%$cudom+
                   12188: 		   $cusymb%$cuname+
                   12189: 		   $cusymb%$cudom+
                   12190: 		   $cucourseid%$cuname+
                   12191: 		   $cucourseid%$cudom+
                   12192: 		   $cpart%$cuname+
                   12193: 		   $cpart%$cudom);
                   12194:     } else {
                   12195: 	$return.= ($cunique%$cuname+
                   12196: 		   $cunique%$cudom+
                   12197: 		   $cusymb%$cuname+
                   12198: 		   $cusymb%$cudom+
                   12199: 		   $cucourseid%$cuname+
                   12200: 		   $cucourseid%$cudom);
                   12201:     }
                   12202:     return $return;
1.76      www      12203: }
                   12204: 
                   12205: sub receipt {
1.474     albertel 12206:     my ($part)=@_;
1.790     albertel 12207:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 12208:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      12209: }
1.260     ng       12210: 
1.790     albertel 12211: sub whichuser {
                   12212:     my ($passedsymb)=@_;
                   12213:     my ($symb,$courseid,$domain,$name,$publicuser);
                   12214:     if (defined($env{'form.grade_symb'})) {
                   12215: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   12216: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   12217: 	if (!$allowed &&
                   12218: 	    exists($env{'request.course.sec'}) &&
                   12219: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   12220: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   12221: 			      '/'.$env{'request.course.sec'});
                   12222: 	}
                   12223: 	if ($allowed) {
                   12224: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   12225: 	    $courseid=$tmp_courseid;
                   12226: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   12227: 	    ($name)=&get_env_multiple('form.grade_username');
                   12228: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   12229: 	}
                   12230:     }
                   12231:     if (!$passedsymb) {
                   12232: 	$symb=&symbread();
                   12233:     } else {
                   12234: 	$symb=$passedsymb;
                   12235:     }
                   12236:     $courseid=$env{'request.course.id'};
                   12237:     $domain=$env{'user.domain'};
                   12238:     $name=$env{'user.name'};
                   12239:     if ($name eq 'public' && $domain eq 'public') {
                   12240: 	if (!defined($env{'form.username'})) {
                   12241: 	    $env{'form.username'}.=time.rand(10000000);
                   12242: 	}
                   12243: 	$name.=$env{'form.username'};
                   12244:     }
                   12245:     return ($symb,$courseid,$domain,$name,$publicuser);
                   12246: 
                   12247: }
                   12248: 
1.36      albertel 12249: # ------------------------------------------------------------ Serves up a file
1.472     albertel 12250: # returns either the contents of the file or 
                   12251: # -1 if the file doesn't exist
1.481     raeburn  12252: #
                   12253: # if the target is a file that was uploaded via DOCS, 
                   12254: # a check will be made to see if a current copy exists on the local server,
                   12255: # if it does this will be served, otherwise a copy will be retrieved from
                   12256: # the home server for the course and stored in /home/httpd/html/userfiles on
                   12257: # the local server.   
1.472     albertel 12258: 
1.36      albertel 12259: sub getfile {
1.538     albertel 12260:     my ($file) = @_;
1.609     banghart 12261:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 12262:     &repcopy($file);
                   12263:     return &readfile($file);
                   12264: }
                   12265: 
                   12266: sub repcopy_userfile {
                   12267:     my ($file)=@_;
1.1142    raeburn  12268:     my $londocroot = $perlvar{'lonDocRoot'};
                   12269:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  12270:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 12271:     my ($cdom,$cnum,$filename) = 
1.811     albertel 12272: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 12273:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   12274:     if (-e "$file") {
1.828     www      12275: # we already have a local copy, check it out
1.538     albertel 12276: 	my @fileinfo = stat($file);
1.828     www      12277: 	my $rtncode;
                   12278: 	my $info;
1.538     albertel 12279: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 12280: 	if ($lwpresp ne 'ok') {
1.828     www      12281: # there is no such file anymore, even though we had a local copy
1.482     albertel 12282: 	    if ($rtncode eq '404') {
1.538     albertel 12283: 		unlink($file);
1.482     albertel 12284: 	    }
                   12285: 	    return -1;
                   12286: 	}
                   12287: 	if ($info < $fileinfo[9]) {
1.828     www      12288: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  12289: 	    return 'ok';
1.828     www      12290: 	} else {
                   12291: # the file is outdated, get rid of it
                   12292: 	    unlink($file);
1.482     albertel 12293: 	}
1.828     www      12294:     }
                   12295: # one way or the other, at this point, we don't have the file
                   12296: # construct the correct path for the file
                   12297:     my @parts = ($cdom,$cnum); 
                   12298:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   12299: 	push @parts, split(/\//,$1);
                   12300:     }
                   12301:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   12302:     foreach my $part (@parts) {
                   12303: 	$path .= '/'.$part;
                   12304: 	if (!-e $path) {
                   12305: 	    mkdir($path,0770);
1.482     albertel 12306: 	}
                   12307:     }
1.828     www      12308: # now the path exists for sure
                   12309: # get a user agent
                   12310:     my $ua=new LWP::UserAgent;
                   12311:     my $transferfile=$file.'.in.transfer';
                   12312: # FIXME: this should flock
                   12313:     if (-e $transferfile) { return 'ok'; }
                   12314:     my $request;
                   12315:     $uri=~s/^\///;
1.980     raeburn  12316:     my $homeserver = &homeserver($cnum,$cdom);
                   12317:     my $protocol = $protocol{$homeserver};
                   12318:     $protocol = 'http' if ($protocol ne 'https');
                   12319:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      12320:     my $response=$ua->request($request,$transferfile);
                   12321: # did it work?
                   12322:     if ($response->is_error()) {
                   12323: 	unlink($transferfile);
                   12324: 	&logthis("Userfile repcopy failed for $uri");
                   12325: 	return -1;
                   12326:     }
                   12327: # worked, rename the transfer file
                   12328:     rename($transferfile,$file);
1.607     raeburn  12329:     return 'ok';
1.481     raeburn  12330: }
                   12331: 
1.517     albertel 12332: sub tokenwrapper {
                   12333:     my $uri=shift;
1.980     raeburn  12334:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 12335:     $uri=~s|^/||;
1.620     albertel 12336:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 12337:     my $token=$1;
1.552     albertel 12338:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   12339:     if ($udom && $uname && $file) {
                   12340: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  12341:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  12342:         my $homeserver = &homeserver($uname,$udom);
                   12343:         my $protocol = $protocol{$homeserver};
                   12344:         $protocol = 'http' if ($protocol ne 'https');
                   12345:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 12346:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   12347:                                '&tokenissued='.$perlvar{'lonHostID'};
                   12348:     } else {
                   12349:         return '/adm/notfound.html';
                   12350:     }
                   12351: }
                   12352: 
1.828     www      12353: # call with reqtype HEAD: get last modification time
                   12354: # call with reqtype GET: get the file contents
                   12355: # Do not call this with reqtype GET for large files! It loads everything into memory
                   12356: #
1.481     raeburn  12357: sub getuploaded {
                   12358:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   12359:     $uri=~s/^\///;
1.980     raeburn  12360:     my $homeserver = &homeserver($cnum,$cdom);
                   12361:     my $protocol = $protocol{$homeserver};
                   12362:     $protocol = 'http' if ($protocol ne 'https');
                   12363:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  12364:     my $ua=new LWP::UserAgent;
                   12365:     my $request=new HTTP::Request($reqtype,$uri);
                   12366:     my $response=$ua->request($request);
                   12367:     $$rtncode = $response->code;
1.482     albertel 12368:     if (! $response->is_success()) {
                   12369: 	return 'failed';
                   12370:     }      
                   12371:     if ($reqtype eq 'HEAD') {
1.486     www      12372: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 12373:     } elsif ($reqtype eq 'GET') {
                   12374: 	$$info = $response->content;
1.472     albertel 12375:     }
1.482     albertel 12376:     return 'ok';
1.36      albertel 12377: }
                   12378: 
1.481     raeburn  12379: sub readfile {
                   12380:     my $file = shift;
                   12381:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   12382:     my $fh;
                   12383:     open($fh,"<$file");
                   12384:     my $a='';
1.800     albertel 12385:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  12386:     return $a;
                   12387: }
                   12388: 
1.36      albertel 12389: sub filelocation {
1.590     banghart 12390:     my ($dir,$file) = @_;
                   12391:     my $location;
                   12392:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 12393: 
                   12394:     if ($file =~ m-^/adm/-) {
                   12395: 	$file=~s-^/adm/wrapper/-/-;
                   12396: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   12397:     }
1.882     albertel 12398: 
1.1139    www      12399:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  12400:         $location = $file;
1.609     banghart 12401:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 12402:         my ($udom,$uname,$filename)=
1.811     albertel 12403:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 12404:         my $home=&homeserver($uname,$udom);
                   12405:         my $is_me=0;
                   12406:         my @ids=&current_machine_ids();
                   12407:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   12408:         if ($is_me) {
1.1117    foxr     12409:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 12410:         } else {
                   12411:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   12412:   	      $udom.'/'.$uname.'/'.$filename;
                   12413:         }
1.882     albertel 12414:     } elsif ($file =~ m-^/adm/-) {
                   12415: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 12416:     } else {
                   12417:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      12418:         $file=~s:^/(res|priv)/:/:;
                   12419:         my $space=$1;
1.590     banghart 12420:         if ( !( $file =~ m:^/:) ) {
                   12421:             $location = $dir. '/'.$file;
                   12422:         } else {
1.1142    raeburn  12423:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 12424:         }
1.59      albertel 12425:     }
1.590     banghart 12426:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 12427:     while ($location=~m{/\.\./}) {
                   12428: 	if ($location =~ m{/[^/]+/\.\./}) {
                   12429: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   12430: 	} else {
                   12431: 	    $location=~ s{/\.\./}{/}g;
                   12432: 	}
                   12433:     } #remove dir/..
1.590     banghart 12434:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   12435:     return $location;
1.46      www      12436: }
1.36      albertel 12437: 
1.46      www      12438: sub hreflocation {
                   12439:     my ($dir,$file)=@_;
1.980     raeburn  12440:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 12441: 	$file=filelocation($dir,$file);
1.700     albertel 12442:     } elsif ($file=~m-^/adm/-) {
                   12443: 	$file=~s-^/adm/wrapper/-/-;
                   12444: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 12445:     }
                   12446:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   12447: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   12448:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  12449: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   12450: 	        {/uploaded/$1/$2/}x;
1.46      www      12451:     }
1.913     albertel 12452:     if ($file=~ m{^/userfiles/}) {
                   12453: 	$file =~ s{^/userfiles/}{/uploaded/};
                   12454:     }
1.462     albertel 12455:     return $file;
1.465     albertel 12456: }
                   12457: 
1.1139    www      12458: 
                   12459: 
                   12460: 
                   12461: 
1.465     albertel 12462: sub current_machine_domains {
1.853     albertel 12463:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   12464: }
                   12465: 
                   12466: sub machine_domains {
                   12467:     my ($hostname) = @_;
1.465     albertel 12468:     my @domains;
1.838     albertel 12469:     my %hostname = &all_hostnames();
1.465     albertel 12470:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  12471: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 12472: 	if ($hostname eq $name) {
1.844     albertel 12473: 	    push(@domains,&host_domain($id));
1.465     albertel 12474: 	}
                   12475:     }
                   12476:     return @domains;
                   12477: }
                   12478: 
                   12479: sub current_machine_ids {
1.853     albertel 12480:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   12481: }
                   12482: 
                   12483: sub machine_ids {
                   12484:     my ($hostname) = @_;
                   12485:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 12486:     my @ids;
1.888     albertel 12487:     my %name_to_host = &all_names();
1.889     albertel 12488:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   12489: 	return @{ $name_to_host{$hostname} };
                   12490:     }
                   12491:     return;
1.31      www      12492: }
                   12493: 
1.824     raeburn  12494: sub additional_machine_domains {
                   12495:     my @domains;
                   12496:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   12497:     while( my $line = <$fh>) {
                   12498:         $line =~ s/\s//g;
                   12499:         push(@domains,$line);
                   12500:     }
                   12501:     return @domains;
                   12502: }
                   12503: 
                   12504: sub default_login_domain {
                   12505:     my $domain = $perlvar{'lonDefDomain'};
                   12506:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   12507:     foreach my $posdom (&current_machine_domains(),
                   12508:                         &additional_machine_domains()) {
                   12509:         if (lc($posdom) eq lc($testdomain)) {
                   12510:             $domain=$posdom;
                   12511:             last;
                   12512:         }
                   12513:     }
                   12514:     return $domain;
                   12515: }
                   12516: 
1.31      www      12517: # ------------------------------------------------------------- Declutters URLs
                   12518: 
                   12519: sub declutter {
                   12520:     my $thisfn=shift;
1.569     albertel 12521:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49  raeburn  12522:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   12523:         $thisfn=~s{^/home/httpd/html}{};
                   12524:     }
1.31      www      12525:     $thisfn=~s/^\///;
1.697     albertel 12526:     $thisfn=~s|^adm/wrapper/||;
                   12527:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      12528:     $thisfn=~s/^res\///;
1.1172    bisitz   12529:     $thisfn=~s/^priv\///;
1.1032    raeburn  12530:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   12531:         $thisfn=~s/\?.+$//;
                   12532:     }
1.268     www      12533:     return $thisfn;
                   12534: }
                   12535: 
                   12536: # ------------------------------------------------------------- Clutter up URLs
                   12537: 
                   12538: sub clutter {
                   12539:     my $thisfn='/'.&declutter(shift);
1.887     albertel 12540:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 12541: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      12542:        $thisfn='/res'.$thisfn; 
                   12543:     }
1.1031    raeburn  12544:     if ($thisfn !~m|^/adm|) {
                   12545: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 12546: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 12547: 	} else {
                   12548: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   12549: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 12550: 	    if ($embstyle eq 'ssi'
                   12551: 		|| ($embstyle eq 'hdn')
                   12552: 		|| ($embstyle eq 'rat')
                   12553: 		|| ($embstyle eq 'prv')
                   12554: 		|| ($embstyle eq 'ign')) {
                   12555: 		#do nothing with these
                   12556: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 12557: 		|| ($embstyle eq 'emb')
                   12558: 		|| ($embstyle eq 'wrp')) {
                   12559: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 12560: 	    } elsif ($embstyle eq 'unk'
                   12561: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 12562: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 12563: 	    } else {
1.718     www      12564: #		&logthis("Got a blank emb style");
1.695     albertel 12565: 	    }
1.694     albertel 12566: 	}
1.1172.2.93.4  2(raebur 12567:7):     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
                   12568:7):         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 12569:     }
1.31      www      12570:     return $thisfn;
1.12      www      12571: }
                   12572: 
1.787     albertel 12573: sub clutter_with_no_wrapper {
                   12574:     my $uri = &clutter(shift);
                   12575:     if ($uri =~ m-^/adm/-) {
                   12576: 	$uri =~ s-^/adm/wrapper/-/-;
                   12577: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   12578:     }
                   12579:     return $uri;
                   12580: }
                   12581: 
1.557     albertel 12582: sub freeze_escape {
                   12583:     my ($value)=@_;
                   12584:     if (ref($value)) {
                   12585: 	$value=&nfreeze($value);
                   12586: 	return '__FROZEN__'.&escape($value);
                   12587:     }
                   12588:     return &escape($value);
                   12589: }
                   12590: 
1.11      www      12591: 
1.557     albertel 12592: sub thaw_unescape {
                   12593:     my ($value)=@_;
                   12594:     if ($value =~ /^__FROZEN__/) {
                   12595: 	substr($value,0,10,undef);
                   12596: 	$value=&unescape($value);
                   12597: 	return &thaw($value);
                   12598:     }
                   12599:     return &unescape($value);
                   12600: }
                   12601: 
1.436     albertel 12602: sub correct_line_ends {
                   12603:     my ($result)=@_;
                   12604:     $$result =~s/\r\n/\n/mg;
                   12605:     $$result =~s/\r/\n/mg;
1.415     albertel 12606: }
1.1       albertel 12607: # ================================================================ Main Program
                   12608: 
1.184     www      12609: sub goodbye {
1.204     albertel 12610:    &logthis("Starting Shut down");
1.443     albertel 12611: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 12612:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 12613: #converted
1.599     albertel 12614: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 12615:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   12616: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   12617: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 12618: #1.1 only
1.870     albertel 12619: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   12620: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   12621: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   12622: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   12623:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 12624:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   12625:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      12626:    &flushcourselogs();
                   12627:    &logthis("Shutting down");
                   12628: }
                   12629: 
1.852     albertel 12630: sub get_dns {
1.1172.2.17  raeburn  12631:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 12632:     if (!$ignore_cache) {
                   12633: 	my ($content,$cached)=
                   12634: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   12635: 	if ($cached) {
1.1172.2.17  raeburn  12636: 	    &$func($content,$hashref);
1.869     albertel 12637: 	    return;
                   12638: 	}
                   12639:     }
                   12640: 
                   12641:     my %alldns;
1.852     albertel 12642:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   12643:     foreach my $dns (<$config>) {
                   12644: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  12645:         my $line = $1;
                   12646:         my ($host,$protocol) = split(/:/,$line);
                   12647:         if ($protocol ne 'https') {
                   12648:             $protocol = 'http';
                   12649:         }
                   12650: 	$alldns{$host} = $protocol;
1.869     albertel 12651:     }
                   12652:     while (%alldns) {
1.1172.2.52  raeburn  12653: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 12654: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  12655:         $ua->timeout(30);
1.979     raeburn  12656: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 12657: 	my $response=$ua->request($request);
1.979     raeburn  12658:         delete($alldns{$dns});
1.852     albertel 12659: 	next if ($response->is_error());
                   12660: 	my @content = split("\n",$response->content);
1.1172.2.17  raeburn  12661:         unless ($nocache) {
1.1172.2.23  raeburn  12662: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  12663:         }
                   12664: 	&$func(\@content,$hashref);
1.869     albertel 12665: 	return;
1.852     albertel 12666:     }
                   12667:     close($config);
1.871     albertel 12668:     my $which = (split('/',$url))[3];
                   12669:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   12670:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 12671:     my @content = <$config>;
1.1172.2.17  raeburn  12672:     &$func(\@content,$hashref);
                   12673:     return;
                   12674: }
                   12675: 
                   12676: # ------------------------------------------------------Get DNS checksums file
                   12677: sub parse_dns_checksums_tab {
                   12678:     my ($lines,$hashref) = @_;
1.1172.2.53  raeburn  12679:     my $lonhost = $perlvar{'lonHostID'};
                   12680:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17  raeburn  12681:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53  raeburn  12682:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   12683:     my $webconfdir = '/etc/httpd/conf';
                   12684:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   12685:         $webconfdir = '/etc/apache2';
                   12686:     } elsif ($distro =~ /^sles(\d+)$/) {
                   12687:         if ($1 >= 10) {
                   12688:             $webconfdir = '/etc/apache2';
                   12689:         }
                   12690:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   12691:         if ($1 >= 10.0) {
                   12692:             $webconfdir = '/etc/apache2';
                   12693:         }
                   12694:     }
1.1172.2.17  raeburn  12695:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   12696:     my (%chksum,%revnum);
                   12697:     if (ref($lines) eq 'ARRAY') {
                   12698:         chomp(@{$lines});
1.1172.2.34  raeburn  12699:         my $version = shift(@{$lines});
                   12700:         if ($version eq $release) {
1.1172.2.17  raeburn  12701:             foreach my $line (@{$lines}) {
1.1172.2.34  raeburn  12702:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53  raeburn  12703:                 if ($file =~ m{^/etc/httpd/conf}) {
                   12704:                     if ($webconfdir eq '/etc/apache2') {
                   12705:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   12706:                     }
                   12707:                 }
1.1172.2.34  raeburn  12708:                 $chksum{$file} = $shasum;
                   12709:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  12710:             }
                   12711:             if (ref($hashref) eq 'HASH') {
                   12712:                 %{$hashref} = (
                   12713:                                 sums     => \%chksum,
                   12714:                                 versions => \%revnum,
                   12715:                               );
                   12716:             }
                   12717:         }
                   12718:     }
1.869     albertel 12719:     return;
1.852     albertel 12720: }
1.1172.2.17  raeburn  12721: 
                   12722: sub fetch_dns_checksums {
                   12723:     my %checksums;
1.1172.2.34  raeburn  12724:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48  raeburn  12725:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34  raeburn  12726:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   12727:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  12728:              \%checksums);
                   12729:     return \%checksums;
                   12730: }
                   12731: 
1.327     albertel 12732: # ------------------------------------------------------------ Read domain file
                   12733: {
1.852     albertel 12734:     my $loaded;
1.846     albertel 12735:     my %domain;
                   12736: 
1.852     albertel 12737:     sub parse_domain_tab {
                   12738: 	my ($lines) = @_;
                   12739: 	foreach my $line (@$lines) {
                   12740: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      12741: 
1.846     albertel 12742: 	    chomp($line);
1.852     albertel 12743: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 12744: 	    my %this_domain;
                   12745: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   12746: 			       'lang_def', 'city', 'longi', 'lati',
                   12747: 			       'primary') {
                   12748: 		$this_domain{$field} = shift(@elements);
                   12749: 	    }
                   12750: 	    $domain{$name} = \%this_domain;
1.852     albertel 12751: 	}
                   12752:     }
1.864     albertel 12753: 
                   12754:     sub reset_domain_info {
                   12755: 	undef($loaded);
                   12756: 	undef(%domain);
                   12757:     }
                   12758: 
1.852     albertel 12759:     sub load_domain_tab {
1.1172.2.70  raeburn  12760: 	my ($ignore_cache,$nocache) = @_;
                   12761: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 12762: 	my $fh;
                   12763: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   12764: 	    my @lines = <$fh>;
                   12765: 	    &parse_domain_tab(\@lines);
1.448     albertel 12766: 	}
1.852     albertel 12767: 	close($fh);
                   12768: 	$loaded = 1;
1.327     albertel 12769:     }
1.846     albertel 12770: 
                   12771:     sub domain {
1.852     albertel 12772: 	&load_domain_tab() if (!$loaded);
                   12773: 
1.846     albertel 12774: 	my ($name,$what) = @_;
                   12775: 	return if ( !exists($domain{$name}) );
                   12776: 
                   12777: 	if (!$what) {
                   12778: 	    return $domain{$name}{'description'};
                   12779: 	}
                   12780: 	return $domain{$name}{$what};
                   12781:     }
1.974     raeburn  12782: 
                   12783:     sub domain_info {
                   12784:         &load_domain_tab() if (!$loaded);
                   12785:         return %domain;
                   12786:     }
                   12787: 
1.327     albertel 12788: }
                   12789: 
                   12790: 
1.1       albertel 12791: # ------------------------------------------------------------- Read hosts file
                   12792: {
1.838     albertel 12793:     my %hostname;
1.844     albertel 12794:     my %hostdom;
1.845     albertel 12795:     my %libserv;
1.852     albertel 12796:     my $loaded;
1.888     albertel 12797:     my %name_to_host;
1.1074    raeburn  12798:     my %internetdom;
1.1107    raeburn  12799:     my %LC_dns_serv;
1.852     albertel 12800: 
                   12801:     sub parse_hosts_tab {
                   12802: 	my ($file) = @_;
                   12803: 	foreach my $configline (@$file) {
                   12804: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  12805:             chomp($configline);
                   12806: 	    if ($configline =~ /^\^/) {
                   12807:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   12808:                     $LC_dns_serv{$1} = 1;
                   12809:                 }
                   12810:                 next;
                   12811:             }
1.1074    raeburn  12812: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 12813: 	    $name=~s/\s//g;
                   12814: 	    if ($id && $domain && $role && $name) {
                   12815: 		$hostname{$id}=$name;
1.888     albertel 12816: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 12817: 		$hostdom{$id}=$domain;
                   12818: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  12819:                 if (defined($protocol)) {
                   12820:                     if ($protocol eq 'https') {
                   12821:                         $protocol{$id} = $protocol;
                   12822:                     } else {
                   12823:                         $protocol{$id} = 'http'; 
                   12824:                     }
1.968     raeburn  12825:                 } else {
1.969     raeburn  12826:                     $protocol{$id} = 'http';
1.968     raeburn  12827:                 }
1.1074    raeburn  12828:                 if (defined($intdom)) {
                   12829:                     $internetdom{$id} = $intdom;
                   12830:                 }
1.852     albertel 12831: 	    }
                   12832: 	}
                   12833:     }
1.864     albertel 12834:     
                   12835:     sub reset_hosts_info {
1.897     albertel 12836: 	&purge_remembered();
1.864     albertel 12837: 	&reset_domain_info();
                   12838: 	&reset_hosts_ip_info();
1.892     albertel 12839: 	undef(%name_to_host);
1.864     albertel 12840: 	undef(%hostname);
                   12841: 	undef(%hostdom);
                   12842: 	undef(%libserv);
                   12843: 	undef($loaded);
                   12844:     }
1.1       albertel 12845: 
1.852     albertel 12846:     sub load_hosts_tab {
1.1172.2.70  raeburn  12847: 	my ($ignore_cache,$nocache) = @_;
                   12848: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.852     albertel 12849: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   12850: 	my @config = <$config>;
                   12851: 	&parse_hosts_tab(\@config);
                   12852: 	close($config);
                   12853: 	$loaded=1;
1.1       albertel 12854:     }
1.852     albertel 12855: 
1.838     albertel 12856:     sub hostname {
1.852     albertel 12857: 	&load_hosts_tab() if (!$loaded);
                   12858: 
1.838     albertel 12859: 	my ($lonid) = @_;
                   12860: 	return $hostname{$lonid};
                   12861:     }
1.845     albertel 12862: 
1.838     albertel 12863:     sub all_hostnames {
1.852     albertel 12864: 	&load_hosts_tab() if (!$loaded);
                   12865: 
1.838     albertel 12866: 	return %hostname;
                   12867:     }
1.845     albertel 12868: 
1.888     albertel 12869:     sub all_names {
1.1172.2.70  raeburn  12870:         my ($ignore_cache,$nocache) = @_;
                   12871: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 12872: 
                   12873: 	return %name_to_host;
                   12874:     }
                   12875: 
1.974     raeburn  12876:     sub all_host_domain {
                   12877:         &load_hosts_tab() if (!$loaded);
                   12878:         return %hostdom;
                   12879:     }
                   12880: 
1.845     albertel 12881:     sub is_library {
1.852     albertel 12882: 	&load_hosts_tab() if (!$loaded);
                   12883: 
1.845     albertel 12884: 	return exists($libserv{$_[0]});
                   12885:     }
                   12886: 
                   12887:     sub all_library {
1.852     albertel 12888: 	&load_hosts_tab() if (!$loaded);
                   12889: 
1.845     albertel 12890: 	return %libserv;
                   12891:     }
                   12892: 
1.1062    droeschl 12893:     sub unique_library {
                   12894: 	#2x reverse removes all hostnames that appear more than once
                   12895:         my %unique = reverse &all_library();
                   12896:         return reverse %unique;
                   12897:     }
                   12898: 
1.841     albertel 12899:     sub get_servers {
1.852     albertel 12900: 	&load_hosts_tab() if (!$loaded);
                   12901: 
1.841     albertel 12902: 	my ($domain,$type) = @_;
                   12903: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   12904: 	                                          : %hostname;
                   12905: 	my %result;
1.842     albertel 12906: 	if (ref($domain) eq 'ARRAY') {
                   12907: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 12908: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 12909: 		    $result{$host} = $hostname;
                   12910: 		}
                   12911: 	    }
                   12912: 	} else {
                   12913: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   12914: 		if ($hostdom{$host} eq $domain) {
                   12915: 		    $result{$host} = $hostname;
                   12916: 		}
1.841     albertel 12917: 	    }
                   12918: 	}
                   12919: 	return %result;
                   12920:     }
1.845     albertel 12921: 
1.1062    droeschl 12922:     sub get_unique_servers {
                   12923:         my %unique = reverse &get_servers(@_);
                   12924: 	return reverse %unique;
                   12925:     }
                   12926: 
1.844     albertel 12927:     sub host_domain {
1.852     albertel 12928: 	&load_hosts_tab() if (!$loaded);
                   12929: 
1.844     albertel 12930: 	my ($lonid) = @_;
                   12931: 	return $hostdom{$lonid};
                   12932:     }
                   12933: 
1.841     albertel 12934:     sub all_domains {
1.852     albertel 12935: 	&load_hosts_tab() if (!$loaded);
                   12936: 
1.841     albertel 12937: 	my %seen;
                   12938: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   12939: 	return @uniq;
                   12940:     }
1.1074    raeburn  12941: 
                   12942:     sub internet_dom {
                   12943:         &load_hosts_tab() if (!$loaded);
                   12944: 
                   12945:         my ($lonid) = @_;
                   12946:         return $internetdom{$lonid};
                   12947:     }
1.1107    raeburn  12948: 
                   12949:     sub is_LC_dns {
                   12950:         &load_hosts_tab() if (!$loaded);
                   12951: 
                   12952:         my ($hostname) = @_;
                   12953:         return exists($LC_dns_serv{$hostname});
                   12954:     }
                   12955: 
1.1       albertel 12956: }
                   12957: 
1.847     albertel 12958: { 
                   12959:     my %iphost;
1.856     albertel 12960:     my %name_to_ip;
                   12961:     my %lonid_to_ip;
1.869     albertel 12962: 
1.847     albertel 12963:     sub get_hosts_from_ip {
                   12964: 	my ($ip) = @_;
                   12965: 	my %iphosts = &get_iphost();
                   12966: 	if (ref($iphosts{$ip})) {
                   12967: 	    return @{$iphosts{$ip}};
                   12968: 	}
                   12969: 	return;
1.839     albertel 12970:     }
1.864     albertel 12971:     
                   12972:     sub reset_hosts_ip_info {
                   12973: 	undef(%iphost);
                   12974: 	undef(%name_to_ip);
                   12975: 	undef(%lonid_to_ip);
                   12976:     }
1.856     albertel 12977: 
                   12978:     sub get_host_ip {
                   12979: 	my ($lonid) = @_;
                   12980: 	if (exists($lonid_to_ip{$lonid})) {
                   12981: 	    return $lonid_to_ip{$lonid};
                   12982: 	}
                   12983: 	my $name=&hostname($lonid);
                   12984:    	my $ip = gethostbyname($name);
                   12985: 	return if (!$ip || length($ip) ne 4);
                   12986: 	$ip=inet_ntoa($ip);
                   12987: 	$name_to_ip{$name}   = $ip;
                   12988: 	$lonid_to_ip{$lonid} = $ip;
                   12989: 	return $ip;
                   12990:     }
1.847     albertel 12991:     
                   12992:     sub get_iphost {
1.1172.2.70  raeburn  12993: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 12994: 
1.869     albertel 12995: 	if (!$ignore_cache) {
                   12996: 	    if (%iphost) {
                   12997: 		return %iphost;
                   12998: 	    }
                   12999: 	    my ($ip_info,$cached)=
                   13000: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   13001: 	    if ($cached) {
                   13002: 		%iphost      = %{$ip_info->[0]};
                   13003: 		%name_to_ip  = %{$ip_info->[1]};
                   13004: 		%lonid_to_ip = %{$ip_info->[2]};
                   13005: 		return %iphost;
                   13006: 	    }
                   13007: 	}
1.894     albertel 13008: 
                   13009: 	# get yesterday's info for fallback
                   13010: 	my %old_name_to_ip;
                   13011: 	my ($ip_info,$cached)=
                   13012: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   13013: 	if ($cached) {
                   13014: 	    %old_name_to_ip = %{$ip_info->[1]};
                   13015: 	}
                   13016: 
1.1172.2.70  raeburn  13017: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 13018: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 13019: 	    my $ip;
                   13020: 	    if (!exists($name_to_ip{$name})) {
                   13021: 		$ip = gethostbyname($name);
                   13022: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 13023: 		    if (defined($old_name_to_ip{$name})) {
                   13024: 			$ip = $old_name_to_ip{$name};
                   13025: 			&logthis("Can't find $name defaulting to old $ip");
                   13026: 		    } else {
                   13027: 			&logthis("Name $name no IP found");
                   13028: 			next;
                   13029: 		    }
                   13030: 		} else {
                   13031: 		    $ip=inet_ntoa($ip);
1.847     albertel 13032: 		}
                   13033: 		$name_to_ip{$name} = $ip;
                   13034: 	    } else {
                   13035: 		$ip = $name_to_ip{$name};
1.653     albertel 13036: 	    }
1.888     albertel 13037: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   13038: 		$lonid_to_ip{$id} = $ip;
                   13039: 	    }
                   13040: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 13041: 	}
1.1172.2.70  raeburn  13042:         unless ($nocache) {
                   13043: 	    &do_cache_new('iphost','iphost',
                   13044: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   13045: 		          48*60*60);
                   13046:         }
1.869     albertel 13047: 
1.847     albertel 13048: 	return %iphost;
1.598     albertel 13049:     }
                   13050: 
1.992     raeburn  13051:     #
                   13052:     #  Given a DNS returns the loncapa host name for that DNS 
                   13053:     # 
                   13054:     sub host_from_dns {
                   13055:         my ($dns) = @_;
                   13056:         my @hosts;
                   13057:         my $ip;
                   13058: 
1.993     raeburn  13059:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  13060:             $ip = $name_to_ip{$dns};
                   13061:         }
                   13062:         if (!$ip) {
                   13063:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   13064:             if (length($ip) == 4) { 
                   13065: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   13066:             }
                   13067:         }
                   13068:         if ($ip) {
                   13069: 	    @hosts = get_hosts_from_ip($ip);
                   13070: 	    return $hosts[0];
                   13071:         }
                   13072:         return undef;
1.986     foxr     13073:     }
1.992     raeburn  13074: 
1.1074    raeburn  13075:     sub get_internet_names {
                   13076:         my ($lonid) = @_;
                   13077:         return if ($lonid eq '');
                   13078:         my ($idnref,$cached)=
                   13079:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   13080:         if ($cached) {
                   13081:             return $idnref;
                   13082:         }
                   13083:         my $ip = &get_host_ip($lonid);
                   13084:         my @hosts = &get_hosts_from_ip($ip);
                   13085:         my %iphost = &get_iphost();
                   13086:         my (@idns,%seen);
                   13087:         foreach my $id (@hosts) {
                   13088:             my $dom = &host_domain($id);
                   13089:             my $prim_id = &domain($dom,'primary');
                   13090:             my $prim_ip = &get_host_ip($prim_id);
                   13091:             next if ($seen{$prim_ip});
                   13092:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   13093:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   13094:                     my $intdom = &internet_dom($id);
                   13095:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   13096:                         push(@idns,$intdom);
                   13097:                     }
                   13098:                 }
                   13099:             }
                   13100:             $seen{$prim_ip} = 1;
                   13101:         }
1.1172.2.23  raeburn  13102:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  13103:     }
                   13104: 
1.986     foxr     13105: }
                   13106: 
1.1079    raeburn  13107: sub all_loncaparevs {
1.1172.2.39  raeburn  13108:     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  13109: }
                   13110: 
1.1172.2.27  raeburn  13111: # ------------------------------------------------------- Read loncaparev table
                   13112: {
                   13113:     sub load_loncaparevs {
                   13114:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   13115:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   13116:                 while (my $configline=<$config>) {
                   13117:                     chomp($configline);
                   13118:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   13119:                     $loncaparevs{$hostid}=$loncaparev;
                   13120:                 }
                   13121:                 close($config);
                   13122:             }
                   13123:         }
                   13124:     }
                   13125: }
                   13126: 
                   13127: # ----------------------------------------------------- Read serverhostID table
                   13128: {
                   13129:     sub load_serverhomeIDs {
                   13130:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   13131:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   13132:                 while (my $configline=<$config>) {
                   13133:                     chomp($configline);
                   13134:                     my ($name,$id)=split(/:/,$configline);
                   13135:                     $serverhomeIDs{$name}=$id;
                   13136:                 }
                   13137:                 close($config);
                   13138:             }
                   13139:         }
                   13140:     }
                   13141: }
                   13142: 
                   13143: 
1.862     albertel 13144: BEGIN {
                   13145: 
                   13146: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   13147:     unless ($readit) {
                   13148: {
                   13149:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   13150:     %perlvar = (%perlvar,%{$configvars});
                   13151: }
                   13152: 
                   13153: 
1.1       albertel 13154: # ------------------------------------------------------ Read spare server file
                   13155: {
1.448     albertel 13156:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 13157: 
                   13158:     while (my $configline=<$config>) {
                   13159:        chomp($configline);
1.284     matthew  13160:        if ($configline) {
1.784     albertel 13161: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 13162: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 13163: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 13164:        }
                   13165:     }
1.448     albertel 13166:     close($config);
1.1       albertel 13167: }
1.11      www      13168: # ------------------------------------------------------------ Read permissions
                   13169: {
1.448     albertel 13170:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      13171: 
                   13172:     while (my $configline=<$config>) {
1.448     albertel 13173: 	chomp($configline);
                   13174: 	if ($configline) {
                   13175: 	    my ($role,$perm)=split(/ /,$configline);
                   13176: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   13177: 	}
1.11      www      13178:     }
1.448     albertel 13179:     close($config);
1.11      www      13180: }
                   13181: 
                   13182: # -------------------------------------------- Read plain texts for permissions
                   13183: {
1.448     albertel 13184:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      13185: 
                   13186:     while (my $configline=<$config>) {
1.448     albertel 13187: 	chomp($configline);
                   13188: 	if ($configline) {
1.742     raeburn  13189: 	    my ($short,@plain)=split(/:/,$configline);
                   13190:             %{$prp{$short}} = ();
                   13191: 	    if (@plain > 0) {
                   13192:                 $prp{$short}{'std'} = $plain[0];
                   13193:                 for (my $i=1; $i<@plain; $i++) {
                   13194:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   13195:                 }
                   13196:             }
1.448     albertel 13197: 	}
1.135     www      13198:     }
1.448     albertel 13199:     close($config);
1.135     www      13200: }
                   13201: 
                   13202: # ---------------------------------------------------------- Read package table
                   13203: {
1.448     albertel 13204:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      13205: 
                   13206:     while (my $configline=<$config>) {
1.483     albertel 13207: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 13208: 	chomp($configline);
                   13209: 	my ($short,$plain)=split(/:/,$configline);
                   13210: 	my ($pack,$name)=split(/\&/,$short);
                   13211: 	if ($plain ne '') {
                   13212: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   13213: 	    $packagetab{$short}=$plain; 
                   13214: 	}
1.11      www      13215:     }
1.448     albertel 13216:     close($config);
1.329     matthew  13217: }
                   13218: 
1.1172.2.27  raeburn  13219: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  13220: 
1.1172.2.27  raeburn  13221: &load_loncaparevs();
                   13222: 
                   13223: # ------------------------------------------------------- Read serverhostID table
                   13224: 
                   13225: &load_serverhomeIDs();
1.1074    raeburn  13226: 
1.1172.2.27  raeburn  13227: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  13228: {
                   13229:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   13230:     if (-e $file) {
                   13231:         my $parser = HTML::LCParser->new($file);
                   13232:         while (my $token = $parser->get_token()) {
                   13233:             if ($token->[0] eq 'S') {
                   13234:                 my $item = $token->[1];
                   13235:                 my $name = $token->[2]{'name'};
                   13236:                 my $value = $token->[2]{'value'};
                   13237:                 if ($item ne '' && $name ne '' && $value ne '') {
                   13238:                     my $release = $parser->get_text();
                   13239:                     $release =~ s/(^\s*|\s*$ )//gx;
                   13240:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   13241:                 }
                   13242:             }
                   13243:         }
                   13244:     }
1.1073    raeburn  13245: }
                   13246: 
1.1138    raeburn  13247: # ---------------------------------------------------------- Read managers table
                   13248: {
                   13249:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   13250:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   13251:             while (my $configline=<$config>) {
                   13252:                 chomp($configline);
                   13253:                 next if ($configline =~ /^\#/);
                   13254:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   13255:                     $managerstab{$configline} = 1;
                   13256:                 }
                   13257:             }
                   13258:             close($config);
                   13259:         }
                   13260:     }
                   13261: }
                   13262: 
1.329     matthew  13263: # ------------- set up temporary directory
                   13264: {
1.1117    foxr     13265:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  13266: 
1.11      www      13267: }
                   13268: 
1.794     albertel 13269: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   13270: 				'compress_threshold'=> 20_000,
                   13271:  			        });
1.185     www      13272: 
1.281     www      13273: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      13274: $dumpcount=0;
1.958     www      13275: $locknum=0;
1.22      www      13276: 
1.163     harris41 13277: &logtouch();
1.672     albertel 13278: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      13279: $readit=1;
1.564     albertel 13280:     {
                   13281: 	use integer;
                   13282: 	my $test=(2**32)+1;
1.568     albertel 13283: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 13284: 	&logthis(" Detected 64bit platform ($_64bit)");
                   13285:     }
1.195     www      13286: }
1.1       albertel 13287: }
1.179     www      13288: 
1.1       albertel 13289: 1;
1.191     harris41 13290: __END__
                   13291: 
1.243     albertel 13292: =pod
                   13293: 
1.191     harris41 13294: =head1 NAME
                   13295: 
1.243     albertel 13296: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 13297: 
                   13298: =head1 SYNOPSIS
                   13299: 
1.243     albertel 13300: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 13301: 
                   13302:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   13303: 
1.243     albertel 13304: Common parameters:
                   13305: 
                   13306: =over 4
                   13307: 
                   13308: =item *
                   13309: 
                   13310: $uname : an internal username (if $cname expecting a course Id specifically)
                   13311: 
                   13312: =item *
                   13313: 
                   13314: $udom : a domain (if $cdom expecting a course's domain specifically)
                   13315: 
                   13316: =item *
                   13317: 
                   13318: $symb : a resource instance identifier
                   13319: 
                   13320: =item *
                   13321: 
                   13322: $namespace : the name of a .db file that contains the data needed or
                   13323: being set.
                   13324: 
                   13325: =back
                   13326: 
1.394     bowersj2 13327: =head1 OVERVIEW
1.191     harris41 13328: 
1.394     bowersj2 13329: lonnet provides subroutines which interact with the
                   13330: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   13331: about classes, users, and resources.
1.243     albertel 13332: 
                   13333: For many of these objects you can also use this to store data about
                   13334: them or modify them in various ways.
1.191     harris41 13335: 
1.394     bowersj2 13336: =head2 Symbs
1.191     harris41 13337: 
1.394     bowersj2 13338: To identify a specific instance of a resource, LON-CAPA uses symbols
                   13339: or "symbs"X<symb>. These identifiers are built from the URL of the
                   13340: map, the resource number of the resource in the map, and the URL of
                   13341: the resource itself. The latter is somewhat redundant, but might help
                   13342: if maps change.
                   13343: 
                   13344: An example is
                   13345: 
                   13346:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   13347: 
                   13348: The respective map entry is
                   13349: 
                   13350:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   13351:   title="Problem 2">
                   13352:  </resource>
                   13353: 
                   13354: Symbs are used by the random number generator, as well as to store and
                   13355: restore data specific to a certain instance of for example a problem.
                   13356: 
                   13357: =head2 Storing And Retrieving Data
                   13358: 
                   13359: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   13360: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   13361: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   13362: is is the non-critical message twin of cstore. These functions are for
                   13363: handlers to store a perl hash to a user's permanent data space in an
                   13364: easy manner, and to retrieve it again on another call. It is expected
                   13365: that a handler would use this once at the beginning to retrieve data,
                   13366: and then again once at the end to send only the new data back.
                   13367: 
                   13368: The data is stored in the user's data directory on the user's
                   13369: homeserver under the ID of the course.
                   13370: 
                   13371: The hash that is returned by restore will have all of the previous
                   13372: value for all of the elements of the hash.
                   13373: 
                   13374: Example:
                   13375: 
                   13376:  #creating a hash
                   13377:  my %hash;
                   13378:  $hash{'foo'}='bar';
                   13379: 
                   13380:  #storing it
                   13381:  &Apache::lonnet::cstore(\%hash);
                   13382: 
                   13383:  #changing a value
                   13384:  $hash{'foo'}='notbar';
                   13385: 
                   13386:  #adding a new value
                   13387:  $hash{'bar'}='foo';
                   13388:  &Apache::lonnet::cstore(\%hash);
                   13389: 
                   13390:  #retrieving the hash
                   13391:  my %history=&Apache::lonnet::restore();
                   13392: 
                   13393:  #print the hash
                   13394:  foreach my $key (sort(keys(%history))) {
                   13395:    print("\%history{$key} = $history{$key}");
                   13396:  }
                   13397: 
                   13398: Will print out:
1.191     harris41 13399: 
1.394     bowersj2 13400:  %history{1:foo} = bar
                   13401:  %history{1:keys} = foo:timestamp
                   13402:  %history{1:timestamp} = 990455579
                   13403:  %history{2:bar} = foo
                   13404:  %history{2:foo} = notbar
                   13405:  %history{2:keys} = foo:bar:timestamp
                   13406:  %history{2:timestamp} = 990455580
                   13407:  %history{bar} = foo
                   13408:  %history{foo} = notbar
                   13409:  %history{timestamp} = 990455580
                   13410:  %history{version} = 2
                   13411: 
                   13412: Note that the special hash entries C<keys>, C<version> and
                   13413: C<timestamp> were added to the hash. C<version> will be equal to the
                   13414: total number of versions of the data that have been stored. The
                   13415: C<timestamp> attribute will be the UNIX time the hash was
                   13416: stored. C<keys> is available in every historical section to list which
                   13417: keys were added or changed at a specific historical revision of a
                   13418: hash.
                   13419: 
                   13420: B<Warning>: do not store the hash that restore returns directly. This
                   13421: will cause a mess since it will restore the historical keys as if the
                   13422: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 13423: 
1.394     bowersj2 13424: Calling convention:
1.191     harris41 13425: 
1.1172.2.27  raeburn  13426:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64  raeburn  13427:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 13428: 
1.394     bowersj2 13429: For more detailed information, see lonnet specific documentation.
1.191     harris41 13430: 
1.394     bowersj2 13431: =head1 RETURN MESSAGES
1.191     harris41 13432: 
1.394     bowersj2 13433: =over 4
1.191     harris41 13434: 
1.394     bowersj2 13435: =item * B<con_lost>: unable to contact remote host
1.191     harris41 13436: 
1.394     bowersj2 13437: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   13438: when the connection is brought back up
1.191     harris41 13439: 
1.394     bowersj2 13440: =item * B<con_failed>: unable to contact remote host and unable to save message
                   13441: for later delivery
1.191     harris41 13442: 
1.967     bisitz   13443: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 13444: 
1.394     bowersj2 13445: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 13446: that was requested
1.191     harris41 13447: 
1.243     albertel 13448: =back
1.191     harris41 13449: 
1.243     albertel 13450: =head1 PUBLIC SUBROUTINES
1.191     harris41 13451: 
1.243     albertel 13452: =head2 Session Environment Functions
1.191     harris41 13453: 
1.243     albertel 13454: =over 4
1.191     harris41 13455: 
1.394     bowersj2 13456: =item * 
                   13457: X<appenv()>
1.949     raeburn  13458: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 13459: the user envirnoment file, and will be restored for each access this
1.620     albertel 13460: user makes during this session, also modifies the %env for the current
1.949     raeburn  13461: process. Optional rolesarrayref - if defined contains a reference to an array
                   13462: of roles which are exempt from the restriction on modifying user.role entries 
                   13463: in the user's environment.db and in %env.    
1.191     harris41 13464: 
                   13465: =item *
1.394     bowersj2 13466: X<delenv()>
1.987     raeburn  13467: B<delenv($delthis,$regexp)>: removes all items from the session
                   13468: environment file that begin with $delthis. If the 
                   13469: optional second arg - $regexp - is true, $delthis is treated as a 
                   13470: regular expression, otherwise \Q$delthis\E is used. 
                   13471: The values are also deleted from the current processes %env.
1.191     harris41 13472: 
1.795     albertel 13473: =item * get_env_multiple($name) 
                   13474: 
                   13475: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   13476: values may be defined and end up as an array ref.
                   13477: 
                   13478: returns an array of values
                   13479: 
1.243     albertel 13480: =back
                   13481: 
                   13482: =head2 User Information
1.191     harris41 13483: 
1.243     albertel 13484: =over 4
1.191     harris41 13485: 
                   13486: =item *
1.394     bowersj2 13487: X<queryauthenticate()>
                   13488: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 13489: authentication scheme
                   13490: 
                   13491: =item *
1.394     bowersj2 13492: X<authenticate()>
1.1073    raeburn  13493: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 13494: authenticate user from domain's lib servers (first use the current
                   13495: one). C<$upass> should be the users password.
1.1073    raeburn  13496: $checkdefauth is optional (value is 1 if a check should be made to
                   13497:    authenticate user using default authentication method, and allow
                   13498:    account creation if username does not have account in the domain).
                   13499: $clientcancheckhost is optional (value is 1 if checking whether the
                   13500:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 13501: 
                   13502: =item *
1.394     bowersj2 13503: X<homeserver()>
                   13504: B<homeserver($uname,$udom)>: find the server which has
                   13505: the user's directory and files (there must be only one), this caches
                   13506: the answer, and also caches if there is a borken connection.
1.191     harris41 13507: 
                   13508: =item *
1.394     bowersj2 13509: X<idget()>
                   13510: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   13511: (IDs are a unique resource in a domain, there must be only 1 ID per
                   13512: username, and only 1 username per ID in a specific domain) (returns
                   13513: hash: id=>name,id=>name)
1.191     harris41 13514: 
                   13515: =item *
1.394     bowersj2 13516: X<idrget()>
                   13517: B<idrget($udom,@unames)>: find the IDs behind a list of
                   13518: usernames (returns hash: name=>id,name=>id)
1.191     harris41 13519: 
                   13520: =item *
1.394     bowersj2 13521: X<idput()>
                   13522: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 13523: 
                   13524: =item *
1.394     bowersj2 13525: X<rolesinit()>
1.1169    droeschl 13526: B<rolesinit($udom,$username)>: get user privileges.
                   13527: returns user role, first access and timer interval hashes
1.243     albertel 13528: 
                   13529: =item *
1.1171    droeschl 13530: X<privileged()>
                   13531: B<privileged($username,$domain)>: returns a true if user has a
                   13532: privileged and active role (i.e. su or dc), false otherwise.
                   13533: 
                   13534: =item *
1.551     albertel 13535: X<getsection()>
                   13536: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 13537: course $cname, return section name/number or '' for "not in course"
                   13538: and '-1' for "no section"
                   13539: 
                   13540: =item *
1.394     bowersj2 13541: X<userenvironment()>
                   13542: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 13543: passed in @what from the requested user's environment, returns a hash
                   13544: 
1.858     raeburn  13545: =item * 
                   13546: X<userlog_query()>
1.859     albertel 13547: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   13548: activity.log file. %filters defines filters applied when parsing the
                   13549: log file. These can be start or end timestamps, or the type of action
                   13550: - log to look for Login or Logout events, check for Checkin or
                   13551: Checkout, role for role selection. The response is in the form
                   13552: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   13553: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  13554: 
1.243     albertel 13555: =back
                   13556: 
                   13557: =head2 User Roles
                   13558: 
                   13559: =over 4
                   13560: 
                   13561: =item *
                   13562: 
1.1172.2.65  raeburn  13563: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   13564: returns codes for allowed actions.
                   13565: 
                   13566: The first argument is required, all others are optional.
                   13567: 
                   13568: $priv is the privilege being checked.
                   13569: $uri contains additional information about what is being checked for access (e.g.,
                   13570: URL, course ID etc.).
                   13571: $symb is the unique resource instance identifier in a course; if needed,
                   13572: but not provided, it will be retrieved via a call to &symbread().
                   13573: $role is the role for which a priv is being checked (only used if priv is evb).
                   13574: $clientip is the user's IP address (only used when checking for access to portfolio
                   13575: files).
                   13576: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
                   13577: prevents recursive calls to &allowed.
                   13578: 
1.243     albertel 13579:  F: full access
                   13580:  U,I,K: authentication modes (cxx only)
                   13581:  '': forbidden
                   13582:  1: user needs to choose course
                   13583:  2: browse allowed
1.766     albertel 13584:  A: passphrase authentication needed
1.1172.2.65  raeburn  13585:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 13586: 
                   13587: =item *
                   13588: 
1.1172.2.13  raeburn  13589: constructaccess($url,$setpriv) : check for access to construction space URL
                   13590: 
                   13591: See if the owner domain and name in the URL match those in the
                   13592: expected environment.  If so, return three element list
                   13593: ($ownername,$ownerdomain,$ownerhome).
                   13594: 
                   13595: Otherwise return the null string.
                   13596: 
                   13597: If second argument 'setpriv' is true, it assigns the privileges,
                   13598: and returns the same three element list, unless the owner has
                   13599: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   13600: in which case the null string is returned.
                   13601: 
                   13602: =item *
                   13603: 
1.1172.2.84  raeburn  13604: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   13605: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   13606: for system, domain, and course level. $uname and $udom are optional (current
                   13607: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 13608: 
                   13609: =item *
                   13610: 
1.988     raeburn  13611: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   13612: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  13613: $type is Course (default) or Community.
1.988     raeburn  13614: If $forcedefault evaluates to true, text returned will be default 
                   13615: text for $type. Otherwise, if this is a course, the text returned 
                   13616: will be a custom name for the role (if defined in the course's 
                   13617: environment).  If no custom name is defined the default is returned.
                   13618:    
1.832     raeburn  13619: =item *
                   13620: 
1.1172.2.23  raeburn  13621: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  13622: All arguments are optional. Returns a hash of a roles, either for
                   13623: co-author/assistant author roles for a user's Construction Space
1.906     albertel 13624: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  13625: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   13626: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   13627: For each key, value is set to colon-separated start and end times for
                   13628: the role.  If no username and domain are specified, will default to
1.934     raeburn  13629: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  13630: of role statuses (active, future or previous), roles 
                   13631: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   13632: to restrict the list of roles reported. If no array ref is 
                   13633: provided for types, will default to return only active roles.
1.834     albertel 13634: 
1.1172.2.13  raeburn  13635: =item *
                   13636: 
                   13637: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   13638: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   13639: 
                   13640: Additional optional arguments are: $type (if role checking is to be restricted
                   13641: to certain user status types -- previous (expired roles), active (currently
                   13642: available roles) or future (roles available in the future), and
                   13643: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  13644: have active Domain Coordinator role in course's domain or in additional
                   13645: domains (specified in 'Domains to check for privileged users' in course
                   13646: environment -- set via:  Course Settings -> Classlists and staff listing).
                   13647: 
                   13648: =item *
                   13649: 
                   13650: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   13651: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   13652: $possdomains and $possroles are optional array refs -- to domains to check and
                   13653: roles to check.  If $possdomains is not specified, a dump will be done of the
                   13654: users' roles.db to check for a dc or su role in any domain. This can be
                   13655: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   13656: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   13657: this then allows &privileged_by_domain() to be used, which caches the identity
                   13658: of privileged users, eliminating the need for repeated calls to &dump().
                   13659: 
                   13660: =item *
                   13661: 
                   13662: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   13663: where the outer hash keys are domains specified in the $possdomains array ref,
                   13664: next inner hash keys are privileged roles specified in the $roles array ref,
                   13665: and the innermost hash contains key = value pairs for username:domain = end:start
                   13666: for active or future "privileged" users with that role in that domain. To avoid
                   13667: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   13668: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  13669: 
1.243     albertel 13670: =back
                   13671: 
                   13672: =head2 User Modification
                   13673: 
                   13674: =over 4
                   13675: 
                   13676: =item *
                   13677: 
1.957     raeburn  13678: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 13679: user for the level given by URL.  Optional start and end dates (leave empty
                   13680: string or zero for "no date")
1.191     harris41 13681: 
                   13682: =item *
                   13683: 
1.243     albertel 13684: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   13685: change a users, password, possible return values are: ok,
                   13686: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   13687: refused
1.191     harris41 13688: 
                   13689: =item *
                   13690: 
1.243     albertel 13691: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 13692: 
                   13693: =item *
                   13694: 
1.1058    raeburn  13695: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   13696:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   13697: 
                   13698: will update user information (firstname,middlename,lastname,generation,
                   13699: permanentemail), and if forceid is true, student/employee ID also.
                   13700: A user's institutional affiliation(s) can also be updated.
                   13701: User information fields will not be overwritten with empty entries 
                   13702: unless the field is included in the $candelete array reference.
                   13703: This array is included when a single user is modified via "Manage Users",
                   13704: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 13705: 
                   13706: =item *
                   13707: 
1.286     matthew  13708: modifystudent
                   13709: 
1.957     raeburn  13710: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  13711: The course id is resolved based on the current user's environment.  
                   13712: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  13713: associated with a course.
                   13714: 
1.297     matthew  13715: This call is essentially a wrapper for lonnet::modifyuser and
                   13716: lonnet::modify_student_enrollment
1.286     matthew  13717: 
                   13718: Inputs: 
                   13719: 
                   13720: =over 4
                   13721: 
1.957     raeburn  13722: =item B<$udom> Student's loncapa domain
1.286     matthew  13723: 
1.957     raeburn  13724: =item B<$uname> Student's loncapa login name
1.286     matthew  13725: 
1.964     bisitz   13726: =item B<$uid> Student/Employee ID
1.286     matthew  13727: 
1.957     raeburn  13728: =item B<$umode> Student's authentication mode
1.286     matthew  13729: 
1.957     raeburn  13730: =item B<$upass> Student's password
1.286     matthew  13731: 
1.957     raeburn  13732: =item B<$first> Student's first name
1.286     matthew  13733: 
1.957     raeburn  13734: =item B<$middle> Student's middle name
1.286     matthew  13735: 
1.957     raeburn  13736: =item B<$last> Student's last name
1.286     matthew  13737: 
1.957     raeburn  13738: =item B<$gene> Student's generation
1.286     matthew  13739: 
1.957     raeburn  13740: =item B<$usec> Student's section in course
1.286     matthew  13741: 
                   13742: =item B<$end> Unix time of the roles expiration
                   13743: 
                   13744: =item B<$start> Unix time of the roles start date
                   13745: 
                   13746: =item B<$forceid> If defined, allow $uid to be changed
                   13747: 
                   13748: =item B<$desiredhome> server to use as home server for student
                   13749: 
1.957     raeburn  13750: =item B<$email> Student's permanent e-mail address
                   13751: 
                   13752: =item B<$type> Type of enrollment (auto or manual)
                   13753: 
1.963     raeburn  13754: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   13755: 
                   13756: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  13757: 
1.963     raeburn  13758: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  13759: 
1.963     raeburn  13760: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  13761: 
1.1172.2.19  raeburn  13762: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   13763: 
                   13764: =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  13765: 
1.286     matthew  13766: =back
1.297     matthew  13767: 
                   13768: =item *
                   13769: 
                   13770: modify_student_enrollment
                   13771: 
1.1172.2.31  raeburn  13772: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  13773: 'role.request.course' must be defined for this function to proceed.
                   13774: 
                   13775: Inputs:
                   13776: 
                   13777: =over 4
                   13778: 
1.1172.2.31  raeburn  13779: =item $udom, student's domain
1.297     matthew  13780: 
1.1172.2.31  raeburn  13781: =item $uname, student's name
1.297     matthew  13782: 
1.1172.2.31  raeburn  13783: =item $uid, student's user id
1.297     matthew  13784: 
1.1172.2.31  raeburn  13785: =item $first, student's first name
1.297     matthew  13786: 
                   13787: =item $middle
                   13788: 
                   13789: =item $last
                   13790: 
                   13791: =item $gene
                   13792: 
                   13793: =item $usec
                   13794: 
                   13795: =item $end
                   13796: 
                   13797: =item $start
                   13798: 
1.957     raeburn  13799: =item $type
                   13800: 
                   13801: =item $locktype
                   13802: 
                   13803: =item $cid
                   13804: 
                   13805: =item $selfenroll
                   13806: 
                   13807: =item $context
                   13808: 
1.1172.2.19  raeburn  13809: =item $credits, number of credits student will earn from this class
                   13810: 
1.1172.2.76  raeburn  13811: =item $instsec, institutional course section code for student
                   13812: 
1.297     matthew  13813: =back
                   13814: 
1.191     harris41 13815: 
                   13816: =item *
                   13817: 
1.243     albertel 13818: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   13819: custom role; give a custom role to a user for the level given by URL.  Specify
                   13820: name and domain of role author, and role name
1.191     harris41 13821: 
                   13822: =item *
                   13823: 
1.243     albertel 13824: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 13825: 
                   13826: =item *
                   13827: 
1.243     albertel 13828: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   13829: 
                   13830: =back
                   13831: 
                   13832: =head2 Course Infomation
                   13833: 
                   13834: =over 4
1.191     harris41 13835: 
                   13836: =item *
                   13837: 
1.1118    foxr     13838: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 13839: specified course id, including all environment settings for the
                   13840: course, the description of the course will be in the hash under the
                   13841: key 'description'
1.191     harris41 13842: 
1.1118    foxr     13843: $options is an optional parameter that if supplied is a hash reference that controls
                   13844: what how this function works.  It has the following key/values:
                   13845: 
                   13846: =over 4
                   13847: 
                   13848: =item freshen_cache
                   13849: 
                   13850: If defined, and the environment cache for the course is valid, it is 
                   13851: returned in the returned hash.
                   13852: 
                   13853: =item one_time
                   13854: 
                   13855: If defined, the last cache time is set to _now_
                   13856: 
                   13857: =item user
                   13858: 
                   13859: If defined, the supplied username is used instead of the current user.
                   13860: 
                   13861: 
                   13862: =back
                   13863: 
1.191     harris41 13864: =item *
                   13865: 
1.624     albertel 13866: resdata($name,$domain,$type,@which) : request for current parameter
                   13867: setting for a specific $type, where $type is either 'course' or 'user',
                   13868: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  13869: answers for 10 minutes.
1.243     albertel 13870: 
1.877     foxr     13871: =item *
                   13872: 
                   13873: get_courseresdata($courseid, $domain) : dump the entire course resource
                   13874: data base, returning a hash that is keyed by the resource name and has
                   13875: values that are the resource value.  I believe that the timestamps and
                   13876: versions are also returned.
                   13877: 
1.1172.2.31  raeburn  13878: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   13879: supplemental content area. This routine caches the number of files for
                   13880: 10 minutes.
                   13881: 
1.243     albertel 13882: =back
                   13883: 
                   13884: =head2 Course Modification
                   13885: 
                   13886: =over 4
1.191     harris41 13887: 
                   13888: =item *
                   13889: 
1.243     albertel 13890: writecoursepref($courseid,%prefs) : write preferences (environment
                   13891: database) for a course
1.191     harris41 13892: 
                   13893: =item *
                   13894: 
1.1011    raeburn  13895: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   13896: 
                   13897: =item *
                   13898: 
1.1038    raeburn  13899: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 13900: 
1.1167    droeschl 13901: =item *
                   13902: 
                   13903: is_course($courseid), is_course($cdom, $cnum)
                   13904: 
                   13905: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   13906: two component version $cdom, $cnum. It checks if the specified course exists.
                   13907: 
                   13908: Returns:
                   13909:     undef if the course doesn't exist, otherwise
                   13910:     in scalar context the combined courseid.
                   13911:     in list context the two components of the course identifier, domain and 
                   13912:     courseid.    
                   13913: 
1.243     albertel 13914: =back
                   13915: 
                   13916: =head2 Resource Subroutines
                   13917: 
                   13918: =over 4
1.191     harris41 13919: 
                   13920: =item *
                   13921: 
1.243     albertel 13922: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 13923: 
                   13924: =item *
                   13925: 
1.243     albertel 13926: repcopy($filename) : subscribes to the requested file, and attempts to
                   13927: replicate from the owning library server, Might return
1.607     raeburn  13928: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   13929: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 13930: resource. Expects the local filesystem pathname
                   13931: (/home/httpd/html/res/....)
                   13932: 
                   13933: =back
                   13934: 
                   13935: =head2 Resource Information
                   13936: 
                   13937: =over 4
1.191     harris41 13938: 
                   13939: =item *
                   13940: 
1.1172.2.28  raeburn  13941: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   13942: and returns the value of a variety of different possible values,
                   13943: $varname should be a request string, and the other parameters can be
                   13944: used to specify who and what one is asking about. Ordinarily, $cid 
                   13945: does not need to be specified, as it is retrived from 
                   13946: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   13947: within lonuserstate::loadmap() when initializing a course, before
                   13948: $env{'request.course.id'} has been set, so it needs to be provided
                   13949: in that one case.
1.243     albertel 13950: 
                   13951: Possible values for $varname are environment.lastname (or other item
                   13952: from the envirnment hash), user.name (or someother aspect about the
                   13953: user), resource.0.maxtries (or some other part and parameter of a
                   13954: resource)
1.204     albertel 13955: 
                   13956: =item *
                   13957: 
1.243     albertel 13958: directcondval($number) : get current value of a condition; reads from a state
                   13959: string
1.204     albertel 13960: 
                   13961: =item *
                   13962: 
1.243     albertel 13963: condval($condidx) : value of condition index based on state
1.204     albertel 13964: 
                   13965: =item *
                   13966: 
1.243     albertel 13967: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   13968: resource's metadata, $what should be either a specific key, or either
                   13969: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   13970: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   13971: 
                   13972: this function automatically caches all requests
1.191     harris41 13973: 
                   13974: =item *
                   13975: 
1.243     albertel 13976: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   13977: network of library servers; returns file handle of where SQL and regex results
                   13978: will be stored for query
1.191     harris41 13979: 
                   13980: =item *
                   13981: 
1.1172.2.66  raeburn  13982: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
                   13983: return symbolic list entry (all arguments optional).
                   13984: 
                   13985: Args: filename is the filename (including path) for the file for which a symb
                   13986: is required; donotrecurse, if true will prevent calls to allowed() being made
                   13987: to check access status if more than one resource was found in the bighash
                   13988: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
                   13989: a randompick); ignorecachednull, if true will prevent a symb of '' being
                   13990: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   13991: cause possible symbs to be checked to determine if they are subject to content
                   13992: blocking, if so they will not be included as possible symbs; possibles is a
                   13993: ref to a hash, which, as a side effect, will be populated with all possible
                   13994: symbs (content blocking not tested).
                   13995: 
1.243     albertel 13996: returns the data handle
1.191     harris41 13997: 
                   13998: =item *
                   13999: 
1.1172.2.17  raeburn  14000: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  14001: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 14002: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  14003: on failure, user must be in a course, as it assumes the existence of
                   14004: the course initial hash, and uses $env('request.course.id'}.  The third
                   14005: arg is an optional reference to a scalar.  If this arg is passed in the
                   14006: call to symbverify, it will be set to 1 if the symb has been set to be 
                   14007: encrypted; otherwise it will be null.
1.243     albertel 14008: 
1.191     harris41 14009: =item *
                   14010: 
1.243     albertel 14011: symbclean($symb) : removes versions numbers from a symb, returns the
                   14012: cleaned symb
1.191     harris41 14013: 
                   14014: =item *
                   14015: 
1.243     albertel 14016: is_on_map($uri) : checks if the $uri is somewhere on the current
                   14017: course map, user must be in a course for it to work.
1.191     harris41 14018: 
                   14019: =item *
                   14020: 
1.243     albertel 14021: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 14022: 
                   14023: =item *
                   14024: 
1.243     albertel 14025: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   14026: a random seed, all arguments are optional, if they aren't sent it uses the
                   14027: environment to derive them. Note: if symb isn't sent and it can't get one
                   14028: from &symbread it will use the current time as its return value
1.191     harris41 14029: 
                   14030: =item *
                   14031: 
1.243     albertel 14032: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   14033: unfakeable, receipt
1.191     harris41 14034: 
                   14035: =item *
                   14036: 
1.620     albertel 14037: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 14038: 
                   14039: =item *
                   14040: 
1.243     albertel 14041: countacc($url) : count the number of accesses to a given URL
1.191     harris41 14042: 
                   14043: =item *
                   14044: 
1.243     albertel 14045: 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 14046: 
                   14047: =item *
                   14048: 
1.243     albertel 14049: 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 14050: 
                   14051: =item *
                   14052: 
1.243     albertel 14053: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 14054: 
                   14055: =item *
                   14056: 
1.243     albertel 14057: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   14058: forcing spreadsheet to reevaluate the resource scores next time.
                   14059: 
1.1172.2.13  raeburn  14060: =item *
                   14061: 
                   14062: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   14063: when viewing in course context.
                   14064: 
                   14065:  input: six args -- filename (decluttered), course number, course domain,
                   14066:                     url, symb (if registered) and group (if this is a
                   14067:                     group item -- e.g., bulletin board, group page etc.).
                   14068: 
                   14069:  output: array of five scalars --
                   14070:          $cfile -- url for file editing if editable on current server
                   14071:          $home -- homeserver of resource (i.e., for author if published,
                   14072:                                           or course if uploaded.).
                   14073:          $switchserver --  1 if server switch will be needed.
                   14074:          $forceedit -- 1 if icon/link should be to go to edit mode
                   14075:          $forceview -- 1 if icon/link should be to go to view mode
                   14076: 
                   14077: =item *
                   14078: 
                   14079: is_course_upload($file,$cnum,$cdom)
                   14080: 
                   14081: Used in course context to determine if current file was uploaded to
                   14082: the course (i.e., would be found in /userfiles/docs on the course's
                   14083: homeserver.
                   14084: 
                   14085:   input: 3 args -- filename (decluttered), course number and course domain.
                   14086:   output: boolean -- 1 if file was uploaded.
                   14087: 
1.243     albertel 14088: =back
                   14089: 
                   14090: =head2 Storing/Retreiving Data
                   14091: 
                   14092: =over 4
1.191     harris41 14093: 
                   14094: =item *
                   14095: 
1.1172.2.64  raeburn  14096: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
                   14097: permanently for this url; hashref needs to be given and should be a \%hashname;
                   14098: the remaining args aren't required and if they aren't passed or are '' they will
                   14099: be derived from the env (with the exception of $laststore, which is an
                   14100: optional arg used when a user's submission is stored in grading).
                   14101: $laststore is $version=$timestamp, where $version is the most recent version
                   14102: number retrieved for the corresponding $symb in the $namespace db file, and
                   14103: $timestamp is the timestamp for that transaction (UNIX time).
                   14104: $laststore is currently only passed when cstore() is called by
                   14105: structuretags::finalize_storage().
1.191     harris41 14106: 
                   14107: =item *
                   14108: 
1.1172.2.64  raeburn  14109: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
                   14110: but uses critical subroutine
1.191     harris41 14111: 
                   14112: =item *
                   14113: 
1.243     albertel 14114: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   14115: all args are optional
1.191     harris41 14116: 
                   14117: =item *
                   14118: 
1.717     albertel 14119: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   14120: dumps the complete (or key matching regexp) namespace into a hash
                   14121: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   14122: normally &store()ed into
                   14123: 
                   14124: $range should be either an integer '100' (give me the first 100
                   14125:                                            matching records)
                   14126:               or be  two integers sperated by a - with no spaces
                   14127:                  '30-50' (give me the 30th through the 50th matching
                   14128:                           records)
                   14129: 
                   14130: 
                   14131: =item *
                   14132: 
1.1172.2.59  raeburn  14133: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 14134: replaces a &store() version of data with a replacement set of data
                   14135: for a particular resource in a namespace passed in the $storehash hash 
1.1172.2.59  raeburn  14136: reference. If $tolog is true, the transaction is logged in the courselog
                   14137: with an action=PUTSTORE.
1.717     albertel 14138: 
                   14139: =item *
                   14140: 
1.243     albertel 14141: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   14142: works very similar to store/cstore, but all data is stored in a
                   14143: temporary location and can be reset using tmpreset, $storehash should
                   14144: be a hash reference, returns nothing on success
1.191     harris41 14145: 
                   14146: =item *
                   14147: 
1.243     albertel 14148: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   14149: similar to restore, but all data is stored in a temporary location and
                   14150: can be reset using tmpreset. Returns a hash of values on success,
                   14151: error string otherwise.
1.191     harris41 14152: 
                   14153: =item *
                   14154: 
1.243     albertel 14155: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   14156: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 14157: 
                   14158: =item *
                   14159: 
1.243     albertel 14160: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14161: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 14162: 
                   14163: =item *
                   14164: 
1.243     albertel 14165: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   14166: namesp ($udom and $uname are optional)
1.191     harris41 14167: 
                   14168: =item *
                   14169: 
1.702     albertel 14170: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 14171: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 14172: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  14173: 
1.702     albertel 14174: $range should be either an integer '100' (give me the first 100
                   14175:                                            matching records)
                   14176:               or be  two integers sperated by a - with no spaces
                   14177:                  '30-50' (give me the 30th through the 50th matching
                   14178:                           records)
1.449     matthew  14179: =item *
                   14180: 
                   14181: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   14182: $store can be a scalar, an array reference, or if the amount to be 
                   14183: incremented is > 1, a hash reference.
                   14184: 
                   14185: ($udom and $uname are optional)
1.191     harris41 14186: 
                   14187: =item *
                   14188: 
1.243     albertel 14189: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   14190: ($udom and $uname are optional)
1.191     harris41 14191: 
                   14192: =item *
                   14193: 
1.243     albertel 14194: cput($namespace,$storehash,$udom,$uname) : critical put
                   14195: ($udom and $uname are optional)
1.191     harris41 14196: 
                   14197: =item *
                   14198: 
1.748     albertel 14199: newput($namespace,$storehash,$udom,$uname) :
                   14200: 
                   14201: Attempts to store the items in the $storehash, but only if they don't
                   14202: currently exist, if this succeeds you can be certain that you have 
                   14203: successfully created a new key value pair in the $namespace db.
                   14204: 
                   14205: 
                   14206: Args:
                   14207:  $namespace: name of database to store values to
                   14208:  $storehash: hashref to store to the db
                   14209:  $udom: (optional) domain of user containing the db
                   14210:  $uname: (optional) name of user caontaining the db
                   14211: 
                   14212: Returns:
                   14213:  'ok' -> succeeded in storing all keys of $storehash
                   14214:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   14215:                         least <key> already existed in the db (other
                   14216:                         requested keys may also already exist)
1.967     bisitz   14217:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 14218:  'con_lost' -> unable to contact request server
                   14219:  'refused' -> action was not allowed by remote machine
                   14220: 
                   14221: 
                   14222: =item *
                   14223: 
1.243     albertel 14224: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14225: reference filled in from namesp (encrypts the return communication)
                   14226: ($udom and $uname are optional)
1.191     harris41 14227: 
                   14228: =item *
                   14229: 
1.243     albertel 14230: log($udom,$name,$home,$message) : write to permanent log for user; use
                   14231: critical subroutine
                   14232: 
1.806     raeburn  14233: =item *
                   14234: 
1.860     raeburn  14235: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   14236: array reference filled in from namespace found in domain level on either
                   14237: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  14238: 
                   14239: =item *
                   14240: 
1.860     raeburn  14241: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   14242: domain level either on specified domain server ($uhome) or primary domain 
                   14243: server ($udom and $uhome are optional)
1.806     raeburn  14244: 
1.943     raeburn  14245: =item * 
                   14246: 
1.1172.2.35  raeburn  14247: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
                   14248: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   14249: the target domain.
                   14250: 
                   14251: May also include additional key => value pairs for the following groups:
                   14252: 
                   14253: =over
                   14254: 
                   14255: =item
                   14256: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   14257: 
                   14258: =over
                   14259: 
                   14260: =item defaultquota, authorquota
                   14261: 
                   14262: =back
                   14263: 
                   14264: =item
                   14265: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   14266: portfolio for users).
                   14267: 
                   14268: =over
                   14269: 
                   14270: =item
                   14271: aboutme, blog, webdav, portfolio
                   14272: 
                   14273: =back
                   14274: 
                   14275: =item
                   14276: requestcourses: ability to request courses, and how requests are processed.
                   14277: 
                   14278: =over
                   14279: 
                   14280: =item
1.1172.2.37  raeburn  14281: official, unofficial, community, textbook
1.1172.2.35  raeburn  14282: 
                   14283: =back
                   14284: 
                   14285: =item
                   14286: inststatus: types of institutional affiliation, and order in which they are displayed.
                   14287: 
                   14288: =over
                   14289: 
                   14290: =item
1.1172.2.44  raeburn  14291: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35  raeburn  14292: 
                   14293: =back
                   14294: 
                   14295: =item
                   14296: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   14297: for course's uploaded content.
                   14298: 
                   14299: =over
                   14300: 
                   14301: =item
1.1172.2.68  raeburn  14302: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
                   14303: communityquota, textbookquota
1.1172.2.35  raeburn  14304: 
                   14305: =back
                   14306: 
                   14307: =item
                   14308: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   14309: on your servers.
                   14310: 
                   14311: =over
                   14312: 
                   14313: =item
                   14314: remotesessions, hostedsessions
                   14315: 
                   14316: =back
                   14317: 
                   14318: =back
                   14319: 
                   14320: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   14321: utility to create a configuration.db file on a domain's primary library server
                   14322: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   14323: -- corresponding values are authentication type (internal, krb4, krb5,
                   14324: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
                   14325: will be available. Values are retrieved from cache (if current), unless the
                   14326: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   14327: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   14328: 
                   14329: Typical usage:
1.943     raeburn  14330: 
1.1172.2.35  raeburn  14331: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  14332: 
1.243     albertel 14333: =back
                   14334: 
                   14335: =head2 Network Status Functions
                   14336: 
                   14337: =over 4
1.191     harris41 14338: 
                   14339: =item *
                   14340: 
1.1137    raeburn  14341: dirlist() : return directory list based on URI (first arg).
                   14342: 
                   14343: Inputs: 1 required, 5 optional.
                   14344: 
                   14345: =over
                   14346: 
                   14347: =item 
                   14348: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   14349: 
                   14350: =item
                   14351: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   14352: 
                   14353: =item
                   14354: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   14355: 
                   14356: =item
                   14357: $getpropath - boolean: 1 if prepend path using &propath(). 
                   14358: 
                   14359: =item
                   14360: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   14361: 
                   14362: =item 
                   14363: $alternateRoot - path to prepend in place of path from $uri.
                   14364: 
                   14365: =back
                   14366: 
                   14367: Returns: Array of up to two items.
                   14368: 
                   14369: =over
                   14370: 
                   14371: a reference to an array of files/subdirectories
                   14372: 
                   14373: =over
                   14374: 
                   14375: Each element in the array of files/subdirectories is a & separated list of
                   14376: item name and the result of running stat on the item.  If dirlist was requested
                   14377: for a file instead of a directory, the item name will be ''. For a directory 
                   14378: listing, if the item is a metadata file, the element will end &N&M 
                   14379: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   14380: default copyright set (1).  
                   14381: 
                   14382: =back
                   14383: 
                   14384: a scalar containing error condition (if encountered).
                   14385: 
                   14386: =over
                   14387: 
                   14388: =item 
                   14389: no_host (no homeserver identified for $username:$domain).
                   14390: 
                   14391: =item 
                   14392: no_such_host (server contacted for listing not identified as valid host).
                   14393: 
                   14394: =item 
                   14395: con_lost (connection to remote server failed).
                   14396: 
                   14397: =item 
                   14398: refused (invalid $username:$domain received on lond side).
                   14399: 
                   14400: =item 
                   14401: no_such_dir (directory at specified path on lond side does not exist). 
                   14402: 
                   14403: =item 
                   14404: empty (directory at specified path on lond side is empty).
                   14405: 
                   14406: =over
                   14407: 
                   14408: This is currently not encountered because the &ls3, &ls2, 
                   14409: &ls (_handler) routines on the lond side do not filter out
                   14410: . and .. from a directory listing. 
                   14411: 
                   14412: =back
                   14413: 
                   14414: =back
                   14415: 
                   14416: =back
1.191     harris41 14417: 
                   14418: =item *
                   14419: 
1.243     albertel 14420: spareserver() : find server with least workload from spare.tab
                   14421: 
1.986     foxr     14422: 
                   14423: =item *
                   14424: 
                   14425: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   14426: if there is no corresponding loncapa host.
                   14427: 
1.243     albertel 14428: =back
                   14429: 
1.986     foxr     14430: 
1.243     albertel 14431: =head2 Apache Request
                   14432: 
                   14433: =over 4
1.191     harris41 14434: 
                   14435: =item *
                   14436: 
1.243     albertel 14437: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   14438: localhost, posts hash
                   14439: 
                   14440: =back
                   14441: 
                   14442: =head2 Data to String to Data
                   14443: 
                   14444: =over 4
1.191     harris41 14445: 
                   14446: =item *
                   14447: 
1.243     albertel 14448: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   14449: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 14450: 
                   14451: =item *
                   14452: 
1.243     albertel 14453: hashref2str($hashref) : convert a hashref into a string complete with
                   14454: escaping and '=' and '&' separators, supports elements that are
                   14455: arrayrefs and hashrefs
1.191     harris41 14456: 
                   14457: =item *
                   14458: 
1.243     albertel 14459: arrayref2str($arrayref) : convert an arrayref into a string complete
                   14460: with escaping and '&' separators, supports elements that are arrayrefs
                   14461: and hashrefs
1.191     harris41 14462: 
                   14463: =item *
                   14464: 
1.243     albertel 14465: str2hash($string) : convert string to hash using unescaping and
                   14466: splitting on '=' and '&', supports elements that are arrayrefs and
                   14467: hashrefs
1.191     harris41 14468: 
                   14469: =item *
                   14470: 
1.243     albertel 14471: str2array($string) : convert string to hash using unescaping and
                   14472: splitting on '&', supports elements that are arrayrefs and hashrefs
                   14473: 
                   14474: =back
                   14475: 
                   14476: =head2 Logging Routines
                   14477: 
                   14478: 
                   14479: These routines allow one to make log messages in the lonnet.log and
                   14480: lonnet.perm logfiles.
1.191     harris41 14481: 
1.1119    foxr     14482: =over 4
                   14483: 
1.191     harris41 14484: =item *
                   14485: 
1.243     albertel 14486: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 14487: 
                   14488: =item *
                   14489: 
1.243     albertel 14490: logthis() : append message to the normal lonnet.log file, it gets
                   14491: preiodically rolled over and deleted.
1.191     harris41 14492: 
                   14493: =item *
                   14494: 
1.243     albertel 14495: logperm() : append a permanent message to lonnet.perm.log, this log
                   14496: file never gets deleted by any automated portion of the system, only
                   14497: messages of critical importance should go in here.
                   14498: 
1.1119    foxr     14499: 
1.243     albertel 14500: =back
                   14501: 
                   14502: =head2 General File Helper Routines
                   14503: 
                   14504: =over 4
1.191     harris41 14505: 
                   14506: =item *
                   14507: 
1.481     raeburn  14508: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   14509: (a) files in /uploaded
                   14510:   (i) If a local copy of the file exists - 
                   14511:       compares modification date of local copy with last-modified date for 
                   14512:       definitive version stored on home server for course. If local copy is 
                   14513:       stale, requests a new version from the home server and stores it. 
                   14514:       If the original has been removed from the home server, then local copy 
                   14515:       is unlinked.
                   14516:   (ii) If local copy does not exist -
                   14517:       requests the file from the home server and stores it. 
                   14518:   
                   14519:   If $caller is 'uploadrep':  
                   14520:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   14521:     for request for files originally uploaded via DOCS. 
                   14522:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   14523:   
                   14524:   Otherwise:
                   14525:      This indicates a call from the content generation phase of the request.
                   14526:      -  returns the entire contents of the file or -1.
                   14527:      
                   14528: (b) files in /res
                   14529:    - returns the entire contents of a file or -1; 
                   14530:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 14531: 
1.712     albertel 14532: 
                   14533: =item *
                   14534: 
                   14535: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   14536:                   reference
                   14537: 
                   14538: returns either a stat() list of data about the file or an empty list
                   14539: if the file doesn't exist or couldn't find out about it (connection
                   14540: problems or user unknown)
                   14541: 
1.191     harris41 14542: =item *
                   14543: 
1.243     albertel 14544: filelocation($dir,$file) : returns file system location of a file
                   14545: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   14546: directory that relative $file lookups are to looked in ($dir of /a/dir
                   14547: and a file of ../bob will become /a/bob)
1.191     harris41 14548: 
                   14549: =item *
                   14550: 
                   14551: hreflocation($dir,$file) : returns file system location or a URL; same as
                   14552: filelocation except for hrefs
                   14553: 
                   14554: =item *
                   14555: 
1.1172.2.49  raeburn  14556: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   14557: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 14558: 
1.243     albertel 14559: =back
                   14560: 
1.608     albertel 14561: =head2 Usererfile file routines (/uploaded*)
                   14562: 
                   14563: =over 4
                   14564: 
                   14565: =item *
                   14566: 
                   14567: userfileupload(): main rotine for putting a file in a user or course's
                   14568:                   filespace, arguments are,
                   14569: 
1.620     albertel 14570:  formname - required - this is the name of the element in $env where the
1.608     albertel 14571:            filename, and the contents of the file to create/modifed exist
1.620     albertel 14572:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   14573:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  14574:  context - if coursedoc, store the file in the course of the active role
                   14575:              of the current user; 
                   14576:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   14577:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 14578:  subdir - required - subdirectory to put the file in under ../userfiles/
                   14579:          if undefined, it will be placed in "unknown"
                   14580: 
                   14581:  (This routine calls clean_filename() to remove any dangerous
                   14582:  characters from the filename, and then calls finuserfileupload() to
                   14583:  complete the transaction)
                   14584: 
                   14585:  returns either the url of the uploaded file (/uploaded/....) if successful
                   14586:  and /adm/notfound.html if unsuccessful
                   14587: 
                   14588: =item *
                   14589: 
                   14590: clean_filename(): routine for cleaing a filename up for storage in
                   14591:                  userfile space, argument is:
                   14592: 
                   14593:  filename - proposed filename
                   14594: 
                   14595: returns: the new clean filename
                   14596: 
                   14597: =item *
                   14598: 
1.1090    raeburn  14599: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 14600: userspace, probably shouldn't be called directly
                   14601: 
                   14602:   docuname: username or courseid of destination for the file
                   14603:   docudom: domain of user/course of destination for the file
                   14604:   formname: same as for userfileupload()
1.1090    raeburn  14605:   fname: filename (including subdirectories) for the file
                   14606:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   14607:   allfiles: reference to hash used to store objects found by parser
                   14608:   codebase: reference to hash used for codebases of java objects found by parser
                   14609:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   14610:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   14611:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   14612:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   14613:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   14614:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  14615:   mimetype: reference to scalar to accommodate mime type determined
                   14616:             from File::MMagic if $parser = parse.
1.608     albertel 14617: 
                   14618:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  14619:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   14620:  was 'overwrite').
                   14621:  
1.608     albertel 14622: 
                   14623: =item *
                   14624: 
                   14625: renameuserfile(): renames an existing userfile to a new name
                   14626: 
                   14627:   Args:
                   14628:    docuname: username or courseid of destination for the file
                   14629:    docudom: domain of user/course of destination for the file
                   14630:    old: current file name (including any subdirs under userfiles)
                   14631:    new: desired file name (including any subdirs under userfiles)
                   14632: 
                   14633: =item *
                   14634: 
                   14635: mkdiruserfile(): creates a directory is a userfiles dir
                   14636: 
                   14637:   Args:
                   14638:    docuname: username or courseid of destination for the file
                   14639:    docudom: domain of user/course of destination for the file
                   14640:    dir: dir to create (including any subdirs under userfiles)
                   14641: 
                   14642: =item *
                   14643: 
                   14644: removeuserfile(): removes a file that exists in userfiles
                   14645: 
                   14646:   Args:
                   14647:    docuname: username or courseid of destination for the file
                   14648:    docudom: domain of user/course of destination for the file
                   14649:    fname: filname to delete (including any subdirs under userfiles)
                   14650: 
                   14651: =item *
                   14652: 
                   14653: removeuploadedurl(): convience function for removeuserfile()
                   14654: 
                   14655:   Args:
                   14656:    url:  a full /uploaded/... url to delete
                   14657: 
1.747     albertel 14658: =item * 
                   14659: 
                   14660: get_portfile_permissions():
                   14661:   Args:
                   14662:     domain: domain of user or course contain the portfolio files
                   14663:     user: name of user or num of course contain the portfolio files
                   14664:   Returns:
                   14665:     hashref of a dump of the proper file_permissions.db
                   14666:    
                   14667: 
                   14668: =item * 
                   14669: 
                   14670: get_access_controls():
                   14671: 
                   14672: Args:
                   14673:   current_permissions: the hash ref returned from get_portfile_permissions()
                   14674:   group: (optional) the group you want the files associated with
                   14675:   file: (optional) the file you want access info on
                   14676: 
                   14677: Returns:
1.749     raeburn  14678:     a hash (keys are file names) of hashes containing
                   14679:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   14680:         values are XML containing access control settings (see below) 
1.747     albertel 14681: 
                   14682: Internal notes:
                   14683: 
1.749     raeburn  14684:  access controls are stored in file_permissions.db as key=value pairs.
                   14685:     key -> path to file/file_name\0uniqueID:scope_end_start
                   14686:         where scope -> public,guest,course,group,domains or users.
                   14687:               end -> UNIX time for end of access (0 -> no end date)
                   14688:               start -> UNIX time for start of access
                   14689: 
                   14690:     value -> XML description of access control
                   14691:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   14692:             <start></start>
                   14693:             <end></end>
                   14694: 
                   14695:             <password></password>  for scope type = guest
                   14696: 
                   14697:             <domain></domain>     for scope type = course or group
                   14698:             <number></number>
                   14699:             <roles id="">
                   14700:              <role></role>
                   14701:              <access></access>
                   14702:              <section></section>
                   14703:              <group></group>
                   14704:             </roles>
                   14705: 
                   14706:             <dom></dom>         for scope type = domains
                   14707: 
                   14708:             <users>             for scope type = users
                   14709:              <user>
                   14710:               <uname></uname>
                   14711:               <udom></udom>
                   14712:              </user>
                   14713:             </users>
                   14714:            </scope> 
                   14715:               
                   14716:  Access data is also aggregated for each file in an additional key=value pair:
                   14717:  key -> path to file/file_name\0accesscontrol 
                   14718:  value -> reference to hash
                   14719:           hash contains key = value pairs
                   14720:           where key = uniqueID:scope_end_start
                   14721:                 value = UNIX time record was last updated
                   14722: 
                   14723:           Used to improve speed of look-ups of access controls for each file.  
                   14724:  
                   14725:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   14726: 
1.1172.2.13  raeburn  14727: =item *
                   14728: 
1.749     raeburn  14729: modify_access_controls():
                   14730: 
                   14731: Modifies access controls for a portfolio file
                   14732: Args
                   14733: 1. file name
                   14734: 2. reference to hash of required changes,
                   14735: 3. domain
                   14736: 4. username
                   14737:   where domain,username are the domain of the portfolio owner 
                   14738:   (either a user or a course) 
                   14739: 
                   14740: Returns:
                   14741: 1. result of additions or updates ('ok' or 'error', with error message). 
                   14742: 2. result of deletions ('ok' or 'error', with error message).
                   14743: 3. reference to hash of any new or updated access controls.
                   14744: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   14745:    key = integer (inbound ID)
1.1172.2.13  raeburn  14746:    value = uniqueID
                   14747: 
                   14748: =item *
                   14749: 
                   14750: get_timebased_id():
                   14751: 
                   14752: Attempts to get a unique timestamp-based suffix for use with items added to a
                   14753: course via the Course Editor (e.g., folders, composite pages,
                   14754: group bulletin boards).
                   14755: 
                   14756: Args: (first three required; six others optional)
                   14757: 
                   14758: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   14759:    docssequence, or name of group
                   14760: 
                   14761: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   14762:    e.g., num, boardids
                   14763: 
                   14764: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   14765:    file will be named nohist_namespace.db
                   14766: 
                   14767: 4. cdom: domain of course; default is current course domain from %env
                   14768: 
                   14769: 5. cnum: course number; default is current course number from %env
                   14770: 
                   14771: 6. idtype: set to concat if an additional digit is to be appended to the
                   14772:    unix timestamp to form the suffix, if the plain timestamp is already
                   14773:    in use.  Default is to not do this, but simply increment the unix
                   14774:    timestamp by 1 until a unique key is obtained.
                   14775: 
                   14776: 7. who: holder of locking key; defaults to user:domain for user.
                   14777: 
                   14778: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   14779:    retrying); default is 3.
                   14780: 
                   14781: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   14782: 
                   14783: Returns:
                   14784: 
                   14785: 1. suffix obtained (numeric)
                   14786: 
                   14787: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   14788: 
                   14789: 3. error: contains (localized) error message if an error occurred.
                   14790: 
1.747     albertel 14791: 
1.608     albertel 14792: =back
                   14793: 
1.243     albertel 14794: =head2 HTTP Helper Routines
                   14795: 
                   14796: =over 4
                   14797: 
1.191     harris41 14798: =item *
                   14799: 
                   14800: escape() : unpack non-word characters into CGI-compatible hex codes
                   14801: 
                   14802: =item *
                   14803: 
                   14804: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   14805: 
1.243     albertel 14806: =back
                   14807: 
                   14808: =head1 PRIVATE SUBROUTINES
                   14809: 
                   14810: =head2 Underlying communication routines (Shouldn't call)
                   14811: 
                   14812: =over 4
                   14813: 
                   14814: =item *
                   14815: 
                   14816: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   14817: 
                   14818: =item *
                   14819: 
                   14820: reply() : uses subreply to send a message to remote machine, logs all failures
                   14821: 
                   14822: =item *
                   14823: 
                   14824: critical() : passes a critical message to another server; if cannot
                   14825: get through then place message in connection buffer directory and
                   14826: returns con_delayed, if incapable of saving message, returns
                   14827: con_failed
                   14828: 
                   14829: =item *
                   14830: 
                   14831: reconlonc() : tries to reconnect lonc client processes.
                   14832: 
                   14833: =back
                   14834: 
                   14835: =head2 Resource Access Logging
                   14836: 
                   14837: =over 4
                   14838: 
                   14839: =item *
                   14840: 
                   14841: flushcourselogs() : flush (save) buffer logs and access logs
                   14842: 
                   14843: =item *
                   14844: 
                   14845: courselog($what) : save message for course in hash
                   14846: 
                   14847: =item *
                   14848: 
                   14849: courseacclog($what) : save message for course using &courselog().  Perform
                   14850: special processing for specific resource types (problems, exams, quizzes, etc).
                   14851: 
1.191     harris41 14852: =item *
                   14853: 
                   14854: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   14855: as a PerlChildExitHandler
1.243     albertel 14856: 
                   14857: =back
                   14858: 
                   14859: =head2 Other
                   14860: 
                   14861: =over 4
                   14862: 
                   14863: =item *
                   14864: 
                   14865: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 14866: 
                   14867: =back
                   14868: 
                   14869: =cut
1.877     foxr     14870: 

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