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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.109! raeburn     4: # $Id: lonnet.pm,v 1.1172.2.108 2019/08/03 23:36:09 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;
1.1172.2.107  raeburn    77: use CGI::Cookie;
1.977     amueller   78: 
1.1172.2.104  raeburn    79: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $deftex
1.1138    raeburn    80:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
                     81:             %managerstab);
1.871     albertel   82: 
                     83: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     84:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     85:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        86:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        87: 
1.1       albertel   88: use IO::Socket;
1.31      www        89: use GDBM_File;
1.208     albertel   90: use HTML::LCParser;
1.88      www        91: use Fcntl qw(:flock);
1.870     albertel   92: use Storable qw(thaw nfreeze);
1.1172.2.79  raeburn    93: use Time::HiRes qw( sleep gettimeofday tv_interval );
1.599     albertel   94: use Cache::Memcached;
1.676     albertel   95: use Digest::MD5;
1.790     albertel   96: use Math::Random;
1.1024    raeburn    97: use File::MMagic;
1.807     albertel   98: use LONCAPA qw(:DEFAULT :match);
1.740     www        99: use LONCAPA::Configuration;
1.1160    www       100: use LONCAPA::lonmetadata;
1.1172.2.22  raeburn   101: use LONCAPA::Lond;
1.1117    foxr      102: 
1.1090    raeburn   103: use File::Copy;
1.676     albertel  104: 
1.195     www       105: my $readit;
1.1172.2.79  raeburn   106: my $max_connection_retries = 20;     # Or some such value.
1.1       albertel  107: 
1.619     albertel  108: require Exporter;
                    109: 
                    110: our @ISA = qw (Exporter);
                    111: our @EXPORT = qw(%env);
                    112: 
1.1172.2.9  raeburn   113: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729     www       114: {
                    115:     my $logid;
1.1172.2.9  raeburn   116:     sub write_log {
                    117: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    118:         if ($context eq 'course') {
                    119:             if (($cnum eq '') || ($cdom eq '')) {
                    120:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    121:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    122:             }
1.957     raeburn   123:         }
1.1172.2.13  raeburn   124: 	$logid ++;
1.957     raeburn   125:         my $now = time();
                    126: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.1172.2.9  raeburn   127:         my $logentry = {
                    128:                          $id => {
                    129:                                   'exe_uname' => $env{'user.name'},
                    130:                                   'exe_udom'  => $env{'user.domain'},
                    131:                                   'exe_time'  => $now,
                    132:                                   'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    133:                                   'delflag'   => $delflag,
                    134:                                   'logentry'  => $storehash,
                    135:                                   'uname'     => $uname,
                    136:                                   'udom'      => $udom,
                    137:                                 }
                    138:                        };
                    139:         return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729     www       140:     }
                    141: }
1.1       albertel  142: 
1.163     harris41  143: sub logtouch {
                    144:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  145:     unless (-e "$execdir/logs/lonnet.log") {	
1.1172.2.96  raeburn   146: 	open(my $fh,">>","$execdir/logs/lonnet.log");
1.163     harris41  147: 	close $fh;
                    148:     }
                    149:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    150:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    151: }
                    152: 
1.1       albertel  153: sub logthis {
                    154:     my $message=shift;
                    155:     my $execdir=$perlvar{'lonDaemons'};
                    156:     my $now=time;
                    157:     my $local=localtime($now);
1.1172.2.96  raeburn   158:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
1.986     foxr      159: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    160: 	print $fh $logstring;
1.448     albertel  161: 	close($fh);
                    162:     }
1.1       albertel  163:     return 1;
                    164: }
                    165: 
                    166: sub logperm {
                    167:     my $message=shift;
                    168:     my $execdir=$perlvar{'lonDaemons'};
                    169:     my $now=time;
                    170:     my $local=localtime($now);
1.1172.2.96  raeburn   171:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
1.448     albertel  172: 	print $fh "$now:$message:$local\n";
                    173: 	close($fh);
                    174:     }
1.1       albertel  175:     return 1;
                    176: }
                    177: 
1.850     albertel  178: sub create_connection {
1.853     albertel  179:     my ($hostname,$lonid) = @_;
1.851     albertel  180:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  181: 				     Type    => SOCK_STREAM,
                    182: 				     Timeout => 10);
                    183:     return 0 if (!$client);
1.890     albertel  184:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  185:     my $result = <$client>;
                    186:     chomp($result);
                    187:     return 1 if ($result eq 'done');
                    188:     return 0;
                    189: }
                    190: 
1.983     raeburn   191: sub get_server_timezone {
                    192:     my ($cnum,$cdom) = @_;
                    193:     my $home=&homeserver($cnum,$cdom);
                    194:     if ($home ne 'no_host') {
                    195:         my $cachetime = 24*3600;
                    196:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    197:         if (defined($cached)) {
                    198:             return $timezone;
                    199:         } else {
                    200:             my $timezone = &reply('servertimezone',$home);
                    201:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    202:         }
                    203:     }
                    204: }
1.850     albertel  205: 
1.1106    raeburn   206: sub get_server_distarch {
                    207:     my ($lonhost,$ignore_cache) = @_;
                    208:     if (defined($lonhost)) {
                    209:         if (!defined(&hostname($lonhost))) {
                    210:             return;
                    211:         }
                    212:         my $cachetime = 12*3600;
                    213:         if (!$ignore_cache) {
                    214:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    215:             if (defined($cached)) {
                    216:                 return $distarch;
                    217:             }
                    218:         }
                    219:         my $rep = &reply('serverdistarch',$lonhost);
                    220:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    221:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    222:                 $rep eq '') {
                    223:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    224:         }
                    225:     }
                    226:     return;
                    227: }
                    228: 
1.993     raeburn   229: sub get_server_loncaparev {
1.1073    raeburn   230:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   231:     if (defined($lonhost)) {
                    232:         if (!defined(&hostname($lonhost))) {
                    233:             undef($lonhost);
                    234:         }
                    235:     }
                    236:     if (!defined($lonhost)) {
                    237:         if (defined(&domain($dom,'primary'))) {
                    238:             $lonhost=&domain($dom,'primary');
                    239:             if ($lonhost eq 'no_host') {
                    240:                 undef($lonhost);
                    241:             }
                    242:         }
                    243:     }
                    244:     if (defined($lonhost)) {
1.1073    raeburn   245:         my $cachetime = 12*3600;
                    246:         if (!$ignore_cache) {
                    247:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    248:             if (defined($cached)) {
                    249:                 return $loncaparev;
                    250:             }
                    251:         }
                    252:         my ($answer,$loncaparev);
                    253:         my @ids=&current_machine_ids();
                    254:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    255:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   256:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   257:                 $loncaparev = $1;
                    258:             }
                    259:         } else {
                    260:             $answer = &reply('serverloncaparev',$lonhost);
                    261:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    262:                 if ($caller eq 'loncron') {
                    263:                     my $ua=new LWP::UserAgent;
1.1082    raeburn   264:                     $ua->timeout(4);
1.1073    raeburn   265:                     my $protocol = $protocol{$lonhost};
                    266:                     $protocol = 'http' if ($protocol ne 'https');
                    267:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
                    268:                     my $request=new HTTP::Request('GET',$url);
                    269:                     my $response=$ua->request($request);
                    270:                     unless ($response->is_error()) {
                    271:                         my $content = $response->content;
1.1081    raeburn   272:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   273:                             $loncaparev = $1;
                    274:                         }
                    275:                     }
                    276:                 } else {
                    277:                     $loncaparev = $loncaparevs{$lonhost};
                    278:                 }
1.1081    raeburn   279:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   280:                 $loncaparev = $1;
                    281:             }
1.993     raeburn   282:         }
1.1073    raeburn   283:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   284:     }
                    285: }
                    286: 
1.1074    raeburn   287: sub get_server_homeID {
                    288:     my ($hostname,$ignore_cache,$caller) = @_;
                    289:     unless ($ignore_cache) {
                    290:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    291:         if (defined($cached)) {
                    292:             return $serverhomeID;
                    293:         }
                    294:     }
                    295:     my $cachetime = 12*3600;
                    296:     my $serverhomeID;
                    297:     if ($caller eq 'loncron') { 
                    298:         my @machine_ids = &machine_ids($hostname);
                    299:         foreach my $id (@machine_ids) {
                    300:             my $response = &reply('serverhomeID',$id);
                    301:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    302:                 $serverhomeID = $response;
                    303:                 last;
                    304:             }
                    305:         }
                    306:         if ($serverhomeID eq '') {
                    307:             $serverhomeID = $machine_ids[-1];
                    308:         }
                    309:     } else {
                    310:         $serverhomeID = $serverhomeIDs{$hostname};
                    311:     }
                    312:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    313: }
                    314: 
1.1121    raeburn   315: sub get_remote_globals {
                    316:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   317:     my ($result,%returnhash,%whatneeded);
                    318:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   319:         foreach my $what (sort(keys(%{$whathash}))) {
                    320:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   321:             my ($response,$cached);
1.1121    raeburn   322:             unless ($ignore_cache) {
1.1125    raeburn   323:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   324:             }
                    325:             if (defined($cached)) {
1.1125    raeburn   326:                 $returnhash{$what} = $response;
1.1121    raeburn   327:             } else {
1.1125    raeburn   328:                 $whatneeded{$what} = 1;
1.1121    raeburn   329:             }
                    330:         }
1.1125    raeburn   331:         if (keys(%whatneeded) == 0) {
                    332:             $result = 'ok';
                    333:         } else {
1.1121    raeburn   334:             my $requested = &freeze_escape(\%whatneeded);
                    335:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   336:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    337:                 ($rep eq 'unknown_cmd')) {
                    338:                 $result = $rep;
                    339:             } else {
                    340:                 $result = 'ok';
1.1121    raeburn   341:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   342:                 foreach my $item (@pairs) {
                    343:                     my ($key,$value)=split(/=/,$item,2);
                    344:                     my $what = &unescape($key);
                    345:                     my $hashid = $lonhost.'-'.$what;
                    346:                     $returnhash{$what}=&thaw_unescape($value);
                    347:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   348:                 }
                    349:             }
                    350:         }
                    351:     }
1.1125    raeburn   352:     return ($result,\%returnhash);
1.1121    raeburn   353: }
                    354: 
1.1124    raeburn   355: sub remote_devalidate_cache {
1.1172.2.35  raeburn   356:     my ($lonhost,$cachekeys) = @_;
                    357:     my $items;
                    358:     return unless (ref($cachekeys) eq 'ARRAY');
                    359:     my $cachestr = join('&',@{$cachekeys});
                    360:     return &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124    raeburn   361: }
                    362: 
1.1       albertel  363: # -------------------------------------------------- Non-critical communication
                    364: sub subreply {
                    365:     my ($cmd,$server)=@_;
1.838     albertel  366:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      367:     #
                    368:     #  With loncnew process trimming, there's a timing hole between lonc server
                    369:     #  process exit and the master server picking up the listen on the AF_UNIX
                    370:     #  socket.  In that time interval, a lock file will exist:
                    371: 
                    372:     my $lockfile=$peerfile.".lock";
                    373:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
1.1172.2.79  raeburn   374: 	sleep(0.1);
1.549     foxr      375:     }
                    376:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      377:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      378:     #
1.550     foxr      379:     #   We'll give the connection a few tries before abandoning it.  If
                    380:     #   connection is not possible, we'll con_lost back to the client.
                    381:     #   
                    382:     my $client;
                    383:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    384: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    385: 				      Type    => SOCK_STREAM,
                    386: 				      Timeout => 10);
1.869     albertel  387: 	if ($client) {
1.550     foxr      388: 	    last;		# Connected!
1.850     albertel  389: 	} else {
1.853     albertel  390: 	    &create_connection(&hostname($server),$server);
1.550     foxr      391: 	}
1.1172.2.79  raeburn   392:         sleep(0.1);		# Try again later if failed connection.
1.550     foxr      393:     }
                    394:     my $answer;
                    395:     if ($client) {
1.704     albertel  396: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      397: 	$answer=<$client>;
                    398: 	if (!$answer) { $answer="con_lost"; }
                    399: 	chomp($answer);
                    400:     } else {
                    401: 	$answer = 'con_lost';	# Failed connection.
                    402:     }
1.1       albertel  403:     return $answer;
                    404: }
                    405: 
                    406: sub reply {
                    407:     my ($cmd,$server)=@_;
1.838     albertel  408:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  409:     my $answer=subreply($cmd,$server);
1.65      www       410:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  411:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       412:                 " $cmd to $server returned $answer</font>");
                    413:     }
1.1       albertel  414:     return $answer;
                    415: }
                    416: 
                    417: # ----------------------------------------------------------- Send USR1 to lonc
                    418: 
                    419: sub reconlonc {
1.891     albertel  420:     my ($lonid) = @_;
                    421:     if ($lonid) {
1.1172.2.72  raeburn   422:         my $hostname = &hostname($lonid);
1.891     albertel  423: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    424: 	if ($hostname && -e $peerfile) {
                    425: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    426: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    427: 					     Type    => SOCK_STREAM,
                    428: 					     Timeout => 10);
                    429: 	    if ($client) {
                    430: 		print $client ("reset_retries\n");
                    431: 		my $answer=<$client>;
                    432: 		#reset just this one.
                    433: 	    }
                    434: 	}
                    435: 	return;
                    436:     }
                    437: 
1.836     www       438:     &logthis("Trying to reconnect lonc");
1.1       albertel  439:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.1172.2.96  raeburn   440:     if (open(my $fh,"<",$loncfile)) {
1.1       albertel  441: 	my $loncpid=<$fh>;
                    442:         chomp($loncpid);
                    443:         if (kill 0 => $loncpid) {
                    444: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    445:             kill USR1 => $loncpid;
                    446:             sleep 1;
1.836     www       447:          } else {
1.12      www       448: 	    &logthis(
1.672     albertel  449:                "<font color=\"blue\">WARNING:".
1.12      www       450:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  451:         }
                    452:     } else {
1.836     www       453: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  454:     }
                    455: }
                    456: 
                    457: # ------------------------------------------------------ Critical communication
1.12      www       458: 
1.1       albertel  459: sub critical {
                    460:     my ($cmd,$server)=@_;
1.838     albertel  461:     unless (&hostname($server)) {
1.672     albertel  462:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       463:                " Critical message to unknown server ($server)</font>");
                    464:         return 'no_such_host';
                    465:     }
1.1       albertel  466:     my $answer=reply($cmd,$server);
                    467:     if ($answer eq 'con_lost') {
1.1172.2.72  raeburn   468: 	&reconlonc($server);
1.589     albertel  469: 	my $answer=reply($cmd,$server);
1.1       albertel  470:         if ($answer eq 'con_lost') {
                    471:             my $now=time;
                    472:             my $middlename=$cmd;
1.5       www       473:             $middlename=substr($middlename,0,16);
1.1       albertel  474:             $middlename=~s/\W//g;
                    475:             my $dfilename=
1.305     www       476:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    477:             $dumpcount++;
1.1       albertel  478:             {
1.448     albertel  479: 		my $dfh;
1.1172.2.96  raeburn   480: 		if (open($dfh,">",$dfilename)) {
1.448     albertel  481: 		    print $dfh "$cmd\n"; 
                    482: 		    close($dfh);
                    483: 		}
1.1       albertel  484:             }
1.1172.2.79  raeburn   485:             sleep 1;
1.1       albertel  486:             my $wcmd='';
                    487:             {
1.448     albertel  488: 		my $dfh;
1.1172.2.96  raeburn   489: 		if (open($dfh,"<",$dfilename)) {
1.448     albertel  490: 		    $wcmd=<$dfh>; 
                    491: 		    close($dfh);
                    492: 		}
1.1       albertel  493:             }
                    494:             chomp($wcmd);
1.7       www       495:             if ($wcmd eq $cmd) {
1.672     albertel  496: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       497:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  498:                 &logperm("D:$server:$cmd");
                    499: 	        return 'con_delayed';
                    500:             } else {
1.672     albertel  501:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       502:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  503:                 &logperm("F:$server:$cmd");
                    504:                 return 'con_failed';
                    505:             }
                    506:         }
                    507:     }
                    508:     return $answer;
1.405     albertel  509: }
                    510: 
1.755     albertel  511: # ------------------------------------------- check if return value is an error
                    512: 
                    513: sub error {
                    514:     my ($result) = @_;
1.756     albertel  515:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  516: 	if ($2 == 2) { return undef; }
                    517: 	return $1;
                    518:     }
                    519:     return undef;
                    520: }
                    521: 
1.783     albertel  522: sub convert_and_load_session_env {
                    523:     my ($lonidsdir,$handle)=@_;
                    524:     my @profile;
                    525:     {
1.917     albertel  526: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    527: 	if (!$opened) {
1.915     albertel  528: 	    return 0;
                    529: 	}
1.783     albertel  530: 	flock($idf,LOCK_SH);
                    531: 	@profile=<$idf>;
                    532: 	close($idf);
                    533:     }
                    534:     my %temp_env;
                    535:     foreach my $line (@profile) {
1.786     albertel  536: 	if ($line !~ m/=/) {
                    537: 	    return 0;
                    538: 	}
1.783     albertel  539: 	chomp($line);
                    540: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    541: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    542:     }
                    543:     unlink("$lonidsdir/$handle.id");
                    544:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    545: 	    0640)) {
                    546: 	%disk_env = %temp_env;
                    547: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    548: 	untie(%disk_env);
                    549:     }
1.786     albertel  550:     return 1;
1.783     albertel  551: }
                    552: 
1.374     www       553: # ------------------------------------------- Transfer profile into environment
1.780     albertel  554: my $env_loaded;
                    555: sub transfer_profile_to_env {
1.788     albertel  556:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    557:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       558: 
1.720     albertel  559:     if (!defined($lonidsdir)) {
                    560: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    561:     }
                    562:     if (!defined($handle)) {
                    563:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    564:     }
                    565: 
1.786     albertel  566:     my $convert;
                    567:     {
1.917     albertel  568:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    569: 	if (!$opened) {
1.915     albertel  570: 	    return;
                    571: 	}
1.786     albertel  572: 	flock($idf,LOCK_SH);
                    573: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    574: 		&GDBM_READER(),0640)) {
                    575: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    576: 	    untie(%disk_env);
                    577: 	} else {
                    578: 	    $convert = 1;
                    579: 	}
                    580:     }
                    581:     if ($convert) {
                    582: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    583: 	    &logthis("Failed to load session, or convert session.");
                    584: 	}
1.374     www       585:     }
1.783     albertel  586: 
1.786     albertel  587:     my %remove;
1.783     albertel  588:     while ( my $envname = each(%env) ) {
1.433     matthew   589:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    590:             if ($time < time-300) {
1.783     albertel  591:                 $remove{$key}++;
1.433     matthew   592:             }
                    593:         }
                    594:     }
1.783     albertel  595: 
1.619     albertel  596:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  597:     $env_loaded=1;
1.783     albertel  598:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   599:         &delenv($expired_key);
1.374     www       600:     }
1.1       albertel  601: }
                    602: 
1.916     albertel  603: # ---------------------------------------------------- Check for valid session 
                    604: sub check_for_valid_session {
1.1172.2.96  raeburn   605:     my ($r,$name,$userhashref,$domref) = @_;
1.916     albertel  606:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1172.2.108  raeburn   607:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
1.1155    raeburn   608:     if ($name eq 'lonDAV') {
                    609:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    610:     } else {
                    611:         $lonidsdir=$r->dir_config('lonIDsDir');
1.1172.2.108  raeburn   612:         if ($name eq '') {
                    613:             $name = 'lonID';
                    614:         }
                    615:     }
                    616:     if ($name eq 'lonID') {
                    617:         $secure = 'lonSID';
                    618:         $linkname = 'lonLinkID';
                    619:         $pubname = 'lonPubID';
                    620:         if (exists($cookies{$secure})) {
                    621:             $lonid=$cookies{$secure};
                    622:         } elsif (exists($cookies{$name})) {
                    623:             $lonid=$cookies{$name};
                    624:         } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
                    625:             $lonid=$cookies{$linkname};
                    626:         } elsif (exists($cookies{$pubname})) {
                    627:             $lonid=$cookies{$pubname};
                    628:         }
                    629:     } else {
                    630:         $lonid=$cookies{$name};
                    631:     }
                    632:     return undef if (!$lonid);
                    633: 
                    634:     my $handle=&LONCAPA::clean_handle($lonid->value);
                    635:     if (-l "$lonidsdir/$handle.id") {
                    636:         my $link = readlink("$lonidsdir/$handle.id");
                    637:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    638:             $handle = $1;
                    639:         }
1.1155    raeburn   640:     }
1.1172.2.96  raeburn   641:     if (!-e "$lonidsdir/$handle.id") {
                    642:         if ((ref($domref)) && ($name eq 'lonID') &&
                    643:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    644:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    645:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    646:                 $$domref = $possudom;
                    647:             }
                    648:         }
                    649:         return undef;
                    650:     }
1.916     albertel  651: 
1.917     albertel  652:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    653:     return undef if (!$opened);
1.916     albertel  654: 
                    655:     flock($idf,LOCK_SH);
                    656:     my %disk_env;
                    657:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    658: 	    &GDBM_READER(),0640)) {
                    659: 	return undef;	
                    660:     }
                    661: 
                    662:     if (!defined($disk_env{'user.name'})
                    663: 	|| !defined($disk_env{'user.domain'})) {
1.1172.2.107  raeburn   664:         untie(%disk_env);
1.916     albertel  665: 	return undef;
                    666:     }
1.1172.2.18  raeburn   667: 
1.1172.2.36  raeburn   668:     if (ref($userhashref) eq 'HASH') {
                    669:         $userhashref->{'name'} = $disk_env{'user.name'};
                    670:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1172.2.18  raeburn   671:     }
1.1172.2.107  raeburn   672:     untie(%disk_env);
1.1172.2.18  raeburn   673: 
1.916     albertel  674:     return $handle;
                    675: }
                    676: 
1.830     albertel  677: sub timed_flock {
                    678:     my ($file,$lock_type) = @_;
                    679:     my $failed=0;
                    680:     eval {
                    681: 	local $SIG{__DIE__}='DEFAULT';
                    682: 	local $SIG{ALRM}=sub {
                    683: 	    $failed=1;
                    684: 	    die("failed lock");
                    685: 	};
                    686: 	alarm(13);
                    687: 	flock($file,$lock_type);
                    688: 	alarm(0);
                    689:     };
                    690:     if ($failed) {
                    691: 	return undef;
                    692:     } else {
                    693: 	return 1;
                    694:     }
                    695: }
                    696: 
1.1172.2.107  raeburn   697: sub get_sessionfile_vars {
                    698:     my ($handle,$lonidsdir,$storearr) = @_;
                    699:     my %returnhash;
                    700:     unless (ref($storearr) eq 'ARRAY') {
                    701:         return %returnhash;
                    702:     }
                    703:     if (-l "$lonidsdir/$handle.id") {
                    704:         my $link = readlink("$lonidsdir/$handle.id");
                    705:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    706:             $handle = $1;
                    707:         }
                    708:     }
                    709:     if ((-e "$lonidsdir/$handle.id") &&
                    710:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    711:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    712:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    713:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
                    714:                 flock($idf,LOCK_SH);
                    715:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    716:                         &GDBM_READER(),0640)) {
                    717:                     foreach my $item (@{$storearr}) {
                    718:                         $returnhash{$item} = $disk_env{$item};
                    719:                     }
                    720:                     untie(%disk_env);
                    721:                 }
                    722:             }
                    723:         }
                    724:     }
                    725:     return %returnhash;
                    726: }
                    727: 
1.5       www       728: # ---------------------------------------------------------- Append Environment
                    729: 
                    730: sub appenv {
1.949     raeburn   731:     my ($newenv,$roles) = @_;
                    732:     if (ref($newenv) eq 'HASH') {
                    733:         foreach my $key (keys(%{$newenv})) {
                    734:             my $refused = 0;
                    735: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    736:                 $refused = 1;
                    737:                 if (ref($roles) eq 'ARRAY') {
1.1172.2.40  raeburn   738:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   739:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    740:                         $refused = 0;
                    741:                     }
                    742:                 }
                    743:             }
                    744:             if ($refused) {
                    745:                 &logthis("<font color=\"blue\">WARNING: ".
                    746:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    747:                          .'</font>');
                    748: 	        delete($newenv->{$key});
                    749:             } else {
                    750:                 $env{$key}=$newenv->{$key};
                    751:             }
                    752:         }
1.1172.2.96  raeburn   753:         my $lonids = $perlvar{'lonIDsDir'};
                    754:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
                    755:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    756:             if ($opened
                    757: 	        && &timed_flock($env_file,LOCK_EX)
                    758: 	        &&
                    759: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    760: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    761: 	        while (my ($key,$value) = each(%{$newenv})) {
                    762: 	            $disk_env{$key} = $value;
                    763: 	        }
                    764: 	        untie(%disk_env);
                    765:             }
1.35      www       766:         }
1.191     harris41  767:     }
1.56      www       768:     return 'ok';
                    769: }
                    770: # ----------------------------------------------------- Delete from Environment
                    771: 
                    772: sub delenv {
1.1104    raeburn   773:     my ($delthis,$regexp,$roles) = @_;
                    774:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    775:         my $refused = 1;
                    776:         if (ref($roles) eq 'ARRAY') {
                    777:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    778:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    779:                 $refused = 0;
                    780:             }
                    781:         }
                    782:         if ($refused) {
                    783:             &logthis("<font color=\"blue\">WARNING: ".
                    784:                      "Attempt to delete from environment ".$delthis);
                    785:             return 'error';
                    786:         }
1.56      www       787:     }
1.917     albertel  788:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    789:     if ($opened
1.915     albertel  790: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  791: 	&&
                    792: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    793: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  794: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   795: 	    if ($regexp) {
                    796:                 if ($key=~/^$delthis/) {
                    797:                     delete($env{$key});
                    798:                     delete($disk_env{$key});
                    799:                 } 
                    800:             } else {
                    801:                 if ($key=~/^\Q$delthis\E/) {
                    802: 		    delete($env{$key});
                    803: 		    delete($disk_env{$key});
                    804: 	        }
                    805:             }
1.448     albertel  806: 	}
1.783     albertel  807: 	untie(%disk_env);
1.5       www       808:     }
                    809:     return 'ok';
1.369     albertel  810: }
                    811: 
1.790     albertel  812: sub get_env_multiple {
                    813:     my ($name) = @_;
                    814:     my @values;
                    815:     if (defined($env{$name})) {
                    816:         # exists is it an array
                    817:         if (ref($env{$name})) {
                    818:             @values=@{ $env{$name} };
                    819:         } else {
                    820:             $values[0]=$env{$name};
                    821:         }
                    822:     }
                    823:     return(@values);
                    824: }
                    825: 
1.958     www       826: # ------------------------------------------------------------------- Locking
                    827: 
                    828: sub set_lock {
                    829:     my ($text)=@_;
                    830:     $locknum++;
                    831:     my $id=$$.'-'.$locknum;
                    832:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    833:              'session.lock.'.$id => $text});
                    834:     return $id;
                    835: }
                    836: 
                    837: sub get_locks {
                    838:     my $num=0;
                    839:     my %texts=();
                    840:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    841:        if ($lock=~/\w/) {
                    842:           $num++;
                    843:           $texts{$lock}=$env{'session.lock.'.$lock};
                    844:        }
                    845:    }
                    846:    return ($num,%texts);
                    847: }
                    848: 
                    849: sub remove_lock {
                    850:     my ($id)=@_;
                    851:     my $newlocks='';
                    852:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    853:        if (($lock=~/\w/) && ($lock ne $id)) {
                    854:           $newlocks.=','.$lock;
                    855:        }
                    856:     }
                    857:     &appenv({'session.locks' => $newlocks});
                    858:     &delenv('session.lock.'.$id);
                    859: }
                    860: 
                    861: sub remove_all_locks {
                    862:     my $activelocks=$env{'session.locks'};
                    863:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    864:        if ($lock=~/\w/) {
                    865:           &remove_lock($lock);
                    866:        }
                    867:     }
                    868: }
                    869: 
                    870: 
1.369     albertel  871: # ------------------------------------------ Find out current server userload
                    872: sub userload {
                    873:     my $numusers=0;
                    874:     {
                    875: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    876: 	my $filename;
                    877: 	my $curtime=time;
                    878: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  879: 	    next if ($filename eq '.' || $filename eq '..');
                    880: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  881: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  882: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  883: 	}
                    884: 	closedir(LONIDS);
                    885:     }
                    886:     my $userloadpercent=0;
                    887:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    888:     if ($maxuserload) {
1.371     albertel  889: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  890:     }
1.372     albertel  891:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  892:     return $userloadpercent;
1.283     www       893: }
                    894: 
1.1       albertel  895: # ------------------------------ Find server with least workload from spare.tab
1.11      www       896: 
1.1       albertel  897: sub spareserver {
1.1083    raeburn   898:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  899:     my $spare_server;
1.370     albertel  900:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  901:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    902:                                                      :  $userloadpercent;
1.1083    raeburn   903:     my ($uint_dom,$remotesessions);
                    904:     if (($udom ne '') && (&domain($udom) ne '')) {
                    905:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    906:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    907:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    908:         $remotesessions = $udomdefaults{'remotesessions'};
                    909:     }
1.1123    raeburn   910:     my $spareshash = &this_host_spares($udom);
                    911:     if (ref($spareshash) eq 'HASH') {
                    912:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    913:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1172.2.62  raeburn   914:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    915:                                              $try_server));
1.1123    raeburn   916: 	        ($spare_server, $lowest_load) =
                    917: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    918:             }
1.1083    raeburn   919:         }
1.784     albertel  920: 
1.1123    raeburn   921:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    922: 
                    923:         if (!$found_server) {
                    924:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    925: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1172.2.62  raeburn   926:                     next unless (&spare_can_host($udom,$uint_dom,
                    927:                                                  $remotesessions,$try_server));
1.1123    raeburn   928: 	            ($spare_server, $lowest_load) =
                    929: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    930:                 }
                    931: 	    }
                    932:         }
1.784     albertel  933:     }
                    934: 
                    935:     if (!$want_server_name) {
1.968     raeburn   936:         my $protocol = 'http';
                    937:         if ($protocol{$spare_server} eq 'https') {
                    938:             $protocol = $protocol{$spare_server};
                    939:         }
1.1001    raeburn   940:         if (defined($spare_server)) {
                    941:             my $hostname = &hostname($spare_server);
1.1083    raeburn   942:             if (defined($hostname)) {
1.1001    raeburn   943: 	        $spare_server = $protocol.'://'.$hostname;
                    944:             }
                    945:         }
1.784     albertel  946:     }
                    947:     return $spare_server;
                    948: }
                    949: 
                    950: sub compare_server_load {
1.1172.2.41  raeburn   951:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                    952: 
                    953:     if ($required) {
                    954:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                    955:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                    956:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                    957:         if (($major eq '' && $minor eq '') ||
                    958:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                    959:             return ($spare_server,$lowest_load);
                    960:         }
                    961:     }
1.784     albertel  962: 
                    963:     my $loadans     = &reply('load',    $try_server);
                    964:     my $userloadans = &reply('userload',$try_server);
                    965: 
                    966:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   967: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  968:     }
                    969: 
                    970:     my $load;
                    971:     if ($loadans =~ /\d/) {
                    972: 	if ($userloadans =~ /\d/) {
                    973: 	    #both are numbers, pick the bigger one
                    974: 	    $load = ($loadans > $userloadans) ? $loadans 
                    975: 		                              : $userloadans;
1.411     albertel  976: 	} else {
1.784     albertel  977: 	    $load = $loadans;
1.411     albertel  978: 	}
1.784     albertel  979:     } else {
                    980: 	$load = $userloadans;
                    981:     }
                    982: 
                    983:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    984: 	$spare_server = $try_server;
                    985: 	$lowest_load  = $load;
1.370     albertel  986:     }
1.784     albertel  987:     return ($spare_server,$lowest_load);
1.202     matthew   988: }
1.914     albertel  989: 
                    990: # --------------------------- ask offload servers if user already has a session
                    991: sub find_existing_session {
                    992:     my ($udom,$uname) = @_;
1.1123    raeburn   993:     my $spareshash = &this_host_spares($udom);
                    994:     if (ref($spareshash) eq 'HASH') {
                    995:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    996:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    997:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    998:             }
                    999:         }
                   1000:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                   1001:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                   1002:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1003:             }
                   1004:         }
1.914     albertel 1005:     }
                   1006:     return;
                   1007: }
                   1008: 
1.1172.2.107  raeburn  1009: # check if user's browser sent load balancer cookie and server still has session
                   1010: # and is not overloaded.
                   1011: sub check_for_balancer_cookie {
                   1012:     my ($r,$update_mtime) = @_;
                   1013:     my ($otherserver,$cookie);
                   1014:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                   1015:     if (exists($cookies{'balanceID'})) {
                   1016:         my $balid = $cookies{'balanceID'};
                   1017:         $cookie=&LONCAPA::clean_handle($balid->value);
                   1018:         my $balancedir=$r->dir_config('lonBalanceDir');
                   1019:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
                   1020:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
                   1021:                 my ($possudom,$possuname) = ($1,$2);
                   1022:                 my $has_session = 0;
                   1023:                 if ((&domain($possudom) ne '') &&
                   1024:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
                   1025:                     my $try_server;
                   1026:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
                   1027:                     if ($opened) {
                   1028:                         flock($idf,LOCK_SH);
                   1029:                         while (my $line = <$idf>) {
                   1030:                             chomp($line);
                   1031:                             if (&hostname($line) ne '') {
                   1032:                                 $try_server = $line;
                   1033:                                 last;
                   1034:                             }
                   1035:                         }
                   1036:                         close($idf);
                   1037:                         if (($try_server) &&
                   1038:                             (&has_user_session($try_server,$possudom,$possuname))) {
                   1039:                             my $lowest_load = 30000;
                   1040:                             ($otherserver,$lowest_load) =
                   1041:                                 &compare_server_load($try_server,undef,$lowest_load);
                   1042:                             if ($otherserver ne '' && $lowest_load < 100) {
                   1043:                                 $has_session = 1;
                   1044:                             } else {
                   1045:                                 undef($otherserver);
                   1046:                             }
                   1047:                         }
                   1048:                     }
                   1049:                 }
                   1050:                 if ($has_session) {
                   1051:                     if ($update_mtime) {
                   1052:                         my $atime = my $mtime = time;
                   1053:                         utime($atime,$mtime,"$balancedir/$cookie.id");
                   1054:                     }
                   1055:                 } else {
                   1056:                     unlink("$balancedir/$cookie.id");
                   1057:                 }
                   1058:             }
                   1059:         }
                   1060:     }
                   1061:     return ($otherserver,$cookie);
                   1062: }
                   1063: 
                   1064: sub delbalcookie {
                   1065:     my ($cookie,$balancer) =@_;
                   1066:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
                   1067:         my ($udom,$uname) = ($1,$2);
                   1068:         my $uprimary_id = &domain($udom,'primary');
                   1069:         my $uintdom = &internet_dom($uprimary_id);
                   1070:         my $intdom = &internet_dom($balancer);
                   1071:         my $serverhomedom = &host_domain($balancer);
                   1072:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1073:             return &reply("delbalcookie:$cookie",$balancer);
                   1074:         }
                   1075:     }
                   1076: }
                   1077: 
1.914     albertel 1078: # -------------------------------- ask if server already has a session for user
                   1079: sub has_user_session {
                   1080:     my ($lonid,$udom,$uname) = @_;
                   1081:     my $result = &reply(join(':','userhassession',
                   1082: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                   1083:     return 1 if ($result eq 'ok');
                   1084: 
                   1085:     return 0;
                   1086: }
                   1087: 
1.1076    raeburn  1088: # --------- determine least loaded server in a user's domain which allows login
                   1089: 
                   1090: sub choose_server {
1.1172.2.47  raeburn  1091:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn  1092:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn  1093:     my %servers = &get_servers($udom);
1.1076    raeburn  1094:     my $lowest_load = 30000;
1.1172.2.47  raeburn  1095:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                   1096:     if ($skiploadbal) {
                   1097:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                   1098:         unless (defined($cached)) {
                   1099:             my $cachetime = 60*60*24;
                   1100:             my %domconfig =
                   1101:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1102:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1103:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                   1104:                                            $cachetime);
                   1105:             }
                   1106:         }
                   1107:     }
1.1076    raeburn  1108:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn  1109:         my $loginvia;
1.1172.2.47  raeburn  1110:         if ($skiploadbal) {
                   1111:             if (ref($balancers) eq 'HASH') {
                   1112:                 next if (exists($balancers->{$lonhost}));
                   1113:             }
                   1114:         }
1.1115    raeburn  1115:         if ($checkloginvia) {
                   1116:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn  1117:             if ($loginvia) {
                   1118:                 my ($server,$path) = split(/:/,$loginvia);
                   1119:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1120:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn  1121:                 if ($login_host eq $server) {
                   1122:                     $portal_path = $path;
1.1151    raeburn  1123:                     $isredirect = 1;
1.1116    raeburn  1124:                 }
                   1125:             } else {
                   1126:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1127:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn  1128:                 if ($login_host eq $lonhost) {
                   1129:                     $portal_path = '';
1.1151    raeburn  1130:                     $isredirect = ''; 
1.1116    raeburn  1131:                 }
                   1132:             }
                   1133:         } else {
1.1076    raeburn  1134:             ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1135:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1136:         }
                   1137:     }
                   1138:     if ($login_host ne '') {
1.1116    raeburn  1139:         $hostname = &hostname($login_host);
1.1076    raeburn  1140:     }
1.1172.2.88  raeburn  1141:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076    raeburn  1142: }
                   1143: 
1.202     matthew  1144: # --------------------------------------------- Try to change a user's password
                   1145: 
                   1146: sub changepass {
1.799     raeburn  1147:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1148:     $currentpass = &escape($currentpass);
                   1149:     $newpass     = &escape($newpass);
1.1030    raeburn  1150:     my $lonhost = $perlvar{'lonHostID'};
                   1151:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1152: 		       $server);
                   1153:     if (! $answer) {
                   1154: 	&logthis("No reply on password change request to $server ".
                   1155: 		 "by $uname in domain $udom.");
                   1156:     } elsif ($answer =~ "^ok") {
                   1157:         &logthis("$uname in $udom successfully changed their password ".
                   1158: 		 "on $server.");
                   1159:     } elsif ($answer =~ "^pwchange_failure") {
                   1160: 	&logthis("$uname in $udom was unable to change their password ".
                   1161: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1162: 		 "or pwchange");
                   1163:     } elsif ($answer =~ "^non_authorized") {
                   1164:         &logthis("$uname in $udom did not get their password correct when ".
                   1165: 		 "attempting to change it on $server.");
                   1166:     } elsif ($answer =~ "^auth_mode_error") {
                   1167:         &logthis("$uname in $udom attempted to change their password despite ".
                   1168: 		 "not being locally or internally authenticated on $server.");
                   1169:     } elsif ($answer =~ "^unknown_user") {
                   1170:         &logthis("$uname in $udom attempted to change their password ".
                   1171: 		 "on $server but were unable to because $server is not ".
                   1172: 		 "their home server.");
                   1173:     } elsif ($answer =~ "^refused") {
                   1174: 	&logthis("$server refused to change $uname in $udom password because ".
                   1175: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1176:     } elsif ($answer =~ "invalid_client") {
                   1177:         &logthis("$server refused to change $uname in $udom password because ".
                   1178:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1179:     }
                   1180:     return $answer;
1.1       albertel 1181: }
                   1182: 
1.169     harris41 1183: # ----------------------- Try to determine user's current authentication scheme
                   1184: 
                   1185: sub queryauthenticate {
                   1186:     my ($uname,$udom)=@_;
1.456     albertel 1187:     my $uhome=&homeserver($uname,$udom);
                   1188:     if (!$uhome) {
                   1189: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1190: 	return 'no_host';
                   1191:     }
                   1192:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1193:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1194: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1195:     }
1.456     albertel 1196:     return $answer;
1.169     harris41 1197: }
                   1198: 
1.1       albertel 1199: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1200: 
1.1       albertel 1201: sub authenticate {
1.1073    raeburn  1202:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1203:     $upass=&escape($upass);
                   1204:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1205:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1206:     my $newhome;
1.836     www      1207:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1208: # Maybe the machine was offline and only re-appeared again recently?
                   1209:         &reconlonc();
                   1210: # One more
1.952     raeburn  1211: 	$uhome=&homeserver($uname,$udom,1);
                   1212:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1213:             if (defined(&domain($udom,'primary'))) {
                   1214:                 $newhome=&domain($udom,'primary');
                   1215:             }
                   1216:             if ($newhome ne '') {
                   1217:                 $uhome = $newhome;
                   1218:             }
                   1219:         }
1.836     www      1220: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1221: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1222: 	    return 'no_host';
                   1223:         }
1.1       albertel 1224:     }
1.1073    raeburn  1225:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1226:     if ($answer eq 'authorized') {
1.952     raeburn  1227:         if ($newhome) {
                   1228:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1229:             return 'no_account_on_host'; 
                   1230:         } else {
                   1231:             &logthis("User $uname at $udom authorized by $uhome");
                   1232:             return $uhome;
                   1233:         }
1.471     albertel 1234:     }
                   1235:     if ($answer eq 'non_authorized') {
                   1236: 	&logthis("User $uname at $udom rejected by $uhome");
                   1237: 	return 'no_host'; 
1.9       www      1238:     }
1.471     albertel 1239:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1240:     return 'no_host';
                   1241: }
                   1242: 
1.1073    raeburn  1243: sub can_host_session {
1.1074    raeburn  1244:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1245:     my $canhost = 1;
1.1074    raeburn  1246:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1247:     if (ref($remotesessions) eq 'HASH') {
                   1248:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1249:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1250:                 $canhost = 0;
                   1251:             } else {
                   1252:                 $canhost = 1;
                   1253:             }
                   1254:         }
                   1255:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1256:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1257:                 $canhost = 1;
                   1258:             } else {
                   1259:                 $canhost = 0;
                   1260:             }
                   1261:         }
                   1262:         if ($canhost) {
                   1263:             if ($remotesessions->{'version'} ne '') {
                   1264:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1265:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1266:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1267:                         my $major = $1;
                   1268:                         my $minor = $2;
                   1269:                         if (($major < $reqmajor ) ||
                   1270:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1271:                             $canhost = 0;
                   1272:                         }
                   1273:                     } else {
                   1274:                         $canhost = 0;
                   1275:                     }
                   1276:                 }
                   1277:             }
                   1278:         }
                   1279:     }
                   1280:     if ($canhost) {
                   1281:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1282:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1283:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1284:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1285:                 if (($uint_dom ne '') && 
                   1286:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1287:                     $canhost = 0;
                   1288:                 } else {
                   1289:                     $canhost = 1;
                   1290:                 }
                   1291:             }
                   1292:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1293:                 if (($uint_dom ne '') && 
                   1294:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1295:                     $canhost = 1;
                   1296:                 } else {
                   1297:                     $canhost = 0;
                   1298:                 }
                   1299:             }
                   1300:         }
                   1301:     }
                   1302:     return $canhost;
                   1303: }
                   1304: 
1.1083    raeburn  1305: sub spare_can_host {
                   1306:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1307:     my $canhost=1;
1.1172.2.62  raeburn  1308:     my $try_server_hostname = &hostname($try_server);
                   1309:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1310:     my $serverhomedom = &host_domain($serverhomeID);
                   1311:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1312:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1313:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1314:             $canhost = 0;
                   1315:         }
                   1316:     }
                   1317:     if (($canhost) && ($uint_dom)) {
                   1318:         my @intdoms;
                   1319:         my $internet_names = &get_internet_names($try_server);
                   1320:         if (ref($internet_names) eq 'ARRAY') {
                   1321:             @intdoms = @{$internet_names};
                   1322:         }
                   1323:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1324:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1325:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1326:                                          $remotesessions,
                   1327:                                          $defdomdefaults{'hostedsessions'});
                   1328:         }
1.1083    raeburn  1329:     }
                   1330:     return $canhost;
                   1331: }
                   1332: 
1.1123    raeburn  1333: sub this_host_spares {
                   1334:     my ($dom) = @_;
1.1126    raeburn  1335:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1336:     my @hosts = &current_machine_ids();
                   1337:     foreach my $lonhost (@hosts) {
                   1338:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1339:             $dom_in_use = $dom;
                   1340:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1341:             last;
                   1342:         }
                   1343:     }
1.1126    raeburn  1344:     if ($dom_in_use ne '') {
                   1345:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1346:     }
                   1347:     if (ref($result) ne 'HASH') {
                   1348:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1349:         $dom_in_use = &host_domain($lonhost_in_use);
                   1350:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1351:         if (ref($result) ne 'HASH') {
                   1352:             $result = \%spareid;
                   1353:         }
                   1354:     }
                   1355:     return $result;
                   1356: }
                   1357: 
                   1358: sub spares_for_offload  {
                   1359:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1360:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1361:     if (defined($cached)) {
                   1362:         return $result;
                   1363:     } else {
1.1126    raeburn  1364:         my $cachetime = 60*60*24;
                   1365:         my %domconfig =
                   1366:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1367:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1368:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1369:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1370:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1371:                 }
                   1372:             }
                   1373:         }
                   1374:     }
1.1126    raeburn  1375:     return;
1.1123    raeburn  1376: }
                   1377: 
1.1129    raeburn  1378: sub get_lonbalancer_config {
                   1379:     my ($servers) = @_;
                   1380:     my ($currbalancer,$currtargets);
                   1381:     if (ref($servers) eq 'HASH') {
                   1382:         foreach my $server (keys(%{$servers})) {
                   1383:             my %what = (
                   1384:                          spareid => 1,
                   1385:                          perlvar => 1,
                   1386:                        );
                   1387:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1388:             if ($result eq 'ok') {
                   1389:                 if (ref($returnhash) eq 'HASH') {
                   1390:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1391:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1392:                             $currbalancer = $server;
                   1393:                             $currtargets = {};
                   1394:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1395:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1396:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1397:                                 }
                   1398:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1399:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1400:                                 }
                   1401:                             }
                   1402:                             last;
                   1403:                         }
                   1404:                     }
                   1405:                 }
                   1406:             }
                   1407:         }
                   1408:     }
                   1409:     return ($currbalancer,$currtargets);
                   1410: }
                   1411: 
                   1412: sub check_loadbalancing {
1.1172.2.88  raeburn  1413:     my ($uname,$udom,$caller) = @_;
1.1172.2.12  raeburn  1414:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1172.2.107  raeburn  1415:         $rule_in_effect,$offloadto,$otherserver,$setcookie);
1.1129    raeburn  1416:     my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4  raeburn  1417:     my @hosts = &current_machine_ids();
1.1129    raeburn  1418:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1419:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1420:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1421:     my $serverhomedom = &host_domain($lonhost);
1.1172.2.75  raeburn  1422:     my $domneedscache; 
1.1129    raeburn  1423:     my $cachetime = 60*60*24;
                   1424: 
                   1425:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1426:         $dom_in_use = $udom;
                   1427:         $homeintdom = 1;
                   1428:     } else {
                   1429:         $dom_in_use = $serverhomedom;
                   1430:     }
                   1431:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1432:     unless (defined($cached)) {
                   1433:         my %domconfig =
                   1434:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1435:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1436:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1172.2.75  raeburn  1437:         } else {
                   1438:             $domneedscache = $dom_in_use;
1.1129    raeburn  1439:         }
                   1440:     }
                   1441:     if (ref($result) eq 'HASH') {
1.1172.2.107  raeburn  1442:         ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12  raeburn  1443:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1444:         if ($is_balancer) {
                   1445:             if (ref($currrules) eq 'HASH') {
                   1446:                 if ($homeintdom) {
                   1447:                     if ($uname ne '') {
                   1448:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1449:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1450:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1451:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1452:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1453:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1454:                             }
                   1455:                         }
                   1456:                         if ($rule_in_effect eq '') {
                   1457:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1458:                             if ($userenv{'inststatus'} ne '') {
                   1459:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1460:                                 my ($othertitle,$usertypes,$types) =
                   1461:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1462:                                 if (ref($types) eq 'ARRAY') {
                   1463:                                     foreach my $type (@{$types}) {
                   1464:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1465:                                             if (exists($currrules->{$type})) {
                   1466:                                                 $rule_in_effect = $currrules->{$type};
                   1467:                                             }
                   1468:                                         }
                   1469:                                     }
                   1470:                                 }
                   1471:                             } else {
                   1472:                                 if (exists($currrules->{'default'})) {
                   1473:                                     $rule_in_effect = $currrules->{'default'};
                   1474:                                 }
                   1475:                             }
                   1476:                         }
                   1477:                     } else {
                   1478:                         if (exists($currrules->{'default'})) {
                   1479:                             $rule_in_effect = $currrules->{'default'};
                   1480:                         }
                   1481:                     }
                   1482:                 } else {
                   1483:                     if ($currrules->{'_LC_external'} ne '') {
                   1484:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1485:                     }
                   1486:                 }
                   1487:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1488:                                                        $uname,$udom);
                   1489:             }
                   1490:         }
                   1491:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35  raeburn  1492:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1493:         unless (defined($cached)) {
                   1494:             my %domconfig =
                   1495:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1496:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1172.2.75  raeburn  1497:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1498:             } else {
                   1499:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1500:             }
                   1501:         }
                   1502:         if (ref($result) eq 'HASH') {
1.1172.2.107  raeburn  1503:             ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12  raeburn  1504:                 &check_balancer_result($result,@hosts);
                   1505:             if ($is_balancer) {
1.1129    raeburn  1506:                 if (ref($currrules) eq 'HASH') {
                   1507:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1508:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1509:                     }
                   1510:                 }
                   1511:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1512:                                                        $uname,$udom);
                   1513:             }
                   1514:         } else {
                   1515:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1516:                 $is_balancer = 1;
                   1517:                 $offloadto = &this_host_spares($dom_in_use);
                   1518:             }
1.1172.2.75  raeburn  1519:             unless (defined($cached)) {
                   1520:                 $domneedscache = $serverhomedom;
                   1521:             }
1.1129    raeburn  1522:         }
                   1523:     } else {
                   1524:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1525:             $is_balancer = 1;
                   1526:             $offloadto = &this_host_spares($dom_in_use);
                   1527:         }
1.1172.2.75  raeburn  1528:         unless (defined($cached)) {
                   1529:             $domneedscache = $serverhomedom;
                   1530:         }
                   1531:     }
                   1532:     if ($domneedscache) {
                   1533:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1534:     }
1.1172.2.5  raeburn  1535:     if ($is_balancer) {
                   1536:         my $lowest_load = 30000;
                   1537:         if (ref($offloadto) eq 'HASH') {
                   1538:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1539:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1540:                     ($otherserver,$lowest_load) =
                   1541:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1542:                 }
1.1129    raeburn  1543:             }
1.1172.2.5  raeburn  1544:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1545: 
1.1172.2.5  raeburn  1546:             if (!$found_server) {
                   1547:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1548:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1549:                         ($otherserver,$lowest_load) =
                   1550:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1551:                     }
                   1552:                 }
                   1553:             }
                   1554:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1555:             if (@{$offloadto} == 1) {
                   1556:                 $otherserver = $offloadto->[0];
                   1557:             } elsif (@{$offloadto} > 1) {
                   1558:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1559:                     ($otherserver,$lowest_load) =
                   1560:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1561:                 }
                   1562:             }
                   1563:         }
1.1172.2.88  raeburn  1564:         unless ($caller eq 'login') {
                   1565:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1566:                 $is_balancer = 0;
                   1567:                 if ($uname ne '' && $udom ne '') {
                   1568:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1569:                         &appenv({'user.loadbalexempt'     => $lonhost,
                   1570:                                  'user.loadbalcheck.time' => time});
                   1571:                     }
1.1172.2.5  raeburn  1572:                 }
1.1129    raeburn  1573:             }
                   1574:         }
1.1172.2.107  raeburn  1575:         unless ($homeintdom) {
                   1576:             undef($setcookie);
                   1577:         }
1.1129    raeburn  1578:     }
1.1172.2.107  raeburn  1579:     return ($is_balancer,$otherserver,$setcookie);
1.1129    raeburn  1580: }
                   1581: 
1.1172.2.12  raeburn  1582: sub check_balancer_result {
                   1583:     my ($result,@hosts) = @_;
1.1172.2.107  raeburn  1584:     my ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12  raeburn  1585:     if (ref($result) eq 'HASH') {
                   1586:         if ($result->{'lonhost'} ne '') {
                   1587:             my $currbalancer = $result->{'lonhost'};
                   1588:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1589:                 $is_balancer = 1;
                   1590:                 $currtargets = $result->{'targets'};
                   1591:                 $currrules = $result->{'rules'};
                   1592:             }
                   1593:         } else {
                   1594:             foreach my $key (keys(%{$result})) {
                   1595:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1596:                     (ref($result->{$key}) eq 'HASH')) {
                   1597:                     $is_balancer = 1;
                   1598:                     $currrules = $result->{$key}{'rules'};
                   1599:                     $currtargets = $result->{$key}{'targets'};
1.1172.2.107  raeburn  1600:                     $setcookie = $result->{$key}{'cookie'};
1.1172.2.12  raeburn  1601:                     last;
                   1602:                 }
                   1603:             }
                   1604:         }
                   1605:     }
1.1172.2.107  raeburn  1606:     return ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12  raeburn  1607: }
                   1608: 
1.1129    raeburn  1609: sub get_loadbalancer_targets {
                   1610:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1611:     my $offloadto;
1.1172.2.4  raeburn  1612:     if ($rule_in_effect eq 'none') {
                   1613:         return [$perlvar{'lonHostID'}];
                   1614:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1615:         $offloadto = $currtargets;
                   1616:     } else {
                   1617:         if ($rule_in_effect eq 'homeserver') {
                   1618:             my $homeserver = &homeserver($uname,$udom);
                   1619:             if ($homeserver ne 'no_host') {
                   1620:                 $offloadto = [$homeserver];
                   1621:             }
                   1622:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1623:             my %domconfig =
                   1624:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1625:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1626:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1627:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1628:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1629:                     }
                   1630:                 }
                   1631:             } else {
1.1172.2.7  raeburn  1632:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1633:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1634:                 if (&hostname($remotebalancer) ne '') {
                   1635:                     $offloadto = [$remotebalancer];
                   1636:                 }
                   1637:             }
                   1638:         } elsif (&hostname($rule_in_effect) ne '') {
                   1639:             $offloadto = [$rule_in_effect];
                   1640:         }
                   1641:     }
                   1642:     return $offloadto;
                   1643: }
                   1644: 
1.1127    raeburn  1645: sub internet_dom_servers {
                   1646:     my ($dom) = @_;
                   1647:     my (%uniqservers,%servers);
                   1648:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1649:     my @machinedoms = &machine_domains($primaryserver);
                   1650:     foreach my $mdom (@machinedoms) {
                   1651:         my %currservers = %servers;
                   1652:         my %server = &get_servers($mdom);
                   1653:         %servers = (%currservers,%server);
                   1654:     }
                   1655:     my %by_hostname;
                   1656:     foreach my $id (keys(%servers)) {
                   1657:         push(@{$by_hostname{$servers{$id}}},$id);
                   1658:     }
                   1659:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1660:         if (@{$by_hostname{$hostname}} > 1) {
                   1661:             my $match = 0;
                   1662:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1663:                 if (&host_domain($id) eq $dom) {
                   1664:                     $uniqservers{$id} = $hostname;
                   1665:                     $match = 1;
                   1666:                 }
                   1667:             }
                   1668:             unless ($match) {
                   1669:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1670:             }
                   1671:         } else {
                   1672:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1673:         }
                   1674:     }
                   1675:     return %uniqservers;
                   1676: }
                   1677: 
1.1       albertel 1678: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1679: 
1.599     albertel 1680: my %homecache;
1.1       albertel 1681: sub homeserver {
1.230     stredwic 1682:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1683:     my $index="$uname:$udom";
1.426     albertel 1684: 
1.599     albertel 1685:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1686: 
                   1687:     my %servers = &get_servers($udom,'library');
                   1688:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1689:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1690: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1691: 
                   1692: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1693: 	if ($answer eq 'found') {
                   1694: 	    delete($badServerCache{$tryserver}); 
                   1695: 	    return $homecache{$index}=$tryserver;
                   1696: 	} elsif ($answer eq 'no_host') {
                   1697: 	    $badServerCache{$tryserver}=1;
                   1698: 	}
1.1       albertel 1699:     }    
                   1700:     return 'no_host';
1.70      www      1701: }
                   1702: 
                   1703: # ------------------------------------- Find the usernames behind a list of IDs
                   1704: 
                   1705: sub idget {
                   1706:     my ($udom,@ids)=@_;
                   1707:     my %returnhash=();
                   1708:     
1.841     albertel 1709:     my %servers = &get_servers($udom,'library');
                   1710:     foreach my $tryserver (keys(%servers)) {
1.1172.2.73  raeburn  1711: 	my $idlist=join('&', map { &escape($_); } @ids);
1.841     albertel 1712: 	$idlist=~tr/A-Z/a-z/; 
                   1713: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1714: 	my @answer=();
                   1715: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1716: 	    @answer=split(/\&/,$reply);
                   1717: 	}                    ;
                   1718: 	my $i;
                   1719: 	for ($i=0;$i<=$#ids;$i++) {
                   1720: 	    if ($answer[$i]) {
1.1172.2.73  raeburn  1721: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.841     albertel 1722: 	    } 
                   1723: 	}
                   1724:     } 
1.70      www      1725:     return %returnhash;
                   1726: }
                   1727: 
                   1728: # ------------------------------------- Find the IDs behind a list of usernames
                   1729: 
                   1730: sub idrget {
                   1731:     my ($udom,@unames)=@_;
                   1732:     my %returnhash=();
1.800     albertel 1733:     foreach my $uname (@unames) {
                   1734:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1735:     }
1.70      www      1736:     return %returnhash;
                   1737: }
                   1738: 
                   1739: # ------------------------------- Store away a list of names and associated IDs
                   1740: 
                   1741: sub idput {
                   1742:     my ($udom,%ids)=@_;
                   1743:     my %servers=();
1.800     albertel 1744:     foreach my $uname (keys(%ids)) {
                   1745: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1746:         my $uhom=&homeserver($uname,$udom);
1.70      www      1747:         if ($uhom ne 'no_host') {
1.800     albertel 1748:             my $id=&escape($ids{$uname});
1.70      www      1749:             $id=~tr/A-Z/a-z/;
1.800     albertel 1750:             my $esc_unam=&escape($uname);
1.70      www      1751: 	    if ($servers{$uhom}) {
1.800     albertel 1752: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1753:             } else {
1.800     albertel 1754:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1755:             }
                   1756:         }
1.191     harris41 1757:     }
1.800     albertel 1758:     foreach my $server (keys(%servers)) {
                   1759:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1760:     }
1.344     www      1761: }
                   1762: 
1.1172.2.30  raeburn  1763: # ---------------------------------------- Delete unwanted IDs from ids.db file
                   1764: 
                   1765: sub iddel {
                   1766:     my ($udom,$idshashref,$uhome)=@_;
                   1767:     my %result=();
                   1768:     unless (ref($idshashref) eq 'HASH') {
                   1769:         return %result;
                   1770:     }
                   1771:     my %servers=();
                   1772:     while (my ($id,$uname) = each(%{$idshashref})) {
                   1773:         my $uhom;
                   1774:         if ($uhome) {
                   1775:             $uhom = $uhome;
                   1776:         } else {
                   1777:             $uhom=&homeserver($uname,$udom);
                   1778:         }
                   1779:         if ($uhom ne 'no_host') {
                   1780:             if ($servers{$uhom}) {
                   1781:                 $servers{$uhom}.='&'.&escape($id);
                   1782:             } else {
                   1783:                 $servers{$uhom}=&escape($id);
                   1784:             }
                   1785:         }
                   1786:     }
                   1787:     foreach my $server (keys(%servers)) {
                   1788:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1789:     }
                   1790:     return %result;
                   1791: }
                   1792: 
1.1023    raeburn  1793: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1794: sub dump_dom {
1.1165    droeschl 1795:     my ($namespace, $udom, $regexp) = @_;
                   1796: 
                   1797:     $udom ||= $env{'user.domain'};
                   1798: 
                   1799:     return () unless $udom;
                   1800: 
                   1801:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1802: }
                   1803: 
1.1023    raeburn  1804: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1805: 
                   1806: sub get_dom {
1.860     raeburn  1807:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1172.2.57  raeburn  1808:     return if ($udom eq 'public');
1.806     raeburn  1809:     my $items='';
                   1810:     foreach my $item (@$storearr) {
                   1811:         $items.=&escape($item).'&';
                   1812:     }
                   1813:     $items=~s/\&$//;
1.860     raeburn  1814:     if (!$udom) {
                   1815:         $udom=$env{'user.domain'};
1.1172.2.57  raeburn  1816:         return if ($udom eq 'public');
1.860     raeburn  1817:         if (defined(&domain($udom,'primary'))) {
                   1818:             $uhome=&domain($udom,'primary');
                   1819:         } else {
1.874     albertel 1820:             undef($uhome);
1.860     raeburn  1821:         }
                   1822:     } else {
                   1823:         if (!$uhome) {
                   1824:             if (defined(&domain($udom,'primary'))) {
                   1825:                 $uhome=&domain($udom,'primary');
                   1826:             }
                   1827:         }
                   1828:     }
                   1829:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1830:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1831:         my %returnhash;
1.875     albertel 1832:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1833:             return %returnhash;
                   1834:         }
1.806     raeburn  1835:         my @pairs=split(/\&/,$rep);
                   1836:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1837:             return @pairs;
                   1838:         }
                   1839:         my $i=0;
                   1840:         foreach my $item (@$storearr) {
                   1841:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1842:             $i++;
                   1843:         }
                   1844:         return %returnhash;
                   1845:     } else {
1.880     banghart 1846:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1847:     }
                   1848: }
                   1849: 
                   1850: # -------------------------------------------- put items in domain db files 
                   1851: 
                   1852: sub put_dom {
1.860     raeburn  1853:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1854:     if (!$udom) {
                   1855:         $udom=$env{'user.domain'};
                   1856:         if (defined(&domain($udom,'primary'))) {
                   1857:             $uhome=&domain($udom,'primary');
                   1858:         } else {
1.874     albertel 1859:             undef($uhome);
1.860     raeburn  1860:         }
                   1861:     } else {
                   1862:         if (!$uhome) {
                   1863:             if (defined(&domain($udom,'primary'))) {
                   1864:                 $uhome=&domain($udom,'primary');
                   1865:             }
                   1866:         }
                   1867:     } 
                   1868:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1869:         my $items='';
                   1870:         foreach my $item (keys(%$storehash)) {
                   1871:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1872:         }
                   1873:         $items=~s/\&$//;
                   1874:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1875:     } else {
1.860     raeburn  1876:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1877:     }
                   1878: }
                   1879: 
1.1023    raeburn  1880: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1881: sub newput_dom {
1.1023    raeburn  1882:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1883:     my $result;
                   1884:     if (!$udom) {
                   1885:         $udom=$env{'user.domain'};
                   1886:     }
1.1023    raeburn  1887:     if ($udom) {
                   1888:         my $uname = &get_domainconfiguser($udom);
                   1889:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1890:     }
                   1891:     return $result;
                   1892: }
                   1893: 
1.1023    raeburn  1894: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1895: sub del_dom {
1.1023    raeburn  1896:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1897:     if (ref($storearr) eq 'ARRAY') {
                   1898:         if (!$udom) {
                   1899:             $udom=$env{'user.domain'};
                   1900:         }
1.1023    raeburn  1901:         if ($udom) {
                   1902:             my $uname = &get_domainconfiguser($udom); 
                   1903:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1904:         }
                   1905:     }
                   1906: }
                   1907: 
1.1023    raeburn  1908: # ----------------------------------construct domainconfig user for a domain 
                   1909: sub get_domainconfiguser {
                   1910:     my ($udom) = @_;
                   1911:     return $udom.'-domainconfig';
                   1912: }
                   1913: 
1.837     raeburn  1914: sub retrieve_inst_usertypes {
                   1915:     my ($udom) = @_;
                   1916:     my (%returnhash,@order);
1.989     raeburn  1917:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1918:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1919:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44  raeburn  1920:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  1921:     } else {
                   1922:         if (defined(&domain($udom,'primary'))) {
                   1923:             my $uhome=&domain($udom,'primary');
                   1924:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1925:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44  raeburn  1926:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  1927:                 return (\%returnhash,\@order);
                   1928:             }
                   1929:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1930:             my @pairs=split(/\&/,$hashitems);
                   1931:             foreach my $item (@pairs) {
                   1932:                 my ($key,$value)=split(/=/,$item,2);
                   1933:                 $key = &unescape($key);
                   1934:                 next if ($key =~ /^error: 2 /);
                   1935:                 $returnhash{$key}=&thaw_unescape($value);
                   1936:             }
                   1937:             my @esc_order = split(/\&/,$orderitems);
                   1938:             foreach my $item (@esc_order) {
                   1939:                 push(@order,&unescape($item));
                   1940:             }
                   1941:         } else {
1.1172.2.44  raeburn  1942:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  1943:         }
1.1172.2.44  raeburn  1944:         return (\%returnhash,\@order);
1.837     raeburn  1945:     }
                   1946: }
                   1947: 
1.868     raeburn  1948: sub is_domainimage {
                   1949:     my ($url) = @_;
1.1172.2.74  raeburn  1950:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  1951:         if (&domain($1) ne '') {
                   1952:             return '1';
                   1953:         }
                   1954:     }
                   1955:     return;
                   1956: }
                   1957: 
1.899     raeburn  1958: sub inst_directory_query {
                   1959:     my ($srch) = @_;
                   1960:     my $udom = $srch->{'srchdomain'};
                   1961:     my %results;
                   1962:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1963:     my $outcome;
1.899     raeburn  1964:     if ($homeserver ne '') {
1.904     albertel 1965: 	my $queryid=&reply("querysend:instdirsearch:".
                   1966: 			   &escape($srch->{'srchby'}).':'.
                   1967: 			   &escape($srch->{'srchterm'}).':'.
                   1968: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1969: 	my $host=&hostname($homeserver);
                   1970: 	if ($queryid !~/^\Q$host\E\_/) {
1.1172.2.96  raeburn  1971: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 1972: 	    return;
                   1973: 	}
                   1974: 	my $response = &get_query_reply($queryid);
                   1975: 	my $maxtries = 5;
                   1976: 	my $tries = 1;
                   1977: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1978: 	    $response = &get_query_reply($queryid);
                   1979: 	    $tries ++;
                   1980: 	}
                   1981: 
                   1982:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1983:             if ($response eq 'unavailable') {
                   1984:                 $outcome = $response;
                   1985:             } else {
                   1986:                 $outcome = 'ok';
                   1987:                 my @matches = split(/\n/,$response);
                   1988:                 foreach my $match (@matches) {
                   1989:                     my ($key,$value) = split(/=/,$match);
                   1990:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1991:                 }
1.899     raeburn  1992:             }
                   1993:         }
                   1994:     }
1.909     raeburn  1995:     return ($outcome,%results);
1.899     raeburn  1996: }
                   1997: 
                   1998: sub usersearch {
                   1999:     my ($srch) = @_;
                   2000:     my $dom = $srch->{'srchdomain'};
                   2001:     my %results;
                   2002:     my %libserv = &all_library();
                   2003:     my $query = 'usersearch';
                   2004:     foreach my $tryserver (keys(%libserv)) {
                   2005:         if (&host_domain($tryserver) eq $dom) {
                   2006:             my $host=&hostname($tryserver);
                   2007:             my $queryid=
1.911     raeburn  2008:                 &reply("querysend:".&escape($query).':'.
                   2009:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2010:                        &escape($srch->{'srchtype'}).':'.
                   2011:                        &escape($srch->{'srchterm'}),$tryserver);
                   2012:             if ($queryid !~/^\Q$host\E\_/) {
                   2013:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2014:                 next;
1.899     raeburn  2015:             }
                   2016:             my $reply = &get_query_reply($queryid);
                   2017:             my $maxtries = 1;
                   2018:             my $tries = 1;
                   2019:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2020:                 $reply = &get_query_reply($queryid);
                   2021:                 $tries ++;
                   2022:             }
                   2023:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2024:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2025:             } else {
1.911     raeburn  2026:                 my @matches;
                   2027:                 if ($reply =~ /\n/) {
                   2028:                     @matches = split(/\n/,$reply);
                   2029:                 } else {
                   2030:                     @matches = split(/\&/,$reply);
                   2031:                 }
1.899     raeburn  2032:                 foreach my $match (@matches) {
                   2033:                     my ($uname,$udom,%userhash);
1.911     raeburn  2034:                     foreach my $entry (split(/:/,$match)) {
                   2035:                         my ($key,$value) =
                   2036:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2037:                         $userhash{$key} = $value;
                   2038:                         if ($key eq 'username') {
                   2039:                             $uname = $value;
                   2040:                         } elsif ($key eq 'domain') {
                   2041:                             $udom = $value;
1.911     raeburn  2042:                         }
1.899     raeburn  2043:                     }
                   2044:                     $results{$uname.':'.$udom} = \%userhash;
                   2045:                 }
                   2046:             }
                   2047:         }
                   2048:     }
                   2049:     return %results;
                   2050: }
                   2051: 
1.912     raeburn  2052: sub get_instuser {
                   2053:     my ($udom,$uname,$id) = @_;
                   2054:     my $homeserver = &domain($udom,'primary');
                   2055:     my ($outcome,%results);
                   2056:     if ($homeserver ne '') {
                   2057:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2058:                            &escape($id).':'.&escape($udom),$homeserver);
                   2059:         my $host=&hostname($homeserver);
                   2060:         if ($queryid !~/^\Q$host\E\_/) {
                   2061:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2062:             return;
                   2063:         }
                   2064:         my $response = &get_query_reply($queryid);
                   2065:         my $maxtries = 5;
                   2066:         my $tries = 1;
                   2067:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2068:             $response = &get_query_reply($queryid);
                   2069:             $tries ++;
                   2070:         }
                   2071:         if (!&error($response) && $response ne 'refused') {
                   2072:             if ($response eq 'unavailable') {
                   2073:                 $outcome = $response;
                   2074:             } else {
                   2075:                 $outcome = 'ok';
                   2076:                 my @matches = split(/\n/,$response);
                   2077:                 foreach my $match (@matches) {
                   2078:                     my ($key,$value) = split(/=/,$match);
                   2079:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2080:                 }
                   2081:             }
                   2082:         }
                   2083:     }
                   2084:     my %userinfo;
                   2085:     if (ref($results{$uname}) eq 'HASH') {
                   2086:         %userinfo = %{$results{$uname}};
                   2087:     } 
                   2088:     return ($outcome,%userinfo);
                   2089: }
                   2090: 
1.1172.2.69  raeburn  2091: sub get_multiple_instusers {
                   2092:     my ($udom,$users,$caller) = @_;
                   2093:     my ($outcome,$results);
                   2094:     if (ref($users) eq 'HASH') {
                   2095:         my $count = keys(%{$users});
                   2096:         my $requested = &freeze_escape($users);
                   2097:         my $homeserver = &domain($udom,'primary');
                   2098:         if ($homeserver ne '') {
                   2099:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2100:             my $host=&hostname($homeserver);
                   2101:             if ($queryid !~/^\Q$host\E\_/) {
                   2102:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2103:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2104:                 return ($outcome,$results);
                   2105:             }
                   2106:             my $response = &get_query_reply($queryid);
                   2107:             my $maxtries = 5;
                   2108:             if ($count > 100) {
                   2109:                 $maxtries = 1+int($count/20);
                   2110:             }
                   2111:             my $tries = 1;
                   2112:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2113:                 $response = &get_query_reply($queryid);
                   2114:                 $tries ++;
                   2115:             }
                   2116:             if ($response eq '') {
                   2117:                 $results = {};
                   2118:                 foreach my $key (keys(%{$users})) {
                   2119:                     my ($uname,$id);
                   2120:                     if ($caller eq 'id') {
                   2121:                         $id = $key;
                   2122:                     } else {
                   2123:                         $uname = $key;
                   2124:                     }
                   2125:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
                   2126:                     $outcome = $resp;
                   2127:                     if ($resp eq 'ok') {
                   2128:                         %{$results} = (%{$results}, %info);
                   2129:                     } else {
                   2130:                         last;
                   2131:                     }
                   2132:                 }
                   2133:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2134:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2135:                     $outcome = $response;
                   2136:                 } else {
                   2137:                     ($outcome,my $userdata) = split(/=/,$response,2);
                   2138:                     if ($outcome eq 'ok') {
                   2139:                         $results = &thaw_unescape($userdata);
                   2140:                     }
                   2141:                 }
                   2142:             }
                   2143:         }
                   2144:     }
                   2145:     return ($outcome,$results);
                   2146: }
                   2147: 
1.912     raeburn  2148: sub inst_rulecheck {
1.923     raeburn  2149:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2150:     my %returnhash;
                   2151:     if ($udom ne '') {
                   2152:         if (ref($rules) eq 'ARRAY') {
                   2153:             @{$rules} = map {&escape($_);} (@{$rules});
                   2154:             my $rulestr = join(':',@{$rules});
                   2155:             my $homeserver=&domain($udom,'primary');
                   2156:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2157:                 my $response;
                   2158:                 if ($item eq 'username') {                
                   2159:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2160:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2161:                                               $homeserver));
1.923     raeburn  2162:                 } elsif ($item eq 'id') {
                   2163:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2164:                                               ':'.&escape($id).':'.$rulestr,
                   2165:                                               $homeserver));
1.945     raeburn  2166:                 } elsif ($item eq 'selfcreate') {
                   2167:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2168:                                                &escape($udom).':'.&escape($uname).
                   2169:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2170:                 }
1.912     raeburn  2171:                 if ($response ne 'refused') {
                   2172:                     my @pairs=split(/\&/,$response);
                   2173:                     foreach my $item (@pairs) {
                   2174:                         my ($key,$value)=split(/=/,$item,2);
                   2175:                         $key = &unescape($key);
                   2176:                         next if ($key =~ /^error: 2 /);
                   2177:                         $returnhash{$key}=&thaw_unescape($value);
                   2178:                     }
                   2179:                 }
                   2180:             }
                   2181:         }
                   2182:     }
                   2183:     return %returnhash;
                   2184: }
                   2185: 
                   2186: sub inst_userrules {
1.923     raeburn  2187:     my ($udom,$check) = @_;
1.912     raeburn  2188:     my (%ruleshash,@ruleorder);
                   2189:     if ($udom ne '') {
                   2190:         my $homeserver=&domain($udom,'primary');
                   2191:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2192:             my $response;
                   2193:             if ($check eq 'id') {
                   2194:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2195:                                  $homeserver);
1.943     raeburn  2196:             } elsif ($check eq 'email') {
                   2197:                 $response=&reply('instemailrules:'.&escape($udom),
                   2198:                                  $homeserver);
1.923     raeburn  2199:             } else {
                   2200:                 $response=&reply('instuserrules:'.&escape($udom),
                   2201:                                  $homeserver);
                   2202:             }
1.912     raeburn  2203:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2204:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2205:                 ($response ne 'no_such_host')) {
                   2206:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2207:                 my @pairs=split(/\&/,$hashitems);
                   2208:                 foreach my $item (@pairs) {
                   2209:                     my ($key,$value)=split(/=/,$item,2);
                   2210:                     $key = &unescape($key);
                   2211:                     next if ($key =~ /^error: 2 /);
                   2212:                     $ruleshash{$key}=&thaw_unescape($value);
                   2213:                 }
                   2214:                 my @esc_order = split(/\&/,$orderitems);
                   2215:                 foreach my $item (@esc_order) {
                   2216:                     push(@ruleorder,&unescape($item));
                   2217:                 }
                   2218:             }
                   2219:         }
                   2220:     }
                   2221:     return (\%ruleshash,\@ruleorder);
                   2222: }
                   2223: 
1.976     raeburn  2224: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2225: 
                   2226: sub get_domain_defaults {
1.1172.2.35  raeburn  2227:     my ($domain,$ignore_cache) = @_;
                   2228:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2229:     my $cachetime = 60*60*24;
1.1172.2.35  raeburn  2230:     unless ($ignore_cache) {
                   2231:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2232:         if (defined($cached)) {
                   2233:             if (ref($result) eq 'HASH') {
                   2234:                 return %{$result};
                   2235:             }
1.943     raeburn  2236:         }
                   2237:     }
                   2238:     my %domdefaults;
                   2239:     my %domconfig =
1.989     raeburn  2240:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2241:                                   'requestcourses','inststatus',
1.1172.2.9  raeburn  2242:                                   'coursedefaults','usersessions',
1.1172.2.46  raeburn  2243:                                   'requestauthor','selfenrollment',
1.1172.2.89  raeburn  2244:                                   'coursecategories','autoenroll',
                   2245:                                   'helpsettings'],$domain);
1.1172.2.41  raeburn  2246:     my @coursetypes = ('official','unofficial','community','textbook');
1.943     raeburn  2247:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2248:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2249:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2250:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2251:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2252:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2253:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1172.2.91  raeburn  2254:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2255:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2256:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943     raeburn  2257:     } else {
                   2258:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2259:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2260:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2261:     }
1.976     raeburn  2262:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2263:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2264:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2265:         } else {
                   2266:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29  raeburn  2267:         }
1.1172.2.6  raeburn  2268:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2269:         foreach my $item (@usertools) {
                   2270:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2271:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2272:             }
                   2273:         }
1.1172.2.29  raeburn  2274:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2275:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2276:         }
1.976     raeburn  2277:     }
1.985     raeburn  2278:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37  raeburn  2279:         foreach my $item ('official','unofficial','community','textbook') {
1.985     raeburn  2280:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2281:         }
                   2282:     }
1.1172.2.9  raeburn  2283:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2284:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2285:     }
1.989     raeburn  2286:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44  raeburn  2287:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2288:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2289:         }
                   2290:     }
1.1047    raeburn  2291:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60  raeburn  2292:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2293:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2294:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2295:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2296:         }
1.1172.2.41  raeburn  2297:         foreach my $type (@coursetypes) {
                   2298:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2299:                 unless ($type eq 'community') {
                   2300:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2301:                 }
                   2302:             }
                   2303:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2304:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2305:             }
1.1172.2.60  raeburn  2306:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2307:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2308:                     $domdefaults{$type.'postsubtimeout'} =
                   2309:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
                   2310:                 }
                   2311:             }
1.1172.2.30  raeburn  2312:         }
1.1172.2.67  raeburn  2313:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2314:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2315:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2316:                 if (@clonecodes) {
                   2317:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2318:                 }
                   2319:             }
                   2320:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2321:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2322:         }
1.1172.2.103  raeburn  2323:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2324:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
                   2325:         }
1.1047    raeburn  2326:     }
1.1073    raeburn  2327:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2328:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2329:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2330:         }
                   2331:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2332:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2333:         }
1.1172.2.62  raeburn  2334:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2335:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2336:         }
1.1073    raeburn  2337:     }
1.1172.2.41  raeburn  2338:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2339:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2340:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2341:                             'approval','limit');
                   2342:             foreach my $type (@coursetypes) {
                   2343:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2344:                     my @mgrdc = ();
                   2345:                     foreach my $item (@settings) {
                   2346:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2347:                             push(@mgrdc,$item);
                   2348:                         }
                   2349:                     }
                   2350:                     if (@mgrdc) {
                   2351:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2352:                     }
                   2353:                 }
                   2354:             }
                   2355:         }
                   2356:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2357:             foreach my $type (@coursetypes) {
                   2358:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2359:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2360:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2361:                     }
                   2362:                 }
                   2363:             }
                   2364:         }
                   2365:     }
1.1172.2.46  raeburn  2366:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2367:         $domdefaults{'catauth'} = 'std';
                   2368:         $domdefaults{'catunauth'} = 'std';
                   2369:         if ($domconfig{'coursecategories'}{'auth'}) {
                   2370:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2371:         }
                   2372:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2373:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2374:         }
                   2375:     }
1.1172.2.76  raeburn  2376:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2377:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2378:     }
1.1172.2.89  raeburn  2379:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2380:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2381:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2382:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2383:         }
                   2384:     }
1.1172.2.23  raeburn  2385:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2386:     return %domdefaults;
                   2387: }
                   2388: 
1.1172.2.106  raeburn  2389: sub get_dom_cats {
                   2390:     my ($dom) = @_;
                   2391:     return unless (&domain($dom));
                   2392:     my ($cats,$cached)=&is_cached_new('cats',$dom);
                   2393:     unless (defined($cached)) {
                   2394:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
                   2395:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2396:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
                   2397:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
                   2398:             } else {
                   2399:                 $cats = {};
                   2400:             }
                   2401:         } else {
                   2402:             $cats = {};
                   2403:         }
                   2404:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
                   2405:     }
                   2406:     return $cats;
                   2407: }
                   2408: 
                   2409: sub get_dom_instcats {
                   2410:     my ($dom) = @_;
                   2411:     return unless (&domain($dom));
                   2412:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
                   2413:     unless (defined($cached)) {
                   2414:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
                   2415:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
                   2416:         if ($totcodes > 0) {
                   2417:             my $caller = 'global';
                   2418:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
                   2419:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
                   2420:                 $instcats = {
                   2421:                                 codes => \%codes,
                   2422:                                 codetitles => \@codetitles,
                   2423:                                 cat_titles => \%cat_titles,
                   2424:                                 cat_order => \%cat_order,
                   2425:                             };
                   2426:                 &do_cache_new('instcats',$dom,$instcats,3600);
                   2427:             }
                   2428:         }
                   2429:     }
                   2430:     return $instcats;
                   2431: }
                   2432: 
                   2433: sub retrieve_instcodes {
                   2434:     my ($coursecodes,$dom) = @_;
                   2435:     my $totcodes;
                   2436:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
                   2437:     foreach my $course (keys(%courses)) {
                   2438:         if (ref($courses{$course}) eq 'HASH') {
                   2439:             if ($courses{$course}{'inst_code'} ne '') {
                   2440:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
                   2441:                 $totcodes ++;
                   2442:             }
                   2443:         }
                   2444:     }
                   2445:     return $totcodes;
                   2446: }
                   2447: 
1.344     www      2448: # --------------------------------------------------- Assign a key to a student
                   2449: 
                   2450: sub assign_access_key {
1.364     www      2451: #
                   2452: # a valid key looks like uname:udom#comments
                   2453: # comments are being appended
                   2454: #
1.498     www      2455:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2456:     $kdom=
1.620     albertel 2457:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2458:     $knum=
1.620     albertel 2459:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2460:     $cdom=
1.620     albertel 2461:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2462:     $cnum=
1.620     albertel 2463:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2464:     $udom=$env{'user.name'} unless (defined($udom));
                   2465:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2466:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2467:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2468:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2469:                                                   # assigned to this person
                   2470:                                                   # - this should not happen,
1.345     www      2471:                                                   # unless something went wrong
                   2472:                                                   # the first time around
                   2473: # ready to assign
1.364     www      2474:         $logentry=$1.'; '.$logentry;
1.496     www      2475:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2476:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2477: # key now belongs to user
1.346     www      2478: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2479:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2480:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2481:                 return 'ok';
                   2482:             } else {
                   2483:                 return 
                   2484:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2485: 	    }
                   2486:         } else {
                   2487:             return 'error: Could not assign key, try again later.';
                   2488:         }
1.364     www      2489:     } elsif (!$existing{$ckey}) {
1.345     www      2490: # the key does not exist
                   2491: 	return 'error: The key does not exist';
                   2492:     } else {
                   2493: # the key is somebody else's
                   2494: 	return 'error: The key is already in use';
                   2495:     }
1.344     www      2496: }
                   2497: 
1.364     www      2498: # ------------------------------------------ put an additional comment on a key
                   2499: 
                   2500: sub comment_access_key {
                   2501: #
                   2502: # a valid key looks like uname:udom#comments
                   2503: # comments are being appended
                   2504: #
                   2505:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2506:     $cdom=
1.620     albertel 2507:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2508:     $cnum=
1.620     albertel 2509:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2510:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2511:     if ($existing{$ckey}) {
                   2512:         $existing{$ckey}.='; '.$logentry;
                   2513: # ready to assign
1.367     www      2514:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2515:                                                  $cdom,$cnum) eq 'ok') {
                   2516: 	    return 'ok';
                   2517:         } else {
                   2518: 	    return 'error: Count not store comment.';
                   2519:         }
                   2520:     } else {
                   2521: # the key does not exist
                   2522: 	return 'error: The key does not exist';
                   2523:     }
                   2524: }
                   2525: 
1.344     www      2526: # ------------------------------------------------------ Generate a set of keys
                   2527: 
                   2528: sub generate_access_keys {
1.364     www      2529:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2530:     $cdom=
1.620     albertel 2531:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2532:     $cnum=
1.620     albertel 2533:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2534:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2535:     unless (($cdom) && ($cnum)) { return 0; }
                   2536:     if ($number>10000) { return 0; }
                   2537:     sleep(2); # make sure don't get same seed twice
                   2538:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2539:     my $total=0;
                   2540:     for (my $i=1;$i<=$number;$i++) {
                   2541:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2542:                   sprintf("%lx",int(100000*rand)).'-'.
                   2543:                   sprintf("%lx",int(100000*rand));
                   2544:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2545:        $newkey=~s/0/h/g; # and also 0 and O
                   2546:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2547:        if ($existing{$newkey}) {
                   2548:            $i--;
                   2549:        } else {
1.364     www      2550: 	  if (&put('accesskeys',
                   2551:               { $newkey => '# generated '.localtime().
1.620     albertel 2552:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2553:                            '; '.$logentry },
                   2554: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2555:               $total++;
                   2556: 	  }
                   2557:        }
                   2558:     }
1.620     albertel 2559:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2560:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2561:     return $total;
                   2562: }
                   2563: 
                   2564: # ------------------------------------------------------- Validate an accesskey
                   2565: 
                   2566: sub validate_access_key {
                   2567:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2568:     $cdom=
1.620     albertel 2569:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2570:     $cnum=
1.620     albertel 2571:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2572:     $udom=$env{'user.domain'} unless (defined($udom));
                   2573:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2574:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2575:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2576: }
                   2577: 
                   2578: # ------------------------------------- Find the section of student in a course
1.652     albertel 2579: sub devalidate_getsection_cache {
                   2580:     my ($udom,$unam,$courseid)=@_;
                   2581:     my $hashid="$udom:$unam:$courseid";
                   2582:     &devalidate_cache_new('getsection',$hashid);
                   2583: }
1.298     matthew  2584: 
1.815     albertel 2585: sub courseid_to_courseurl {
                   2586:     my ($courseid) = @_;
                   2587:     #already url style courseid
                   2588:     return $courseid if ($courseid =~ m{^/});
                   2589: 
                   2590:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2591: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2592: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2593: 	return "/$cdom/$cnum";
                   2594:     }
                   2595: 
                   2596:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2597:     if (exists($courseinfo{'num'})) {
                   2598: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2599:     }
                   2600: 
                   2601:     return undef;
                   2602: }
                   2603: 
1.298     matthew  2604: sub getsection {
                   2605:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2606:     my $cachetime=1800;
1.551     albertel 2607: 
                   2608:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2609:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2610:     if (defined($cached)) { return $result; }
                   2611: 
1.298     matthew  2612:     my %Pending; 
                   2613:     my %Expired;
                   2614:     #
                   2615:     # Each role can either have not started yet (pending), be active, 
                   2616:     #    or have expired.
                   2617:     #
                   2618:     # If there is an active role, we are done.
                   2619:     #
                   2620:     # If there is more than one role which has not started yet, 
                   2621:     #     choose the one which will start sooner
                   2622:     # If there is one role which has not started yet, return it.
                   2623:     #
                   2624:     # If there is more than one expired role, choose the one which ended last.
                   2625:     # If there is a role which has expired, return it.
                   2626:     #
1.815     albertel 2627:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2628:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2629:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2630:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2631:         my $section=$1;
                   2632:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2633:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2634:         my $now=time;
1.548     albertel 2635:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2636:             $Expired{$end}=$section;
                   2637:             next;
                   2638:         }
1.548     albertel 2639:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2640:             $Pending{$start}=$section;
                   2641:             next;
                   2642:         }
1.599     albertel 2643:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2644:     }
                   2645:     #
                   2646:     # Presumedly there will be few matching roles from the above
                   2647:     # loop and the sorting time will be negligible.
                   2648:     if (scalar(keys(%Pending))) {
                   2649:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2650:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2651:     } 
                   2652:     if (scalar(keys(%Expired))) {
                   2653:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2654:         my $time = pop(@sorted);
1.599     albertel 2655:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2656:     }
1.599     albertel 2657:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2658: }
1.70      www      2659: 
1.599     albertel 2660: sub save_cache {
                   2661:     &purge_remembered();
1.722     albertel 2662:     #&Apache::loncommon::validate_page();
1.620     albertel 2663:     undef(%env);
1.780     albertel 2664:     undef($env_loaded);
1.599     albertel 2665: }
1.452     albertel 2666: 
1.599     albertel 2667: my $to_remember=-1;
                   2668: my %remembered;
                   2669: my %accessed;
                   2670: my $kicks=0;
                   2671: my $hits=0;
1.849     albertel 2672: sub make_key {
                   2673:     my ($name,$id) = @_;
1.872     albertel 2674:     if (length($id) > 65 
                   2675: 	&& length(&escape($id)) > 200) {
                   2676: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2677:     }
1.849     albertel 2678:     return &escape($name.':'.$id);
                   2679: }
                   2680: 
1.599     albertel 2681: sub devalidate_cache_new {
                   2682:     my ($name,$id,$debug) = @_;
                   2683:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81  raeburn  2684:     my $remembered_id=$name.':'.$id;
1.849     albertel 2685:     $id=&make_key($name,$id);
1.599     albertel 2686:     $memcache->delete($id);
1.1172.2.81  raeburn  2687:     delete($remembered{$remembered_id});
                   2688:     delete($accessed{$remembered_id});
1.599     albertel 2689: }
                   2690: 
                   2691: sub is_cached_new {
                   2692:     my ($name,$id,$debug) = @_;
1.1172.2.81  raeburn  2693:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for 
                   2694:                                      # keys in %remembered hash, which persists for
                   2695:                                      # duration of request (no restriction on key length).
                   2696:     if (exists($remembered{$remembered_id})) {
                   2697: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2698: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2699: 	$hits++;
1.1172.2.81  raeburn  2700: 	return ($remembered{$remembered_id},1);
1.599     albertel 2701:     }
1.1172.2.81  raeburn  2702:     $id=&make_key($name,$id);
1.599     albertel 2703:     my $value = $memcache->get($id);
                   2704:     if (!(defined($value))) {
                   2705: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2706: 	return (undef,undef);
1.416     albertel 2707:     }
1.599     albertel 2708:     if ($value eq '__undef__') {
                   2709: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2710: 	$value=undef;
                   2711:     }
1.1172.2.81  raeburn  2712:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2713:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2714:     return ($value,1);
                   2715: }
                   2716: 
                   2717: sub do_cache_new {
                   2718:     my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81  raeburn  2719:     my $remembered_id=$name.':'.$id;
1.849     albertel 2720:     $id=&make_key($name,$id);
1.599     albertel 2721:     my $setvalue=$value;
                   2722:     if (!defined($setvalue)) {
                   2723: 	$setvalue='__undef__';
                   2724:     }
1.623     albertel 2725:     if (!defined($time) ) {
                   2726: 	$time=600;
                   2727:     }
1.599     albertel 2728:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2729:     my $result = $memcache->set($id,$setvalue,$time);
                   2730:     if (! $result) {
1.872     albertel 2731: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2732: 	$memcache->disconnect_all();
1.872     albertel 2733:     }
1.600     albertel 2734:     # need to make a copy of $value
1.1172.2.81  raeburn  2735:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2736:     return $value;
                   2737: }
                   2738: 
                   2739: sub make_room {
1.1172.2.81  raeburn  2740:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 2741: 
1.1172.2.81  raeburn  2742:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 2743:                                     : $value;
1.599     albertel 2744:     if ($to_remember<0) { return; }
1.1172.2.81  raeburn  2745:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2746:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2747:     my $to_kick;
                   2748:     my $max_time=0;
                   2749:     foreach my $other (keys(%accessed)) {
                   2750: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2751: 	    $to_kick=$other;
                   2752: 	    $max_time=&tv_interval($accessed{$other});
                   2753: 	}
                   2754:     }
                   2755:     delete($remembered{$to_kick});
                   2756:     delete($accessed{$to_kick});
                   2757:     $kicks++;
                   2758:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2759:     return;
                   2760: }
                   2761: 
1.599     albertel 2762: sub purge_remembered {
1.604     albertel 2763:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2764:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2765:     undef(%remembered);
                   2766:     undef(%accessed);
1.428     albertel 2767: }
1.70      www      2768: # ------------------------------------- Read an entry from a user's environment
                   2769: 
                   2770: sub userenvironment {
                   2771:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2772:     my $items;
                   2773:     foreach my $item (@what) {
                   2774:         $items.=&escape($item).'&';
                   2775:     }
                   2776:     $items=~s/\&$//;
1.70      www      2777:     my %returnhash=();
1.1009    raeburn  2778:     my $uhome = &homeserver($unam,$udom);
                   2779:     unless ($uhome eq 'no_host') {
                   2780:         my @answer=split(/\&/, 
                   2781:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2782:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2783:             return %returnhash;
                   2784:         }
1.1009    raeburn  2785:         my $i;
                   2786:         for ($i=0;$i<=$#what;$i++) {
                   2787: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2788:         }
1.70      www      2789:     }
                   2790:     return %returnhash;
1.1       albertel 2791: }
                   2792: 
1.617     albertel 2793: # ---------------------------------------------------------- Get a studentphoto
                   2794: sub studentphoto {
                   2795:     my ($udom,$unam,$ext) = @_;
                   2796:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2797:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2798:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2799:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2800:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2801:             } else {
                   2802:                 my ($result,$perm_reqd)=
1.707     albertel 2803: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2804:                 if ($result eq 'ok') {
                   2805:                     if (!($perm_reqd eq 'yes')) {
                   2806:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2807:                     }
                   2808:                 }
                   2809:             }
                   2810:         }
                   2811:     } else {
                   2812:         my ($result,$perm_reqd) = 
1.707     albertel 2813: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2814:         if ($result eq 'ok') {
                   2815:             if (!($perm_reqd eq 'yes')) {
                   2816:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2817:             }
                   2818:         }
                   2819:     }
                   2820:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2821: }
                   2822: 
                   2823: sub retrievestudentphoto {
                   2824:     my ($udom,$unam,$ext,$type) = @_;
                   2825:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2826:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2827:     if ($ret eq 'ok') {
                   2828:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2829:         if ($type eq 'thumbnail') {
                   2830:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2831:         }
                   2832:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2833:         return $tokenurl;
                   2834:     } else {
                   2835:         if ($type eq 'thumbnail') {
                   2836:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2837:         } else { 
                   2838:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2839:         }
1.617     albertel 2840:     }
                   2841: }
                   2842: 
1.263     www      2843: # -------------------------------------------------------------------- New chat
                   2844: 
                   2845: sub chatsend {
1.724     raeburn  2846:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2847:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2848:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2849:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2850:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2851: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2852: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2853: }
                   2854: 
                   2855: # ------------------------------------------ Find current version of a resource
                   2856: 
                   2857: sub getversion {
                   2858:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  2859:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2860:     return &currentversion(&filelocation('',$fname));
                   2861: }
                   2862: 
                   2863: sub currentversion {
                   2864:     my $fname=shift;
                   2865:     my $author=$fname;
                   2866:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2867:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2868:     my $home=&homeserver($uname,$udom);
1.292     www      2869:     if ($home eq 'no_host') { 
                   2870:         return -1; 
                   2871:     }
1.1112    www      2872:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2873:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2874: 	return -1;
                   2875:     }
1.1112    www      2876:     return $answer;
1.263     www      2877: }
                   2878: 
1.1111    www      2879: #
                   2880: # Return special version number of resource if set by override, empty otherwise
                   2881: #
                   2882: sub usedversion {
                   2883:     my $fname=shift;
                   2884:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2885:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2886:     if ($urlversion) { return $urlversion; }
                   2887:     return '';
                   2888: }
                   2889: 
1.1       albertel 2890: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2891: 
1.1       albertel 2892: sub subscribe {
                   2893:     my $fname=shift;
1.761     raeburn  2894:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2895:     $fname=~s/[\n\r]//g;
1.1       albertel 2896:     my $author=$fname;
                   2897:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2898:     my ($udom,$uname)=split(/\//,$author);
                   2899:     my $home=homeserver($uname,$udom);
1.335     albertel 2900:     if ($home eq 'no_host') {
                   2901:         return 'not_found';
1.1       albertel 2902:     }
                   2903:     my $answer=reply("sub:$fname",$home);
1.64      www      2904:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2905: 	$answer.=' by '.$home;
                   2906:     }
1.1       albertel 2907:     return $answer;
                   2908: }
                   2909:     
1.8       www      2910: # -------------------------------------------------------------- Replicate file
                   2911: 
                   2912: sub repcopy {
                   2913:     my $filename=shift;
1.23      www      2914:     $filename=~s/\/+/\//g;
1.1142    raeburn  2915:     my $londocroot = $perlvar{'lonDocRoot'};
                   2916:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2917:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2918:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2919: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2920: 	return &repcopy_userfile($filename);
                   2921:     }
1.532     albertel 2922:     $filename=~s/[\n\r]//g;
1.8       www      2923:     my $transname="$filename.in.transfer";
1.828     www      2924: # FIXME: this should flock
1.607     raeburn  2925:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2926:     my $remoteurl=subscribe($filename);
1.64      www      2927:     if ($remoteurl =~ /^con_lost by/) {
                   2928: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2929:            return 'unavailable';
1.8       www      2930:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2931: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2932: 	   return 'not_found';
1.64      www      2933:     } elsif ($remoteurl =~ /^rejected by/) {
                   2934: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2935:            return 'forbidden';
1.20      www      2936:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2937:            return 'ok';
1.8       www      2938:     } else {
1.290     www      2939:         my $author=$filename;
                   2940:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2941:         my ($udom,$uname)=split(/\//,$author);
                   2942:         my $home=homeserver($uname,$udom);
                   2943:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2944:            my @parts=split(/\//,$filename);
                   2945:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2946:            if ($path ne "$londocroot/res") {
1.8       www      2947:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2948: 	       return 'bad_request';
1.8       www      2949:            }
                   2950:            my $count;
                   2951:            for ($count=5;$count<$#parts;$count++) {
                   2952:                $path.="/$parts[$count]";
                   2953:                if ((-e $path)!=1) {
                   2954: 		   mkdir($path,0777);
                   2955:                }
                   2956:            }
                   2957:            my $ua=new LWP::UserAgent;
                   2958:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2959:            my $response=$ua->request($request,$transname);
                   2960:            if ($response->is_error()) {
                   2961: 	       unlink($transname);
                   2962:                my $message=$response->status_line;
1.672     albertel 2963:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2964:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2965:                return 'unavailable';
1.8       www      2966:            } else {
1.16      www      2967: 	       if ($remoteurl!~/\.meta$/) {
                   2968:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2969:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2970:                   if ($mresponse->is_error()) {
                   2971: 		      unlink($filename.'.meta');
                   2972:                       &logthis(
1.672     albertel 2973:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2974:                   }
                   2975: 	       }
1.8       www      2976:                rename($transname,$filename);
1.607     raeburn  2977:                return 'ok';
1.8       www      2978:            }
1.290     www      2979:        }
1.8       www      2980:     }
1.330     www      2981: }
                   2982: 
                   2983: # ------------------------------------------------ Get server side include body
                   2984: sub ssi_body {
1.381     albertel 2985:     my ($filelink,%form)=@_;
1.606     matthew  2986:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2987:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2988:     }
1.953     www      2989:     my $output='';
                   2990:     my $response;
1.980     raeburn  2991:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2992:        ($output,$response)=&externalssi($filelink);
1.953     www      2993:     } else {
1.1004    droeschl 2994:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2995:        $filelink .= 'inhibitmenu=yes';
1.953     www      2996:        ($output,$response)=&ssi($filelink,%form);
                   2997:     }
1.778     albertel 2998:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2999:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3000:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3001:     if (wantarray) {
                   3002:         return ($output, $response);
                   3003:     } else {
                   3004:         return $output;
                   3005:     }
1.8       www      3006: }
                   3007: 
1.15      www      3008: # --------------------------------------------------------- Server Side Include
                   3009: 
1.782     albertel 3010: sub absolute_url {
                   3011:     my ($host_name) = @_;
                   3012:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3013:     if ($host_name eq '') {
                   3014: 	$host_name = $ENV{'SERVER_NAME'};
                   3015:     }
                   3016:     return $protocol.$host_name;
                   3017: }
                   3018: 
1.942     foxr     3019: #
                   3020: #   Server side include.
                   3021: # Parameters:
                   3022: #  fn     Possibly encrypted resource name/id.
                   3023: #  form   Hash that describes how the rendering should be done
                   3024: #         and other things.
1.944     foxr     3025: # Returns:
1.950     raeburn  3026: #   Scalar context: The content of the response.
                   3027: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3028: #     
1.15      www      3029: sub ssi {
                   3030: 
1.944     foxr     3031:     my ($fn,%form)=@_;
1.1172.2.100  raeburn  3032:     my ($request,$response);
1.711     albertel 3033: 
                   3034:     $form{'no_update_last_known'}=1;
1.895     albertel 3035:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3036:     if (%form) {
1.782     albertel 3037:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1172.2.58  raeburn  3038:       $request->content(join('&',map {
                   3039:             my $name = escape($_);
                   3040:             "$name=" . ( ref($form{$_}) eq 'ARRAY'
                   3041:             ? join("&$name=", map {escape($_) } @{$form{$_}})
                   3042:             : &escape($form{$_}) );
                   3043:         } keys(%form)));
1.23      www      3044:     } else {
1.782     albertel 3045:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      3046:     }
                   3047: 
1.15      www      3048:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.100  raeburn  3049: 
1.1172.2.101  raeburn  3050:     if (($env{'request.course.id'}) &&
                   3051:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
                   3052:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
                   3053:         ($form{'grade_symb'} ne '') &&
                   3054:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
                   3055:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
1.1172.2.100  raeburn  3056:         if (LWP::UserAgent->VERSION >= 5.834) {
                   3057:             my $ua=new LWP::UserAgent;
                   3058:             $ua->local_address('127.0.0.1');
                   3059:             $response = $ua->request($request);
                   3060:         } else {
                   3061:             {
                   3062:                 require LWP::Protocol::http;
                   3063:                 local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => '127.0.0.1');
                   3064:                 my $ua=new LWP::UserAgent;
                   3065:                 $response = $ua->request($request);
                   3066:                 @LWP::Protocol::http::EXTRA_SOCK_OPTS = ();
                   3067:             }
                   3068:         }
                   3069:     } else {
                   3070:         my $ua=new LWP::UserAgent;
                   3071:         $response = $ua->request($request);
                   3072:     }
1.944     foxr     3073:     if (wantarray) {
1.1172.2.3  raeburn  3074: 	return ($response->content, $response);
1.944     foxr     3075:     } else {
1.1172.2.3  raeburn  3076: 	return $response->content;
1.942     foxr     3077:     }
1.324     www      3078: }
                   3079: 
                   3080: sub externalssi {
                   3081:     my ($url)=@_;
                   3082:     my $ua=new LWP::UserAgent;
                   3083:     my $request=new HTTP::Request('GET',$url);
                   3084:     my $response=$ua->request($request);
1.954     raeburn  3085:     if (wantarray) {
                   3086:         return ($response->content, $response);
                   3087:     } else {
                   3088:         return $response->content;
                   3089:     }
1.15      www      3090: }
1.254     www      3091: 
1.1172.2.98  raeburn  3092: # If the local copy of a replicated resource is outdated, trigger a
                   3093: # connection from the homeserver to flush the delayed queue. If no update
                   3094: # happens, remove local copies of outdated resource (and corresponding
                   3095: # metadata file).
                   3096: 
                   3097: sub remove_stale_resfile {
                   3098:     my ($url) = @_;
                   3099:     my $removed;
                   3100:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3101:         my $audom = $1;
                   3102:         my $auname = $2;
                   3103:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
                   3104:             my $homeserver = &homeserver($auname,$audom);
                   3105:             unless (($homeserver eq 'no_host') ||
                   3106:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3107:                 my $fname = &filelocation('',$url);
                   3108:                 if (-e $fname) {
                   3109:                     my $ua=new LWP::UserAgent;
                   3110:                     $ua->timeout(5);
                   3111:                     my $protocol = $protocol{$homeserver};
                   3112:                     $protocol = 'http' if ($protocol ne 'https');
                   3113:                     my $hostname = &hostname($homeserver);
                   3114:                     if ($hostname) {
                   3115:                         my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
                   3116:                         my $request=new HTTP::Request('HEAD',$uri);
                   3117:                         my $response=$ua->request($request);
                   3118:                         if ($response->is_success()) {
                   3119:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3120:                             my $locmodtime = (stat($fname))[9];
                   3121:                             if ($locmodtime < $remmodtime) {
                   3122:                                 my $stale;
                   3123:                                 my $answer = &reply('pong',$homeserver);
                   3124:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3125:                                     sleep(0.2);
                   3126:                                     $locmodtime = (stat($fname))[9];
                   3127:                                     if ($locmodtime < $remmodtime) {
                   3128:                                         my $posstransfer = $fname.'.in.transfer';
                   3129:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3130:                                             $removed = 1;
                   3131:                                         } else {
                   3132:                                             $stale = 1;
                   3133:                                         }
                   3134:                                     } else {
                   3135:                                         $removed = 1;
                   3136:                                     }
                   3137:                                 } else {
                   3138:                                     $stale = 1;
                   3139:                                 }
                   3140:                                 if ($stale) {
                   3141:                                     unlink($fname);
                   3142:                                     if ($uri!~/\.meta$/) {
                   3143:                                         unlink($fname.'.meta');
                   3144:                                     }
                   3145:                                     &reply("unsub:$fname",$homeserver);
                   3146:                                     $removed = 1;
                   3147:                                 }
                   3148:                             }
                   3149:                         }
                   3150:                     }
                   3151:                 }
                   3152:             }
                   3153:         }
                   3154:     }
                   3155:     return $removed;
                   3156: }
                   3157: 
1.492     albertel 3158: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3159: 
                   3160: sub allowuploaded {
                   3161:     my ($srcurl,$url)=@_;
                   3162:     $url=&clutter(&declutter($url));
                   3163:     my $dir=$url;
                   3164:     $dir=~s/\/[^\/]+$//;
                   3165:     my %httpref=();
                   3166:     my $httpurl=&hreflocation('',$url);
                   3167:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3168:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3169: }
1.477     raeburn  3170: 
1.1172.2.13  raeburn  3171: #
                   3172: # Determine if the current user should be able to edit a particular resource,
                   3173: # when viewing in course context.
                   3174: # (a) When viewing resource used to determine if "Edit" item is included in
                   3175: #     Functions.
                   3176: # (b) When displaying folder contents in course editor, used to determine if
                   3177: #     "Edit" link will be displayed alongside resource.
                   3178: #
                   3179: #  input: six args -- filename (decluttered), course number, course domain,
                   3180: #                   url, symb (if registered) and group (if this is a group
                   3181: #                   item -- e.g., bulletin board, group page etc.).
                   3182: #  output: array of five scalars --
                   3183: #          $cfile -- url for file editing if editable on current server
                   3184: #          $home -- homeserver of resource (i.e., for author if published,
                   3185: #                                           or course if uploaded.).
                   3186: #          $switchserver --  1 if server switch will be needed.
                   3187: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   3188: #          $forceview -- 1 if icon/link should be to go to view mode
                   3189: #
                   3190: 
                   3191: sub can_edit_resource {
                   3192:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3193:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3194: #
                   3195: # For aboutme pages user can only edit his/her own.
                   3196: #
                   3197:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   3198:         my ($sdom,$sname) = ($1,$2);
                   3199:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3200:             $home = $env{'user.home'};
                   3201:             $cfile = $resurl;
                   3202:             if ($env{'form.forceedit'}) {
                   3203:                 $forceview = 1;
                   3204:             } else {
                   3205:                 $forceedit = 1;
                   3206:             }
                   3207:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3208:         } else {
                   3209:             return;
                   3210:         }
                   3211:     }
                   3212: 
                   3213:     if ($env{'request.course.id'}) {
                   3214:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3215:         if ($group ne '') {
                   3216: # if this is a group homepage or group bulletin board, check group privs
                   3217:             my $allowed = 0;
                   3218:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3219:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   3220:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3221:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3222:                     $allowed = 1;
                   3223:                 }
                   3224:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3225:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3226:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3227:                     $allowed = 1;
                   3228:                 }
                   3229:             }
                   3230:             if ($allowed) {
                   3231:                 $home=&homeserver($cnum,$cdom);
                   3232:                 if ($env{'form.forceedit'}) {
                   3233:                     $forceview = 1;
                   3234:                 } else {
                   3235:                     $forceedit = 1;
                   3236:                 }
                   3237:                 $cfile = $resurl;
                   3238:             } else {
                   3239:                 return;
                   3240:             }
                   3241:         } else {
1.1172.2.15  raeburn  3242:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3243:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3244:                     return;
                   3245:                 }
                   3246:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  3247: #
                   3248: # No edit allowed where CC has switched to student role.
                   3249: #
                   3250:                 return;
                   3251:             }
                   3252:         }
                   3253:     }
                   3254: 
                   3255:     if ($file ne '') {
                   3256:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   3257:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3258:                 $uploaded = 1;
                   3259:                 $incourse = 1;
                   3260:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3261:                     $cfile = &hreflocation('',$file);
                   3262:                     if ($env{'form.forceedit'}) {
                   3263:                         $forceview = 1;
                   3264:                     } else {
                   3265:                         $forceedit = 1;
                   3266:                     }
                   3267:                 }
                   3268:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3269:                 $incourse = 1;
                   3270:                 if ($env{'form.forceedit'}) {
                   3271:                     $forceview = 1;
                   3272:                 } else {
                   3273:                     $forceedit = 1;
                   3274:                 }
                   3275:                 $cfile = $resurl;
                   3276:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   3277:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3278:                     $incourse = 1;
                   3279:                     if ($env{'form.forceedit'}) {
                   3280:                         $forceview = 1;
                   3281:                     } else {
                   3282:                         $forceedit = 1;
                   3283:                     }
                   3284:                     $cfile = $resurl;
                   3285:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   3286:                     $incourse = 1;
                   3287:                     $cfile = $resurl.'/smpedit';
                   3288:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   3289:                     $incourse = 1;
                   3290:                     if ($env{'form.forceedit'}) {
                   3291:                         $forceview = 1;
                   3292:                     } else {
                   3293:                         $forceedit = 1;
                   3294:                     }
                   3295:                     $cfile = $resurl;
1.1172.2.15  raeburn  3296:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3297:                     $incourse = 1;
                   3298:                     if ($env{'form.forceedit'}) {
                   3299:                         $forceview = 1;
                   3300:                     } else {
                   3301:                         $forceedit = 1;
                   3302:                     }
                   3303:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3304:                 }
                   3305:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3306:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3307:                 if (&is_on_map($template)) {
                   3308:                     $incourse = 1;
                   3309:                     $forceview = 1;
                   3310:                     $cfile = $template;
                   3311:                 }
                   3312:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3313:                     $incourse = 1;
                   3314:                     if ($env{'form.forceedit'}) {
                   3315:                         $forceview = 1;
                   3316:                     } else {
                   3317:                         $forceedit = 1;
                   3318:                     }
                   3319:                     $cfile = $resurl;
                   3320:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3321:                 $incourse = 1;
                   3322:                 $forceview = 1;
                   3323:                 if ($symb) {
                   3324:                     my ($map,$id,$res)=&decode_symb($symb);
                   3325:                     $env{'request.symb'} = $symb;
                   3326:                     $cfile = &clutter($res);
                   3327:                 } else {
                   3328:                     $cfile = $env{'form.suppurl'};
                   3329:                     $cfile =~ s{^http://}{};
                   3330:                     $cfile = '/adm/wrapper/ext/'.$cfile;
                   3331:                 }
1.1172.2.31  raeburn  3332:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3333:                 if ($env{'form.forceedit'}) {
                   3334:                     $forceview = 1;
                   3335:                 } else {
                   3336:                     $forceedit = 1;
                   3337:                 }
                   3338:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3339:             }
                   3340:         }
                   3341:         if ($uploaded || $incourse) {
                   3342:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  3343:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  3344:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3345:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3346:             # Check that the user has permission to edit this resource
                   3347:             my $setpriv = 1;
                   3348:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3349:             if (defined($cfudom)) {
                   3350:                 $home=&homeserver($cfuname,$cfudom);
                   3351:                 $cfile=$file;
                   3352:             }
                   3353:         }
                   3354:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   3355:             (($home ne '') && ($home ne 'no_host'))) {
                   3356:             my @ids=&current_machine_ids();
                   3357:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3358:                 $switchserver=1;
                   3359:             }
                   3360:         }
                   3361:     }
                   3362:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3363: }
                   3364: 
                   3365: sub is_course_upload {
                   3366:     my ($file,$cnum,$cdom) = @_;
                   3367:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3368:     $uploadpath =~ s{^\/}{};
                   3369:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3370:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   3371:         return 1;
                   3372:     }
                   3373:     return;
                   3374: }
                   3375: 
                   3376: sub in_course {
                   3377:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3378:     if ($hideprivileged) {
                   3379:         my $skipuser;
1.1172.2.23  raeburn  3380:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3381:         my @possdoms = ($cdom);
                   3382:         if ($coursehash{'checkforpriv'}) {
                   3383:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   3384:         }
                   3385:         if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13  raeburn  3386:             $skipuser = 1;
                   3387:             if ($coursehash{'nothideprivileged'}) {
                   3388:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3389:                     my $user;
                   3390:                     if ($item =~ /:/) {
                   3391:                         $user = $item;
                   3392:                     } else {
                   3393:                         $user = join(':',split(/[\@]/,$item));
                   3394:                     }
                   3395:                     if ($user eq $uname.':'.$udom) {
                   3396:                         undef($skipuser);
                   3397:                         last;
                   3398:                     }
                   3399:                 }
                   3400:             }
                   3401:             if ($skipuser) {
                   3402:                 return 0;
                   3403:             }
                   3404:         }
                   3405:     }
                   3406:     $type ||= 'any';
                   3407:     if (!defined($cdom) || !defined($cnum)) {
                   3408:         my $cid  = $env{'request.course.id'};
                   3409:         $cdom = $env{'course.'.$cid.'.domain'};
                   3410:         $cnum = $env{'course.'.$cid.'.num'};
                   3411:     }
                   3412:     my $typesref;
                   3413:     if (($type eq 'any') || ($type eq 'all')) {
                   3414:         $typesref = ['active','previous','future'];
                   3415:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3416:         $typesref = [$type];
                   3417:     }
                   3418:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3419:                               $typesref,undef,[$cdom]);
                   3420:     my ($tmp) = keys(%roles);
                   3421:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3422:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3423:     if (@course_roles > 0) {
                   3424:         return 1;
                   3425:     }
                   3426:     return 0;
                   3427: }
                   3428: 
1.478     albertel 3429: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3430: # input: action, courseID, current domain, intended
1.637     raeburn  3431: #        path to file, source of file, instruction to parse file for objects,
                   3432: #        ref to hash for embedded objects,
                   3433: #        ref to hash for codebase of java objects.
1.1095    raeburn  3434: #        reference to scalar to accommodate mime type determined
                   3435: #          from File::MMagic if $parser = parse.
1.637     raeburn  3436: #
1.485     raeburn  3437: # output: url to file (if action was uploaddoc), 
                   3438: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3439: #
1.478     albertel 3440: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3441: # course.
1.477     raeburn  3442: #
1.478     albertel 3443: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3444: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3445: #          course's home server.
1.477     raeburn  3446: #
1.478     albertel 3447: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3448: #          be copied from $source (current location) to 
                   3449: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3450: #         and will then be copied to
                   3451: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3452: #         course's home server.
1.485     raeburn  3453: #
1.481     raeburn  3454: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3455: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3456: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3457: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3458: #         in course's home server.
1.637     raeburn  3459: #
1.477     raeburn  3460: 
                   3461: sub process_coursefile {
1.1095    raeburn  3462:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3463:         $mimetype)=@_;
1.477     raeburn  3464:     my $fetchresult;
1.638     albertel 3465:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3466:     if ($action eq 'propagate') {
1.638     albertel 3467:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3468: 			     $home);
1.481     raeburn  3469:     } else {
1.477     raeburn  3470:         my $fpath = '';
                   3471:         my $fname = $file;
1.478     albertel 3472:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3473:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3474:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3475:         if ($action eq 'copy') {
                   3476:             if ($source eq '') {
                   3477:                 $fetchresult = 'no source file';
                   3478:                 return $fetchresult;
                   3479:             } else {
                   3480:                 my $destination = $filepath.'/'.$fname;
                   3481:                 rename($source,$destination);
                   3482:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3483:                                  $home);
1.481     raeburn  3484:             }
                   3485:         } elsif ($action eq 'uploaddoc') {
1.1172.2.96  raeburn  3486:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3487:             print $fh $env{'form.'.$source};
1.481     raeburn  3488:             close($fh);
1.637     raeburn  3489:             if ($parser eq 'parse') {
1.1024    raeburn  3490:                 my $mm = new File::MMagic;
1.1095    raeburn  3491:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3492:                 if ($type eq 'text/html') {
1.1024    raeburn  3493:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3494:                     unless ($parse_result eq 'ok') {
                   3495:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3496:                     }
1.637     raeburn  3497:                 }
1.1095    raeburn  3498:                 if (ref($mimetype)) {
                   3499:                     $$mimetype = $type;
                   3500:                 } 
1.637     raeburn  3501:             }
1.477     raeburn  3502:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3503:                                  $home);
1.481     raeburn  3504:             if ($fetchresult eq 'ok') {
                   3505:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3506:             } else {
                   3507:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3508:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3509:                 return '/adm/notfound.html';
                   3510:             }
1.477     raeburn  3511:         }
                   3512:     }
1.485     raeburn  3513:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3514:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3515:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3516:     }
                   3517:     return $fetchresult;
                   3518: }
                   3519: 
1.637     raeburn  3520: sub build_filepath {
                   3521:     my ($fpath) = @_;
                   3522:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3523:     unless ($fpath eq '') {
                   3524:         my @parts=split('/',$fpath);
                   3525:         foreach my $part (@parts) {
                   3526:             $filepath.= '/'.$part;
                   3527:             if ((-e $filepath)!=1) {
                   3528:                 mkdir($filepath,0777);
                   3529:             }
                   3530:         }
                   3531:     }
                   3532:     return $filepath;
                   3533: }
                   3534: 
                   3535: sub store_edited_file {
1.638     albertel 3536:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3537:     my $file = $primary_url;
                   3538:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3539:     my $fpath = '';
                   3540:     my $fname = $file;
                   3541:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3542:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3543:     my $filepath = &build_filepath($fpath);
1.1172.2.96  raeburn  3544:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  3545:     print $fh $content;
                   3546:     close($fh);
1.638     albertel 3547:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3548:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3549: 			  $home);
1.637     raeburn  3550:     if ($$fetchresult eq 'ok') {
                   3551:         return '/uploaded/'.$fpath.'/'.$fname;
                   3552:     } else {
1.638     albertel 3553:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3554: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3555:         return '/adm/notfound.html';
                   3556:     }
                   3557: }
                   3558: 
1.531     albertel 3559: sub clean_filename {
1.831     albertel 3560:     my ($fname,$args)=@_;
1.315     www      3561: # Replace Windows backslashes by forward slashes
1.257     www      3562:     $fname=~s/\\/\//g;
1.831     albertel 3563:     if (!$args->{'keep_path'}) {
                   3564:         # Get rid of everything but the actual filename
                   3565: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3566:     }
1.315     www      3567: # Replace spaces by underscores
                   3568:     $fname=~s/\s+/\_/g;
                   3569: # Replace all other weird characters by nothing
1.831     albertel 3570:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3571: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3572: # numbers
                   3573:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3574:     return $fname;
                   3575: }
1.1051    raeburn  3576: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3577: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3578: # image with the same aspect ratio as the original, but with dimensions which do 
                   3579: # not exceed $resizewidth and $resizeheight.
                   3580:  
1.984     neumanie 3581: sub resizeImage {
1.1051    raeburn  3582:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3583:     my $ima = Image::Magick->new;
                   3584:     my $resized;
                   3585:     if (-e $img_path) {
                   3586:         $ima->Read($img_path);
                   3587:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3588:             my $width = $ima->Get('width');
                   3589:             my $height = $ima->Get('height');
                   3590:             if ($width > $resizewidth) {
                   3591: 	        my $factor = $width/$resizewidth;
                   3592:                 my $newheight = $height/$factor;
                   3593:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3594:                 $resized = 1;
                   3595:             }
                   3596:         }
                   3597:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3598:             my $width = $ima->Get('width');
                   3599:             my $height = $ima->Get('height');
                   3600:             if ($height > $resizeheight) {
                   3601:                 my $factor = $height/$resizeheight;
                   3602:                 my $newwidth = $width/$factor;
                   3603:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3604:                 $resized = 1;
                   3605:             }
                   3606:         }
                   3607:         if ($resized) {
                   3608:             $ima->Write($img_path);
                   3609:         }
                   3610:     }
                   3611:     return;
1.977     amueller 3612: }
                   3613: 
1.608     albertel 3614: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3615: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3616: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3617: #        $context - possible values: coursedoc, existingfile, overwrite, 
1.1172.2.109! raeburn  3618: #                                    canceloverwrite, scantron or ''. 
1.1090    raeburn  3619: #                   if 'coursedoc': upload to the current course
                   3620: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3621: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3622: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3623: #        $subdir - directory in userfile to store the file into
1.1172.2.109! raeburn  3624: #        $parser - instruction to parse file for objects ($parser = parse) or
        !          3625: #                  if context is 'scantron', $parser is hashref of csv column mapping
        !          3626: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
        !          3627: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858     raeburn  3628: #        $allfiles - reference to hash for embedded objects
                   3629: #        $codebase - reference to hash for codebase of java objects
                   3630: #        $desuname - username for permanent storage of uploaded file
                   3631: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3632: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3633: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3634: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3635: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3636: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3637: #                    from File::MMagic.
1.858     raeburn  3638: # 
1.686     albertel 3639: # output: url of file in userspace, or error: <message> 
                   3640: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3641: 
1.531     albertel 3642: sub userfileupload {
1.1090    raeburn  3643:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3644:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3645:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3646:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3647:     $fname=&clean_filename($fname);
1.1090    raeburn  3648:     # See if there is anything left
1.257     www      3649:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3650:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3651:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3652:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3653:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3654:         my $now = time;
1.1090    raeburn  3655:         my $filepath;
1.1095    raeburn  3656:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3657:              $filepath = 'tmp/helprequests/'.$now;
                   3658:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3659:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3660:                          '_'.$env{'user.domain'}.'/pending';
                   3661:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3662:             my ($docuname,$docudom);
1.1172.2.96  raeburn  3663:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  3664:                 $docudom = $destudom;
                   3665:             } else {
                   3666:                 $docudom = $env{'user.domain'};
                   3667:             }
1.1172.2.96  raeburn  3668:             if ($destuname =~ /^$match_username$/) { 
1.1090    raeburn  3669:                 $docuname = $destuname;
                   3670:             } else {
                   3671:                 $docuname = $env{'user.name'};
                   3672:             }
                   3673:             if (exists($env{'form.group'})) {
                   3674:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3675:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3676:             }
                   3677:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3678:             if ($context eq 'canceloverwrite') {
                   3679:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3680:                 if (-e  $tempfile) {
                   3681:                     my @info = stat($tempfile);
                   3682:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3683:                         unlink($tempfile);
                   3684:                     }
                   3685:                 }
                   3686:                 return;
1.523     raeburn  3687:             }
                   3688:         }
1.1090    raeburn  3689:         # Create the directory if not present
1.741     raeburn  3690:         my @parts=split(/\//,$filepath);
                   3691:         my $fullpath = $perlvar{'lonDaemons'};
                   3692:         for (my $i=0;$i<@parts;$i++) {
                   3693:             $fullpath .= '/'.$parts[$i];
                   3694:             if ((-e $fullpath)!=1) {
                   3695:                 mkdir($fullpath,0777);
                   3696:             }
                   3697:         }
1.1172.2.96  raeburn  3698:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  3699:         print $fh $env{'form.'.$formname};
                   3700:         close($fh);
1.1090    raeburn  3701:         if ($context eq 'existingfile') {
                   3702:             my @info = stat($fullpath.'/'.$fname);
                   3703:             return ($fullpath.'/'.$fname,$info[9]);
                   3704:         } else {
                   3705:             return $fullpath.'/'.$fname;
                   3706:         }
1.523     raeburn  3707:     }
1.995     raeburn  3708:     if ($subdir eq 'scantron') {
                   3709:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3710:     } else {
1.995     raeburn  3711:         $fname="$subdir/$fname";
                   3712:     }
1.1090    raeburn  3713:     if ($context eq 'coursedoc') {
1.638     albertel 3714: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3715: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3716:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3717:             return &finishuserfileupload($docuname,$docudom,
                   3718: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3719: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3720:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3721:         } else {
1.1172.2.21  raeburn  3722:             if ($env{'form.folder'}) {
                   3723:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3724:             }
1.638     albertel 3725:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3726: 				       $fname,$formname,$parser,
1.1095    raeburn  3727: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3728:         }
1.719     banghart 3729:     } elsif (defined($destuname)) {
                   3730:         my $docuname=$destuname;
                   3731:         my $docudom=$destudom;
1.860     raeburn  3732: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3733: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3734:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3735:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3736:     } else {
1.638     albertel 3737:         my $docuname=$env{'user.name'};
                   3738:         my $docudom=$env{'user.domain'};
1.1172.2.23  raeburn  3739:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3740:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3741:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3742:         }
1.860     raeburn  3743: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3744: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3745:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3746:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3747:     }
1.271     www      3748: }
                   3749: 
                   3750: sub finishuserfileupload {
1.860     raeburn  3751:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3752:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3753:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3754:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3755:   
1.860     raeburn  3756:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3757:     $file=$fname;
                   3758:     if ($fname=~m|/|) {
                   3759:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3760: 	$path.=$fnamepath.'/';
                   3761:     }
1.259     www      3762:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3763:     my $count;
                   3764:     for ($count=4;$count<=$#parts;$count++) {
                   3765:         $filepath.="/$parts[$count]";
                   3766:         if ((-e $filepath)!=1) {
                   3767: 	    mkdir($filepath,0777);
                   3768:         }
                   3769:     }
1.984     neumanie 3770: 
1.258     www      3771: # Save the file
                   3772:     {
1.1172.2.96  raeburn  3773: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 3774: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3775: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3776: 	    return '/adm/notfound.html';
                   3777: 	}
1.1090    raeburn  3778:         if ($context eq 'overwrite') {
1.1117    foxr     3779:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3780:             my $target = $filepath.'/'.$file;
                   3781:             if (-e $source) {
                   3782:                 my @info = stat($source);
                   3783:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3784:                     unless (&File::Copy::move($source,$target)) {
                   3785:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3786:                         return "Moving from $source failed";
                   3787:                     }
                   3788:                 } else {
                   3789:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3790:                 }
                   3791:             } else {
                   3792:                 return "Temporary file: $source missing";
                   3793:             }
                   3794:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3795: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3796: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3797: 	    return '/adm/notfound.html';
                   3798: 	}
1.570     albertel 3799: 	close(FH);
1.1051    raeburn  3800:         if ($resizewidth && $resizeheight) {
                   3801:             my $mm = new File::MMagic;
                   3802:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3803:             if ($mime_type =~ m{^image/}) {
                   3804: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3805:             }  
1.977     amueller 3806: 	}
1.258     www      3807:     }
1.1152    raeburn  3808:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3809:         if (ref($mimetype)) {
                   3810:             if ($$mimetype eq '') {
                   3811:                 my $mm = new File::MMagic;
                   3812:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3813:                 $$mimetype = $type;
                   3814:             }
                   3815:         }
                   3816:     }
1.1172.2.109! raeburn  3817:     if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152    raeburn  3818:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3819:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3820:                                                        $allfiles,$codebase);
                   3821:             unless ($parse_result eq 'ok') {
                   3822:                 &logthis('Failed to parse '.$filepath.$file.
                   3823: 	   	         ' for embedded media: '.$parse_result); 
                   3824:             }
1.637     raeburn  3825:         }
1.1172.2.109! raeburn  3826:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
        !          3827:         my $format = $env{'form.scantron_format'};
        !          3828:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637     raeburn  3829:     }
1.860     raeburn  3830:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3831:         my $input = $filepath.'/'.$file;
                   3832:         my $output = $filepath.'/'.'tn-'.$file;
                   3833:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1172.2.96  raeburn  3834:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   3835:         system({$args[0]} @args);
1.860     raeburn  3836:         if (-e $filepath.'/'.'tn-'.$file) {
                   3837:             $fetchthumb  = 1; 
                   3838:         }
                   3839:     }
1.858     raeburn  3840:  
1.259     www      3841: # Notify homeserver to grep it
                   3842: #
1.984     neumanie 3843:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3844:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3845:     if ($fetchresult eq 'ok') {
1.860     raeburn  3846:         if ($fetchthumb) {
                   3847:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3848:             if ($thumbresult ne 'ok') {
                   3849:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3850:                          $docuhome.': '.$thumbresult);
                   3851:             }
                   3852:         }
1.259     www      3853: #
1.258     www      3854: # Return the URL to it
1.494     albertel 3855:         return '/uploaded/'.$path.$file;
1.263     www      3856:     } else {
1.494     albertel 3857:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3858: 		 ': '.$fetchresult);
1.263     www      3859:         return '/adm/notfound.html';
1.858     raeburn  3860:     }
1.493     albertel 3861: }
                   3862: 
1.637     raeburn  3863: sub extract_embedded_items {
1.961     raeburn  3864:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3865:     my @state = ();
1.1164    raeburn  3866:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3867:     my %javafiles = (
                   3868:                       codebase => '',
                   3869:                       code => '',
                   3870:                       archive => ''
                   3871:                     );
                   3872:     my %mediafiles = (
                   3873:                       src => '',
                   3874:                       movie => '',
                   3875:                      );
1.648     raeburn  3876:     my $p;
                   3877:     if ($content) {
                   3878:         $p = HTML::LCParser->new($content);
                   3879:     } else {
1.961     raeburn  3880:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3881:     }
1.641     albertel 3882:     while (my $t=$p->get_token()) {
1.640     albertel 3883: 	if ($t->[0] eq 'S') {
                   3884: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3885: 	    push(@state, $tagname);
1.648     raeburn  3886:             if (lc($tagname) eq 'allow') {
                   3887:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3888:             }
1.640     albertel 3889: 	    if (lc($tagname) eq 'img') {
                   3890: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3891: 	    }
1.886     albertel 3892: 	    if (lc($tagname) eq 'a') {
1.1172.2.24  raeburn  3893:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
                   3894: 		    &add_filetype($allfiles,$attr->{'href'},'href');
                   3895:                 }
1.886     albertel 3896: 	    }
1.645     raeburn  3897:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3898:                 my $src;
1.645     raeburn  3899:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3900:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3901:                 } else {
1.1164    raeburn  3902:                     if ($attr->{'src'} ne '') {
                   3903:                         $src = $attr->{'src'};
                   3904:                         &add_filetype($allfiles,$src,'src');
                   3905:                     }
                   3906:                 }
                   3907:                 my $text = $p->get_trimmed_text();
                   3908:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3909:                     my @swfargs = split(/,/,$1);
                   3910:                     foreach my $item (@swfargs) {
                   3911:                         $item =~ s/["']//g;
                   3912:                         $item =~ s/^\s+//;
                   3913:                         $item =~ s/\s+$//;
                   3914:                     }
                   3915:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3916:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3917:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3918:                         } else {
                   3919:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3920:                         }
                   3921:                     }
1.645     raeburn  3922:                 }
                   3923:             }
                   3924:             if (lc($tagname) eq 'link') {
                   3925:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3926:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3927:                 }
                   3928:             }
1.640     albertel 3929: 	    if (lc($tagname) eq 'object' ||
                   3930: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3931: 		foreach my $item (keys(%javafiles)) {
                   3932: 		    $javafiles{$item} = '';
                   3933: 		}
1.1164    raeburn  3934:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3935:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3936:                 }
1.640     albertel 3937: 	    }
                   3938: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3939: 		my $name = lc($attr->{'name'});
                   3940: 		foreach my $item (keys(%javafiles)) {
                   3941: 		    if ($name eq $item) {
                   3942: 			$javafiles{$item} = $attr->{'value'};
                   3943: 			last;
                   3944: 		    }
                   3945: 		}
1.1164    raeburn  3946:                 my $pathfrom;
1.640     albertel 3947: 		foreach my $item (keys(%mediafiles)) {
                   3948: 		    if ($name eq $item) {
1.1164    raeburn  3949:                         $pathfrom = $attr->{'value'};
                   3950:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3951: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3952: 			last;
                   3953: 		    }
                   3954: 		}
1.1164    raeburn  3955:                 if ($name eq 'flashvars') {
                   3956:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3957:                 }
                   3958:                 if ($pathfrom ne '') {
                   3959:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3960:                                          $pathfrom);
                   3961:                 }
1.640     albertel 3962: 	    }
                   3963: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3964: 		foreach my $item (keys(%javafiles)) {
                   3965: 		    if ($attr->{$item}) {
                   3966: 			$javafiles{$item} = $attr->{$item};
                   3967: 			last;
                   3968: 		    }
                   3969: 		}
                   3970: 		foreach my $item (keys(%mediafiles)) {
                   3971: 		    if ($attr->{$item}) {
                   3972: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3973: 			last;
                   3974: 		    }
                   3975: 		}
1.1164    raeburn  3976:                 if (lc($tagname) eq 'embed') {
                   3977:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3978:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3979:                                              $attr->{'src'});
                   3980:                     }
                   3981:                 }
1.640     albertel 3982: 	    }
1.1172.2.35  raeburn  3983:             if (lc($tagname) eq 'iframe') {
                   3984:                 my $src = $attr->{'src'} ;
                   3985:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   3986:                     &add_filetype($allfiles,$src,'src');
                   3987:                 } elsif ($src =~ m{^/}) {
                   3988:                     if ($env{'request.course.id'}) {
                   3989:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3990:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3991:                         my $url = &hreflocation('',$fullpath);
                   3992:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   3993:                             my $relpath = $1;
                   3994:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   3995:                                 &add_filetype($allfiles,$1,'src');
                   3996:                             }
                   3997:                         }
                   3998:                     }
                   3999:                 }
                   4000:             }
1.1164    raeburn  4001:             if ($t->[4] =~ m{/>$}) {
1.1172.2.35  raeburn  4002:                 pop(@state);
1.1164    raeburn  4003:             }
1.640     albertel 4004: 	} elsif ($t->[0] eq 'E') {
                   4005: 	    my ($tagname) = ($t->[1]);
                   4006: 	    if ($javafiles{'codebase'} ne '') {
                   4007: 		$javafiles{'codebase'} .= '/';
                   4008: 	    }  
                   4009: 	    if (lc($tagname) eq 'applet' ||
                   4010: 		lc($tagname) eq 'object' ||
                   4011: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4012: 		) {
                   4013: 		foreach my $item (keys(%javafiles)) {
                   4014: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4015: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4016: 			&add_filetype($allfiles,$file,$item);
                   4017: 		    }
                   4018: 		}
                   4019: 	    } 
                   4020: 	    pop @state;
                   4021: 	}
                   4022:     }
1.1164    raeburn  4023:     foreach my $id (sort(keys(%flashvars))) {
                   4024:         if ($shockwave{$id} ne '') {
                   4025:             my @pairs = split(/\&/,$flashvars{$id});
                   4026:             foreach my $pair (@pairs) {
                   4027:                 my ($key,$value) = split(/\=/,$pair);
                   4028:                 if ($key eq 'thumb') {
                   4029:                     &add_filetype($allfiles,$value,$key);
                   4030:                 } elsif ($key eq 'content') {
                   4031:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4032:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4033:                     if ($ext ne '') {
                   4034:                         &add_filetype($allfiles,$path.$value,$ext);
                   4035:                     }
                   4036:                 }
                   4037:             }
                   4038:         }
                   4039:     }
1.637     raeburn  4040:     return 'ok';
                   4041: }
                   4042: 
1.639     albertel 4043: sub add_filetype {
                   4044:     my ($allfiles,$file,$type)=@_;
                   4045:     if (exists($allfiles->{$file})) {
                   4046: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4047: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4048: 	}
                   4049:     } else {
                   4050: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4051:     }
                   4052: }
                   4053: 
1.1164    raeburn  4054: sub embedded_dependency {
                   4055:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4056:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4057:         if (($identifier ne '') &&
                   4058:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4059:             ($pathfrom ne '')) {
                   4060:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4061:             foreach my $dep (@{$related->{$identifier}}) {
                   4062:                 &add_filetype($allfiles,$path.$dep,'object');
                   4063:             }
                   4064:         }
                   4065:     }
                   4066:     return;
                   4067: }
                   4068: 
1.1172.2.109! raeburn  4069: sub bubblesheet_converter {
        !          4070:     my ($cdom,$fullpath,$config,$format) = @_;
        !          4071:     if ((&domain($cdom) ne '') &&
        !          4072:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
        !          4073:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
        !          4074:         my (%csvcols,%csvoptions);
        !          4075:         if (ref($config->{'fields'}) eq 'HASH') {
        !          4076:             %csvcols = %{$config->{'fields'}};
        !          4077:         }
        !          4078:         if (ref($config->{'options'}) eq 'HASH') {
        !          4079:             %csvoptions = %{$config->{'options'}};
        !          4080:         }
        !          4081:         my %csvbynum = reverse(%csvcols);
        !          4082:         my %scantronconf = &get_scantron_config($format,$cdom);
        !          4083:         if (keys(%scantronconf)) {
        !          4084:             my %bynum = (
        !          4085:                           $scantronconf{CODEstart} => 'CODEstart',
        !          4086:                           $scantronconf{IDstart}   => 'IDstart',
        !          4087:                           $scantronconf{PaperID}   => 'PaperID',
        !          4088:                           $scantronconf{FirstName} => 'FirstName',
        !          4089:                           $scantronconf{LastName}  => 'LastName',
        !          4090:                           $scantronconf{Qstart}    => 'Qstart',
        !          4091:                         );
        !          4092:             my @ordered;
        !          4093:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
        !          4094:                 push(@ordered,$bynum{$item});
        !          4095:             }
        !          4096:             my %mapstart = (
        !          4097:                               CODEstart => 'CODE',
        !          4098:                               IDstart   => 'ID',
        !          4099:                               PaperID   => 'PaperID',
        !          4100:                               FirstName => 'FirstName',
        !          4101:                               LastName  => 'LastName',
        !          4102:                               Qstart    => 'FirstQuestion',
        !          4103:                            );
        !          4104:             my %maplength = (
        !          4105:                               CODEstart => 'CODElength',
        !          4106:                               IDstart   => 'IDlength',
        !          4107:                               PaperID   => 'PaperIDlength',
        !          4108:                               FirstName => 'FirstNamelength',
        !          4109:                               LastName  => 'LastNamelength',
        !          4110:             );
        !          4111:             if (open(my $fh,'<',$fullpath)) {
        !          4112:                 my $output;
        !          4113:                 my %lettdig = &letter_to_digits();
        !          4114:                 my %diglett = reverse(%lettdig);
        !          4115:                 my $numletts = scalar(keys(%lettdig));
        !          4116:                 my $num = 0;
        !          4117:                 while (my $line=<$fh>) {
        !          4118:                     $num ++;
        !          4119:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
        !          4120:                     $line =~ s{[\r\n]+$}{};
        !          4121:                     my %found;
        !          4122:                     my @values = split(/,/,$line);
        !          4123:                     my ($qstart,$record);
        !          4124:                     for (my $i=0; $i<@values; $i++) {
        !          4125:                         if ((($qstart ne '') && ($i > $qstart)) ||
        !          4126:                             ($csvbynum{$i} eq 'FirstQuestion')) {
        !          4127:                             if ($values[$i] eq '') {
        !          4128:                                 $values[$i] = $scantronconf{'Qoff'};
        !          4129:                             } elsif ($scantronconf{'Qon'} eq 'number') {
        !          4130:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
        !          4131:                                     $values[$i] = $lettdig{uc($values[$i])};
        !          4132:                                 }
        !          4133:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
        !          4134:                                 if ($values[$i] =~ /^[0-9]$/) {
        !          4135:                                     $values[$i] = $diglett{$values[$i]};
        !          4136:                                 }
        !          4137:                             } else {
        !          4138:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
        !          4139:                                     my $digit;
        !          4140:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
        !          4141:                                         $digit = $lettdig{uc($values[$i])}-1;
        !          4142:                                         if ($values[$i] eq 'J') {
        !          4143:                                             $digit += $numletts;
        !          4144:                                         }
        !          4145:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
        !          4146:                                         $digit = $values[$i]-1;
        !          4147:                                         if ($values[$i] eq '0') {
        !          4148:                                             $digit += $numletts;
        !          4149:                                         }
        !          4150:                                     }
        !          4151:                                     my $qval='';
        !          4152:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
        !          4153:                                         if ($j == $digit) {
        !          4154:                                             $qval .= $scantronconf{'Qon'};
        !          4155:                                         } else {
        !          4156:                                             $qval .= $scantronconf{'Qoff'};
        !          4157:                                         }
        !          4158:                                     }
        !          4159:                                     $values[$i] = $qval;
        !          4160:                                 }
        !          4161:                             }
        !          4162:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
        !          4163:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
        !          4164:                             }
        !          4165:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
        !          4166:                             if ($numblank > 0) {
        !          4167:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
        !          4168:                             }
        !          4169:                             if ($csvbynum{$i} eq 'FirstQuestion') {
        !          4170:                                 $qstart = $i;
        !          4171:                                 $found{$csvbynum{$i}} = $values[$i];
        !          4172:                             } else {
        !          4173:                                 $found{'FirstQuestion'} .= $values[$i];
        !          4174:                             }
        !          4175:                         } elsif (exists($csvbynum{$i})) {
        !          4176:                             if ($csvoptions{'rem'}) {
        !          4177:                                 $values[$i] =~ s/^\s+//;
        !          4178:                             }
        !          4179:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
        !          4180:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
        !          4181:                                     $values[$i] = '0'.$values[$i];
        !          4182:                                 }
        !          4183:                             }
        !          4184:                             $found{$csvbynum{$i}} = $values[$i];
        !          4185:                         }
        !          4186:                     }
        !          4187:                     foreach my $item (@ordered) {
        !          4188:                         my $currlength = 1+length($record);
        !          4189:                         my $numspaces = $scantronconf{$item} - $currlength;
        !          4190:                         if ($numspaces > 0) {
        !          4191:                             $record .= (' ' x $numspaces);
        !          4192:                         }
        !          4193:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
        !          4194:                             unless ($item eq 'Qstart') {
        !          4195:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
        !          4196:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
        !          4197:                                 }
        !          4198:                             }
        !          4199:                             $record .= $found{$mapstart{$item}};
        !          4200:                         }
        !          4201:                     }
        !          4202:                     $output .= "$record\n";
        !          4203:                 }
        !          4204:                 close($fh);
        !          4205:                 if ($output) {
        !          4206:                     if (open(my $fh,'>',$fullpath)) {
        !          4207:                         print $fh $output;
        !          4208:                         close($fh);
        !          4209:                     }
        !          4210:                 }
        !          4211:             }
        !          4212:         }
        !          4213:         return;
        !          4214:     }
        !          4215: }
        !          4216: 
        !          4217: sub letter_to_digits {
        !          4218:     my %lettdig = (
        !          4219:                     A => 1,
        !          4220:                     B => 2,
        !          4221:                     C => 3,
        !          4222:                     D => 4,
        !          4223:                     E => 5,
        !          4224:                     F => 6,
        !          4225:                     G => 7,
        !          4226:                     H => 8,
        !          4227:                     I => 9,
        !          4228:                     J => 0,
        !          4229:                   );
        !          4230:     return %lettdig;
        !          4231: }
        !          4232: 
        !          4233: sub get_scantron_config {
        !          4234:     my ($which,$cdom) = @_;
        !          4235:     my @lines = &get_scantronformat_file($cdom);
        !          4236:     my %config;
        !          4237:     #FIXME probably should move to XML it has already gotten a bit much now
        !          4238:     foreach my $line (@lines) {
        !          4239:         my ($name,$descrip)=split(/:/,$line);
        !          4240:         if ($name ne $which ) { next; }
        !          4241:         chomp($line);
        !          4242:         my @config=split(/:/,$line);
        !          4243:         $config{'name'}=$config[0];
        !          4244:         $config{'description'}=$config[1];
        !          4245:         $config{'CODElocation'}=$config[2];
        !          4246:         $config{'CODEstart'}=$config[3];
        !          4247:         $config{'CODElength'}=$config[4];
        !          4248:         $config{'IDstart'}=$config[5];
        !          4249:         $config{'IDlength'}=$config[6];
        !          4250:         $config{'Qstart'}=$config[7];
        !          4251:         $config{'Qlength'}=$config[8];
        !          4252:         $config{'Qoff'}=$config[9];
        !          4253:         $config{'Qon'}=$config[10];
        !          4254:         $config{'PaperID'}=$config[11];
        !          4255:         $config{'PaperIDlength'}=$config[12];
        !          4256:         $config{'FirstName'}=$config[13];
        !          4257:         $config{'FirstNamelength'}=$config[14];
        !          4258:         $config{'LastName'}=$config[15];
        !          4259:         $config{'LastNamelength'}=$config[16];
        !          4260:         $config{'BubblesPerRow'}=$config[17];
        !          4261:         last;
        !          4262:     }
        !          4263:     return %config;
        !          4264: }
        !          4265: 
        !          4266: sub get_scantronformat_file {
        !          4267:     my ($cdom) = @_;
        !          4268:     if ($cdom eq '') {
        !          4269:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
        !          4270:     }
        !          4271:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
        !          4272:     my $gottab = 0;
        !          4273:     my @lines;
        !          4274:     if (ref($domconfig{'scantron'}) eq 'HASH') {
        !          4275:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
        !          4276:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
        !          4277:             if ($formatfile ne '-1') {
        !          4278:                 @lines = split("\n",$formatfile,-1);
        !          4279:                 $gottab = 1;
        !          4280:             }
        !          4281:         }
        !          4282:     }
        !          4283:     if (!$gottab) {
        !          4284:         my $confname = $cdom.'-domainconfig';
        !          4285:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
        !          4286:         my $formatfile = &getfile($default);
        !          4287:         if ($formatfile ne '-1') {
        !          4288:             @lines = split("\n",$formatfile,-1);
        !          4289:             $gottab = 1;
        !          4290:         }
        !          4291:     }
        !          4292:     if (!$gottab) {
        !          4293:         my @domains = &current_machine_domains();
        !          4294:         if (grep(/^\Q$cdom\E$/,@domains)) {
        !          4295:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
        !          4296:                 @lines = <$fh>;
        !          4297:                 close($fh);
        !          4298:             }
        !          4299:         } else {
        !          4300:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
        !          4301:                 @lines = <$fh>;
        !          4302:                 close($fh);
        !          4303:             }
        !          4304:         }
        !          4305:     }
        !          4306:     return @lines;
        !          4307: }
        !          4308: 
1.493     albertel 4309: sub removeuploadedurl {
1.984     neumanie 4310:     my ($url)=@_;	
                   4311:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4312:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4313: }
                   4314: 
                   4315: sub removeuserfile {
                   4316:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4317:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4318:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4319:     if ($result eq 'ok') {	
1.798     raeburn  4320:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4321:             my $metafile = $fname.'.meta';
                   4322:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4323: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4324:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4325:             my $sqlresult = 
1.823     albertel 4326:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4327:                                         'portfolio_metadata',$group,
                   4328:                                         'delete');
1.798     raeburn  4329:         }
                   4330:     }
                   4331:     return $result;
1.257     www      4332: }
1.15      www      4333: 
1.530     albertel 4334: sub mkdiruserfile {
                   4335:     my ($docuname,$docudom,$dir)=@_;
                   4336:     my $home=&homeserver($docuname,$docudom);
                   4337:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4338: }
                   4339: 
1.531     albertel 4340: sub renameuserfile {
                   4341:     my ($docuname,$docudom,$old,$new)=@_;
                   4342:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4343:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4344:                         &escape("$old").':'.&escape("$new"),$home);
                   4345:     if ($result eq 'ok') {
                   4346:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4347:             my $oldmeta = $old.'.meta';
                   4348:             my $newmeta = $new.'.meta';
                   4349:             my $metaresult = 
                   4350:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4351: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4352:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4353:             my $sqlresult = 
1.823     albertel 4354:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4355:                                         'portfolio_metadata',$group,
                   4356:                                         'delete');
1.798     raeburn  4357:         }
                   4358:     }
                   4359:     return $result;
1.531     albertel 4360: }
                   4361: 
1.14      www      4362: # ------------------------------------------------------------------------- Log
                   4363: 
                   4364: sub log {
                   4365:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4366:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4367: }
                   4368: 
                   4369: # ------------------------------------------------------------------ Course Log
1.352     www      4370: #
                   4371: # This routine flushes several buffers of non-mission-critical nature
                   4372: #
1.157     www      4373: 
                   4374: sub flushcourselogs {
1.352     www      4375:     &logthis('Flushing log buffers');
                   4376: #
                   4377: # course logs
                   4378: # This is a log of all transactions in a course, which can be used
                   4379: # for data mining purposes
                   4380: #
                   4381: # It also collects the courseid database, which lists last transaction
                   4382: # times and course titles for all courseids
                   4383: #
                   4384:     my %courseidbuffer=();
1.921     raeburn  4385:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4386:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4387: 		          &escape($courselogs{$crsid}),
                   4388: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4389: 	    delete $courselogs{$crsid};
                   4390:         } else {
                   4391:             &logthis('Failed to flush log buffer for '.$crsid);
                   4392:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4393:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4394:                         " exceeded maximum size, deleting.</font>");
                   4395:                delete $courselogs{$crsid};
                   4396:             }
1.352     www      4397:         }
1.920     raeburn  4398:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4399:             'description' => $coursedescrbuf{$crsid},
                   4400:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4401:             'type'        => $coursetypebuf{$crsid},
                   4402:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4403:         };
1.191     harris41 4404:     }
1.352     www      4405: #
                   4406: # Write course id database (reverse lookup) to homeserver of courses 
                   4407: # Is used in pickcourse
                   4408: #
1.840     albertel 4409:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4410:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4411:                                     $courseidbuffer{$crs_home},
                   4412:                                     $crs_home,'timeonly');
1.352     www      4413:     }
                   4414: #
                   4415: # File accesses
                   4416: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4417: #
1.449     matthew  4418:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4419:         if ($entry =~ /___count$/) {
                   4420:             my ($dom,$name);
1.807     albertel 4421:             ($dom,$name,undef)=
1.811     albertel 4422: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4423:             if (! defined($dom) || $dom eq '' || 
                   4424:                 ! defined($name) || $name eq '') {
1.620     albertel 4425:                 my $cid = $env{'request.course.id'};
                   4426:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4427:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4428:             }
1.450     matthew  4429:             my $value = $accesshash{$entry};
                   4430:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4431:             my %temphash=($url => $value);
1.449     matthew  4432:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4433:             if ($result eq 'ok') {
                   4434:                 delete $accesshash{$entry};
                   4435:             }
                   4436:         } else {
1.811     albertel 4437:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4438:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4439:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4440:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4441:                 delete $accesshash{$entry};
                   4442:             }
1.185     www      4443:         }
1.191     harris41 4444:     }
1.352     www      4445: #
                   4446: # Roles
                   4447: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4448: #
1.800     albertel 4449:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4450:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4451: 	    split(/\:/,$entry);
                   4452:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4453:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4454:                 $rudom,$runame) eq 'ok') {
                   4455: 	    delete $userrolehash{$entry};
                   4456:         }
                   4457:     }
1.662     raeburn  4458: #
1.1172.2.90  raeburn  4459: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4460: #
                   4461:     my %domrolebuffer = ();
1.1000    raeburn  4462:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4463:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4464:         if ($domrolebuffer{$rudom}) {
                   4465:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4466:                       '='.&escape($domainrolehash{$entry});
                   4467:         } else {
                   4468:             $domrolebuffer{$rudom}.=&escape($entry).
                   4469:                       '='.&escape($domainrolehash{$entry});
                   4470:         }
                   4471:         delete $domainrolehash{$entry};
                   4472:     }
                   4473:     foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82  raeburn  4474:         my %servers;
                   4475:         if (defined(&domain($dom,'primary'))) {
                   4476:             my $primary=&domain($dom,'primary');
                   4477:             my $hostname=&hostname($primary);
                   4478:             $servers{$primary} = $hostname;
                   4479:         } else {
                   4480:             %servers = &get_servers($dom,'library');
                   4481:         }
1.841     albertel 4482: 	foreach my $tryserver (keys(%servers)) {
1.1172.2.82  raeburn  4483: 	    if (&reply('domroleput:'.$dom.':'.
                   4484: 	               $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4485: 	        last;
                   4486: 	    } else {
1.841     albertel 4487: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4488: 	    }
1.662     raeburn  4489:         }
                   4490:     }
1.186     www      4491:     $dumpcount++;
1.157     www      4492: }
                   4493: 
                   4494: sub courselog {
                   4495:     my $what=shift;
1.158     www      4496:     $what=time.':'.$what;
1.620     albertel 4497:     unless ($env{'request.course.id'}) { return ''; }
                   4498:     $coursedombuf{$env{'request.course.id'}}=
                   4499:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4500:     $coursenumbuf{$env{'request.course.id'}}=
                   4501:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4502:     $coursehombuf{$env{'request.course.id'}}=
                   4503:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4504:     $coursedescrbuf{$env{'request.course.id'}}=
                   4505:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4506:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4507:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4508:     $courseownerbuf{$env{'request.course.id'}}=
                   4509:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4510:     $coursetypebuf{$env{'request.course.id'}}=
                   4511:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4512:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4513: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4514:     } else {
1.620     albertel 4515: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4516:     }
1.620     albertel 4517:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4518: 	&flushcourselogs();
                   4519:     }
1.158     www      4520: }
                   4521: 
                   4522: sub courseacclog {
                   4523:     my $fnsymb=shift;
1.620     albertel 4524:     unless ($env{'request.course.id'}) { return ''; }
                   4525:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4526:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4527:         $what.=':POST';
1.583     matthew  4528:         # FIXME: Probably ought to escape things....
1.800     albertel 4529: 	foreach my $key (keys(%env)) {
                   4530:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4531:                 my $formitem = $1;
                   4532:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4533:                     $what.=':'.$formitem.'='.$env{$key};
                   4534:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   4535:                     $what.=':'.$formitem.'='.$env{$key};
                   4536:                 }
1.158     www      4537:             }
1.191     harris41 4538:         }
1.583     matthew  4539:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4540:         # FIXME: We should not be depending on a form parameter that someone
                   4541:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4542:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4543:             $what.= ':POST';
                   4544:             # FIXME: Probably ought to escape things....
                   4545:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4546:                                  'crsdiscuss') {
1.620     albertel 4547:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4548:             }
                   4549:         }
1.158     www      4550:     }
                   4551:     &courselog($what);
1.149     www      4552: }
                   4553: 
1.185     www      4554: sub countacc {
                   4555:     my $url=&declutter(shift);
1.458     matthew  4556:     return if (! defined($url) || $url eq '');
1.620     albertel 4557:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4558: #
                   4559: # Mark that this url was used in this course
                   4560: #
1.620     albertel 4561:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4562: #
                   4563: # Increase the access count for this resource in this child process
                   4564: #
1.281     www      4565:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4566:     $accesshash{$key}++;
1.185     www      4567: }
1.349     www      4568: 
1.361     www      4569: sub linklog {
                   4570:     my ($from,$to)=@_;
                   4571:     $from=&declutter($from);
                   4572:     $to=&declutter($to);
                   4573:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4574:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4575: }
1.1160    www      4576: 
                   4577: sub statslog {
                   4578:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4579:     if ($users<2) { return; }
                   4580:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4581:             'course'       => $env{'request.course.id'},
                   4582:             'sections'     => '"all"',
                   4583:             'num_students' => $users,
                   4584:             'part'         => $part,
                   4585:             'symb'         => $symb,
                   4586:             'mean_tries'   => $av_attempts,
                   4587:             'deg_of_diff'  => $degdiff});
                   4588:     foreach my $key (keys(%dynstore)) {
                   4589:         $accesshash{$key}=$dynstore{$key};
                   4590:     }
                   4591: }
1.361     www      4592:   
1.349     www      4593: sub userrolelog {
                   4594:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4595:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4596:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4597:        $userrolehash
                   4598:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4599:                     =$tend.':'.$tstart;
1.662     raeburn  4600:     }
1.1169    droeschl 4601:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4602:        $userrolehash
                   4603:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4604:                     =$tend.':'.$tstart;
                   4605:     }
1.1172.2.90  raeburn  4606:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4607:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4608:        $domainrolehash
                   4609:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4610:                     = $tend.':'.$tstart;
                   4611:     }
1.351     www      4612: }
                   4613: 
1.957     raeburn  4614: sub courserolelog {
                   4615:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  4616:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4617:         my $cdom = $1;
                   4618:         my $cnum = $2;
                   4619:         my $sec = $3;
                   4620:         my $namespace = 'rolelog';
                   4621:         my %storehash = (
                   4622:                            role    => $trole,
                   4623:                            start   => $tstart,
                   4624:                            end     => $tend,
                   4625:                            selfenroll => $selfenroll,
                   4626:                            context    => $context,
                   4627:                         );
                   4628:         if ($trole eq 'gr') {
                   4629:             $namespace = 'groupslog';
                   4630:             $storehash{'group'} = $sec;
                   4631:         } else {
                   4632:             $storehash{'section'} = $sec;
                   4633:         }
                   4634:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4635:                    $domain,$cnum,$cdom);
                   4636:         if (($trole ne 'st') || ($sec ne '')) {
                   4637:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4638:         }
                   4639:     }
                   4640:     return;
                   4641: }
                   4642: 
1.1172.2.9  raeburn  4643: sub domainrolelog {
                   4644:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4645:     if ($area =~ m{^/($match_domain)/$}) {
                   4646:         my $cdom = $1;
                   4647:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4648:         my $namespace = 'rolelog';
                   4649:         my %storehash = (
                   4650:                            role    => $trole,
                   4651:                            start   => $tstart,
                   4652:                            end     => $tend,
                   4653:                            context => $context,
                   4654:                         );
                   4655:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4656:                    $domain,$domconfiguser,$cdom);
                   4657:     }
                   4658:     return;
                   4659: 
                   4660: }
                   4661: 
                   4662: sub coauthorrolelog {
                   4663:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4664:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4665:         my $audom = $1;
                   4666:         my $auname = $2;
                   4667:         my $namespace = 'rolelog';
                   4668:         my %storehash = (
                   4669:                            role    => $trole,
                   4670:                            start   => $tstart,
                   4671:                            end     => $tend,
                   4672:                            context => $context,
                   4673:                         );
                   4674:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4675:                    $domain,$auname,$audom);
                   4676:     }
                   4677:     return;
                   4678: }
                   4679: 
1.351     www      4680: sub get_course_adv_roles {
1.948     raeburn  4681:     my ($cid,$codes) = @_;
1.620     albertel 4682:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4683:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4684:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4685:     my %nothide=();
1.800     albertel 4686:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4687:         if ($user !~ /:/) {
                   4688: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4689:         } else {
                   4690:             $nothide{$user}=1;
                   4691:         }
1.470     www      4692:     }
1.1172.2.23  raeburn  4693:     my @possdoms = ($coursehash{'domain'});
                   4694:     if ($coursehash{'checkforpriv'}) {
                   4695:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4696:     }
1.351     www      4697:     my %returnhash=();
                   4698:     my %dumphash=
                   4699:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4700:     my $now=time;
1.997     raeburn  4701:     my %privileged;
1.1000    raeburn  4702:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4703: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4704:         if (($tstart) && ($tstart<0)) { next; }
                   4705:         if (($tend) && ($tend<$now)) { next; }
                   4706:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4707:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4708: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  4709:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4710:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4711: 	if ($role eq 'cr') { next; }
1.948     raeburn  4712:         if ($codes) {
                   4713:             if ($section) { $role .= ':'.$section; }
                   4714:             if ($returnhash{$role}) {
                   4715:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4716:             } else {
                   4717:                 $returnhash{$role}=$username.':'.$domain;
                   4718:             }
1.351     www      4719:         } else {
1.988     raeburn  4720:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4721:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4722:             if ($returnhash{$key}) {
                   4723: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4724:             } else {
                   4725:                 $returnhash{$key}=$username.':'.$domain;
                   4726:             }
1.351     www      4727:         }
1.948     raeburn  4728:     }
1.400     www      4729:     return %returnhash;
                   4730: }
                   4731: 
                   4732: sub get_my_roles {
1.937     raeburn  4733:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4734:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4735:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4736:     my (%dumphash,%nothide);
1.1086    raeburn  4737:     if ($context eq 'userroles') {
1.1166    raeburn  4738:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4739:     } else {
1.1172.2.23  raeburn  4740:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4741:         if ($hidepriv) {
                   4742:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4743:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4744:                 if ($user !~ /:/) {
                   4745:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4746:                 } else {
                   4747:                     $nothide{$user} = 1;
                   4748:                 }
                   4749:             }
                   4750:         }
1.858     raeburn  4751:     }
1.400     www      4752:     my %returnhash=();
                   4753:     my $now=time;
1.999     raeburn  4754:     my %privileged;
1.800     albertel 4755:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4756:         my ($role,$tend,$tstart);
                   4757:         if ($context eq 'userroles') {
1.1149    raeburn  4758:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4759: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4760:         } else {
                   4761:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4762:         }
1.400     www      4763:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4764:         my $status = 'active';
1.939     raeburn  4765:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4766:             $status = 'previous';
                   4767:         } 
                   4768:         if (($tstart) && ($now<$tstart)) {
                   4769:             $status = 'future';
                   4770:         }
                   4771:         if (ref($types) eq 'ARRAY') {
                   4772:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4773:                 next;
                   4774:             } 
                   4775:         } else {
                   4776:             if ($status ne 'active') {
                   4777:                 next;
                   4778:             }
                   4779:         }
1.867     raeburn  4780:         my ($rolecode,$username,$domain,$section,$area);
                   4781:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  4782:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4783:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4784:         } else {
                   4785:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4786:         }
1.832     raeburn  4787:         if (ref($roledoms) eq 'ARRAY') {
                   4788:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4789:                 next;
                   4790:             }
                   4791:         }
                   4792:         if (ref($roles) eq 'ARRAY') {
                   4793:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4794:                 if ($role =~ /^cr\//) {
                   4795:                     if (!grep(/^cr$/,@{$roles})) {
                   4796:                         next;
                   4797:                     }
1.1104    raeburn  4798:                 } elsif ($role =~ /^gr\//) {
                   4799:                     if (!grep(/^gr$/,@{$roles})) {
                   4800:                         next;
                   4801:                     }
1.922     raeburn  4802:                 } else {
                   4803:                     next;
                   4804:                 }
1.832     raeburn  4805:             }
1.867     raeburn  4806:         }
1.937     raeburn  4807:         if ($hidepriv) {
1.1172.2.23  raeburn  4808:             my @privroles = ('dc','su');
1.999     raeburn  4809:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  4810:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4811:             } else {
1.1172.2.23  raeburn  4812:                 my $possdoms = [$domain];
                   4813:                 if (ref($roledoms) eq 'ARRAY') {
                   4814:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  4815:                 }
1.1172.2.23  raeburn  4816:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4817:                     if (!$nothide{$username.':'.$domain}) {
                   4818:                         next;
                   4819:                     }
                   4820:                 }
1.937     raeburn  4821:             }
                   4822:         }
1.933     raeburn  4823:         if ($withsec) {
                   4824:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4825:                 $tstart.':'.$tend;
                   4826:         } else {
                   4827:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4828:         }
1.832     raeburn  4829:     }
1.373     www      4830:     return %returnhash;
1.399     www      4831: }
                   4832: 
1.1172.2.89  raeburn  4833: sub get_all_adhocroles {
                   4834:     my ($dom) = @_;
                   4835:     my @roles_by_num = ();
                   4836:     my %domdefaults = &get_domain_defaults($dom);
                   4837:     my (%description,%access_in_dom,%access_info);
                   4838:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   4839:         my $count = 0;
                   4840:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   4841:         my %ordered;
                   4842:         foreach my $role (sort(keys(%domcurrent))) {
                   4843:             my ($order,$desc,$access_in_dom);
                   4844:             if (ref($domcurrent{$role}) eq 'HASH') {
                   4845:                 $order = $domcurrent{$role}{'order'};
                   4846:                 $desc = $domcurrent{$role}{'desc'};
                   4847:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   4848:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   4849:             }
                   4850:             if ($order eq '') {
                   4851:                 $order = $count;
                   4852:             }
                   4853:             $ordered{$order} = $role;
                   4854:             if ($desc ne '') {
                   4855:                 $description{$role} = $desc;
                   4856:             } else {
                   4857:                 $description{$role}= $role;
                   4858:             }
                   4859:             $count++;
                   4860:         }
                   4861:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   4862:             push(@roles_by_num,$ordered{$item});
                   4863:         }
                   4864:     }
                   4865:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   4866: }
                   4867: 
                   4868: sub get_my_adhocroles {
                   4869:     my ($cid,$checkreg) = @_;
                   4870:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   4871:     if ($env{'request.course.id'} eq $cid) {
                   4872:         $cdom = $env{'course.'.$cid.'.domain'};
                   4873:         $cnum = $env{'course.'.$cid.'.num'};
                   4874:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   4875:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   4876:         $cdom = $1;
                   4877:         $cnum = $2;
                   4878:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   4879:                                      $cdom,$cnum);
                   4880:     }
                   4881:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   4882:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   4883:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   4884:         if ($rosterhash{$user} ne '') {
                   4885:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   4886:             return ([],{}) if ($type eq 'auto');
                   4887:         }
                   4888:     }
                   4889:     if (($cdom ne '') && ($cnum ne ''))  {
1.1172.2.90  raeburn  4890:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89  raeburn  4891:             my $then=$env{'user.login.time'};
                   4892:             my $update=$env{'user.update.time'};
1.1172.2.90  raeburn  4893:             if (!$update) {
                   4894:                 $update = $then;
                   4895:             }
                   4896:             my @liveroles;
                   4897:             foreach my $role ('dh','da') {
                   4898:                 if ($env{"user.role.$role./$cdom/"}) {
                   4899:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
                   4900:                     my $limit = $update;
                   4901:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   4902:                         $limit = $then;
                   4903:                     }
                   4904:                     my $activerole = 1;
                   4905:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   4906:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   4907:                     if ($activerole) {
                   4908:                         push(@liveroles,$role);
                   4909:                     }
                   4910:                 }
                   4911:             }
                   4912:             if (@liveroles) {
1.1172.2.89  raeburn  4913:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
                   4914:                     my ($accessref,$accessinfo,%access_in_dom);
                   4915:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   4916:                     if (ref($roles_by_num) eq 'ARRAY') {
                   4917:                         if (@{$roles_by_num}) {
                   4918:                             my %settings;
                   4919:                             if ($env{'request.course.id'} eq $cid) {
                   4920:                                 foreach my $envkey (keys(%env)) {
                   4921:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   4922:                                         $settings{$1} = $env{$envkey};
                   4923:                                     }
                   4924:                                 }
                   4925:                             } else {
                   4926:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   4927:                             }
                   4928:                             my %setincrs;
                   4929:                             if ($settings{'internal.adhocaccess'}) {
                   4930:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   4931:                             }
                   4932:                             my @statuses;
                   4933:                             if ($env{'environment.inststatus'}) {
                   4934:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   4935:                             }
                   4936:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   4937:                             if (ref($accessref) eq 'HASH') {
                   4938:                                 %access_in_dom = %{$accessref};
                   4939:                             }
                   4940:                             foreach my $role (@{$roles_by_num}) {
                   4941:                                 my ($curraccess,@okstatus,@personnel);
                   4942:                                 if ($setincrs{$role}) {
                   4943:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   4944:                                     if ($curraccess eq 'status') {
                   4945:                                         @okstatus = split(/\&/,$rest);
                   4946:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4947:                                         @personnel = split(/\&/,$rest);
                   4948:                                     }
                   4949:                                 } else {
                   4950:                                     $curraccess = $access_in_dom{$role};
                   4951:                                     if (ref($accessinfo) eq 'HASH') {
                   4952:                                         if ($curraccess eq 'status') {
                   4953:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   4954:                                                 @okstatus = @{$accessinfo->{$role}};
                   4955:                                             }
                   4956:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4957:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   4958:                                                 @personnel = @{$accessinfo->{$role}};
                   4959:                                             }
                   4960:                                         }
                   4961:                                     }
                   4962:                                 }
                   4963:                                 if ($curraccess eq 'none') {
                   4964:                                     next;
                   4965:                                 } elsif ($curraccess eq 'all') {
                   4966:                                     push(@possroles,$role);
1.1172.2.90  raeburn  4967:                                 } elsif ($curraccess eq 'dh') {
                   4968:                                     if (grep(/^dh$/,@liveroles)) {
                   4969:                                         push(@possroles,$role);
                   4970:                                     } else {
                   4971:                                         next;
                   4972:                                     }
                   4973:                                 } elsif ($curraccess eq 'da') {
                   4974:                                     if (grep(/^da$/,@liveroles)) {
                   4975:                                         push(@possroles,$role);
                   4976:                                     } else {
                   4977:                                         next;
                   4978:                                     }
1.1172.2.89  raeburn  4979:                                 } elsif ($curraccess eq 'status') {
                   4980:                                     if (@okstatus) {
                   4981:                                         if (!@statuses) {
                   4982:                                             if (grep(/^default$/,@okstatus)) {
                   4983:                                                 push(@possroles,$role);
                   4984:                                             }
                   4985:                                         } else {
                   4986:                                             foreach my $status (@okstatus) {
                   4987:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   4988:                                                     push(@possroles,$role);
                   4989:                                                     last;
                   4990:                                                 }
                   4991:                                             }
                   4992:                                         }
                   4993:                                     }
                   4994:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4995:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   4996:                                         if ($curraccess eq 'exc') {
                   4997:                                             push(@possroles,$role);
                   4998:                                         }
                   4999:                                     } elsif ($curraccess eq 'inc') {
                   5000:                                         push(@possroles,$role);
                   5001:                                     }
                   5002:                                 }
                   5003:                             }
                   5004:                         }
                   5005:                     }
                   5006:                 }
                   5007:             }
                   5008:         }
                   5009:     }
                   5010:     unless (ref($description) eq 'HASH') {
                   5011:         if (ref($roles_by_num) eq 'ARRAY') {
                   5012:             my %desc;
                   5013:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   5014:             $description = \%desc;
                   5015:         } else {
                   5016:             $description = {};
                   5017:         }
                   5018:     }
                   5019:     return (\@possroles,$description);
                   5020: }
                   5021: 
1.399     www      5022: # ----------------------------------------------------- Frontpage Announcements
                   5023: #
                   5024: #
                   5025: 
                   5026: sub postannounce {
                   5027:     my ($server,$text)=@_;
1.844     albertel 5028:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      5029:     unless ($text=~/\w/) { $text=''; }
                   5030:     return &reply('setannounce:'.&escape($text),$server);
                   5031: }
                   5032: 
                   5033: sub getannounce {
1.448     albertel 5034: 
1.1172.2.96  raeburn  5035:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      5036: 	my $announcement='';
1.800     albertel 5037: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 5038: 	close($fh);
1.399     www      5039: 	if ($announcement=~/\w/) { 
                   5040: 	    return 
                   5041:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 5042:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      5043: 	} else {
                   5044: 	    return '';
                   5045: 	}
                   5046:     } else {
                   5047: 	return '';
                   5048:     }
1.351     www      5049: }
1.353     www      5050: 
                   5051: # ---------------------------------------------------------- Course ID routines
                   5052: # Deal with domain's nohist_courseid.db files
                   5053: #
                   5054: 
                   5055: sub courseidput {
1.921     raeburn  5056:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  5057:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  5058:     my $outcome;
                   5059:     if ($caller eq 'timeonly') {
                   5060:         my $cids = '';
                   5061:         foreach my $item (keys(%$storehash)) {
                   5062:             $cids.=&escape($item).'&';
                   5063:         }
                   5064:         $cids=~s/\&$//;
                   5065:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   5066:                           $coursehome);       
                   5067:     } else {
                   5068:         my $items = '';
                   5069:         foreach my $item (keys(%$storehash)) {
                   5070:             $items.= &escape($item).'='.
                   5071:                      &freeze_escape($$storehash{$item}).'&';
                   5072:         }
                   5073:         $items=~s/\&$//;
                   5074:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   5075:                           $coursehome);
1.918     raeburn  5076:     }
                   5077:     if ($outcome eq 'unknown_cmd') {
                   5078:         my $what;
                   5079:         foreach my $cid (keys(%$storehash)) {
                   5080:             $what .= &escape($cid).'=';
1.921     raeburn  5081:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  5082:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  5083:             }
                   5084:             $what =~ s/\:$/&/;
                   5085:         }
                   5086:         $what =~ s/\&$//;  
                   5087:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   5088:     } else {
                   5089:         return $outcome;
                   5090:     }
1.353     www      5091: }
                   5092: 
                   5093: sub courseiddump {
1.921     raeburn  5094:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  5095:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  5096:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38  raeburn  5097:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68  raeburn  5098:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  5099:     my $as_hash = 1;
                   5100:     my %returnhash;
                   5101:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 5102:     my %libserv = &all_library();
                   5103:     foreach my $tryserver (keys(%libserv)) {
                   5104:         if ( (  $hostidflag == 1 
                   5105: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5106: 	     || (!defined($hostidflag)) ) {
                   5107: 
1.918     raeburn  5108: 	    if (($domfilter eq '') ||
                   5109: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  5110:                 my $rep;
                   5111:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   5112:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   5113:                         join(":", (&host_domain($tryserver), $sincefilter,
                   5114:                                 &escape($descfilter), &escape($instcodefilter),
                   5115:                                 &escape($ownerfilter), &escape($coursefilter),
                   5116:                                 &escape($typefilter), &escape($regexp_ok),
                   5117:                                 $as_hash, &escape($selfenrollonly),
                   5118:                                 &escape($catfilter), $showhidden, $caller,
                   5119:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   5120:                                 &escape($createdbefore), &escape($createdafter),
1.1172.2.68  raeburn  5121:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5122:                                 $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22  raeburn  5123:                 } else {
                   5124:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5125:                              $sincefilter.':'.&escape($descfilter).':'.
                   5126:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5127:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5128:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5129:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5130:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5131:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5132:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68  raeburn  5133:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5134:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22  raeburn  5135:                 }
                   5136: 
1.918     raeburn  5137:                 my @pairs=split(/\&/,$rep);
                   5138:                 foreach my $item (@pairs) {
                   5139:                     my ($key,$value)=split(/\=/,$item,2);
                   5140:                     $key = &unescape($key);
                   5141:                     next if ($key =~ /^error: 2 /);
                   5142:                     my $result = &thaw_unescape($value);
                   5143:                     if (ref($result) eq 'HASH') {
                   5144:                         $returnhash{$key}=$result;
                   5145:                     } else {
1.921     raeburn  5146:                         my @responses = split(/:/,$value);
                   5147:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5148:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5149:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5150:                         }
1.1008    raeburn  5151:                     }
1.353     www      5152:                 }
                   5153:             }
                   5154:         }
                   5155:     }
                   5156:     return %returnhash;
                   5157: }
                   5158: 
1.1055    raeburn  5159: sub courselastaccess {
                   5160:     my ($cdom,$cnum,$hostidref) = @_;
                   5161:     my %returnhash;
                   5162:     if ($cdom && $cnum) {
                   5163:         my $chome = &homeserver($cnum,$cdom);
                   5164:         if ($chome ne 'no_host') {
                   5165:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5166:             &extract_lastaccess(\%returnhash,$rep);
                   5167:         }
                   5168:     } else {
                   5169:         if (!$cdom) { $cdom=''; }
                   5170:         my %libserv = &all_library();
                   5171:         foreach my $tryserver (keys(%libserv)) {
                   5172:             if (ref($hostidref) eq 'ARRAY') {
                   5173:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5174:             } 
                   5175:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5176:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5177:                 &extract_lastaccess(\%returnhash,$rep);
                   5178:             }
                   5179:         }
                   5180:     }
                   5181:     return %returnhash;
                   5182: }
                   5183: 
                   5184: sub extract_lastaccess {
                   5185:     my ($returnhash,$rep) = @_;
                   5186:     if (ref($returnhash) eq 'HASH') {
                   5187:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5188:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5189:                  $rep eq '') {
                   5190:             my @pairs=split(/\&/,$rep);
                   5191:             foreach my $item (@pairs) {
                   5192:                 my ($key,$value)=split(/\=/,$item,2);
                   5193:                 $key = &unescape($key);
                   5194:                 next if ($key =~ /^error: 2 /);
                   5195:                 $returnhash->{$key} = &thaw_unescape($value);
                   5196:             }
                   5197:         }
                   5198:     }
                   5199:     return;
                   5200: }
                   5201: 
1.658     raeburn  5202: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5203: 
                   5204: sub dcmailput {
1.685     raeburn  5205:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5206:     my $status = &Apache::lonnet::critical(
1.740     www      5207:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5208:        &escape($message),$server);
1.662     raeburn  5209:     return $status;
                   5210: }
                   5211: 
1.658     raeburn  5212: sub dcmaildump {
                   5213:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5214:     my %returnhash=();
1.846     albertel 5215: 
                   5216:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5217:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5218:                                                          &escape($enddate).':';
                   5219: 	my @esc_senders=map { &escape($_)} @$senders;
                   5220: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5221: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5222:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5223:             if (($key) && ($value)) {
                   5224:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5225:             }
                   5226:         }
                   5227:     }
                   5228:     return %returnhash;
                   5229: }
1.662     raeburn  5230: # ---------------------------------------------------------- Domain roles
                   5231: 
                   5232: sub get_domain_roles {
                   5233:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5234:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5235:         $startdate = '.';
                   5236:     }
1.1018    raeburn  5237:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5238:         $enddate = '.';
                   5239:     }
1.922     raeburn  5240:     my $rolelist;
                   5241:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  5242:         $rolelist = join('&',@{$roles});
1.922     raeburn  5243:     }
1.662     raeburn  5244:     my %personnel = ();
1.841     albertel 5245: 
                   5246:     my %servers = &get_servers($dom,'library');
                   5247:     foreach my $tryserver (keys(%servers)) {
                   5248: 	%{$personnel{$tryserver}}=();
                   5249: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5250: 					    &escape($startdate).':'.
                   5251: 					    &escape($enddate).':'.
                   5252: 					    &escape($rolelist), $tryserver))) {
                   5253: 	    my ($key,$value) = split(/\=/,$line,2);
                   5254: 	    if (($key) && ($value)) {
                   5255: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5256: 	    }
                   5257: 	}
1.662     raeburn  5258:     }
                   5259:     return %personnel;
                   5260: }
1.658     raeburn  5261: 
1.1172.2.89  raeburn  5262: sub get_active_domroles {
                   5263:     my ($dom,$roles) = @_;
                   5264:     return () unless (ref($roles) eq 'ARRAY');
                   5265:     my $now = time;
                   5266:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5267:     my %domroles;
                   5268:     foreach my $server (keys(%dompersonnel)) {
                   5269:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5270:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5271:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5272:         }
                   5273:     }
                   5274:     return %domroles;
                   5275: }
                   5276: 
1.1057    www      5277: # ----------------------------------------------------------- Interval timing 
1.149     www      5278: 
1.1153    www      5279: {
                   5280: # Caches needed for speedup of navmaps
                   5281: # We don't want to cache this for very long at all (5 seconds at most)
                   5282: # 
                   5283: # The user for whom we cache
                   5284: my $cachedkey='';
                   5285: # The cached times for this user
                   5286: my %cachedtimes=();
                   5287: # When this was last done
1.1172.2.66  raeburn  5288: my $cachedtime='';
1.1153    www      5289: 
                   5290: sub load_all_first_access {
1.1154    raeburn  5291:     my ($uname,$udom)=@_;
1.1156    www      5292:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2  raeburn  5293:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  5294:         return;
                   5295:     }
                   5296:     $cachedtime=time;
                   5297:     $cachedkey=$uname.':'.$udom;
                   5298:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5299: }
                   5300: 
1.504     albertel 5301: sub get_first_access {
1.1162    raeburn  5302:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 5303:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5304:     if ($argsymb) { $symb=$argsymb; }
                   5305:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5306:     if ($argmap) { $map = $argmap; }
1.926     albertel 5307:     if ($type eq 'course') {
                   5308: 	$res='course';
                   5309:     } elsif ($type eq 'map') {
1.588     albertel 5310: 	$res=&symbread($map);
                   5311:     } else {
                   5312: 	$res=$symb;
                   5313:     }
1.1153    www      5314:     &load_all_first_access($uname,$udom);
                   5315:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5316: }
                   5317: 
                   5318: sub set_first_access {
1.1162    raeburn  5319:     my ($type,$interval)=@_;
1.790     albertel 5320:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5321:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5322:     if ($type eq 'course') {
                   5323: 	$res='course';
                   5324:     } elsif ($type eq 'map') {
1.588     albertel 5325: 	$res=&symbread($map);
                   5326:     } else {
                   5327: 	$res=$symb;
                   5328:     }
1.1153    www      5329:     $cachedkey='';
1.1162    raeburn  5330:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1172.2.102  raeburn  5331:     if ($firstaccess) {
                   5332:         &logthis("First access time already set ($firstaccess) when attempting ".
                   5333:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
                   5334:                  "in $courseid");
                   5335:         return 'already_set';
                   5336:     } else {
1.1162    raeburn  5337:         my $start = time;
                   5338: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5339:                           $udom,$uname);
                   5340:         if ($putres eq 'ok') {
                   5341:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5342:                  $udom,$uname); 
                   5343:             &appenv(
                   5344:                      {
                   5345:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5346:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5347:                      }
                   5348:                   );
1.1172.2.97  raeburn  5349:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5350:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5351:             }
1.1172.2.102  raeburn  5352:         } elsif ($putres ne 'refused') {
                   5353:             &logthis("Result: $putres when attempting to set first access time ".
                   5354:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  5355:         }
                   5356:         return $putres;
1.505     albertel 5357:     }
                   5358:     return 'already_set';
1.504     albertel 5359: }
1.1153    www      5360: }
1.1172.2.32  raeburn  5361: 
                   5362: sub checkout {
                   5363:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   5364:     my $now=time;
                   5365:     my $lonhost=$perlvar{'lonHostID'};
                   5366:     my $infostr=&escape(
                   5367:                  'CHECKOUTTOKEN&'.
                   5368:                  $tuname.'&'.
                   5369:                  $tudom.'&'.
                   5370:                  $tcrsid.'&'.
                   5371:                  $symb.'&'.
                   5372:                  $now.'&'.$ENV{'REMOTE_ADDR'});
                   5373:     my $token=&reply('tmpput:'.$infostr,$lonhost);
                   5374:     if ($token=~/^error\:/) {
                   5375:         &logthis("<font color=\"blue\">WARNING: ".
                   5376:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5377:                  "</font>");
                   5378:         return '';
                   5379:     }
                   5380: 
                   5381:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   5382:     $token=~tr/a-z/A-Z/;
                   5383: 
                   5384:     my %infohash=('resource.0.outtoken' => $token,
                   5385:                   'resource.0.checkouttime' => $now,
                   5386:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
                   5387: 
                   5388:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5389:        return '';
                   5390:     } else {
                   5391:         &logthis("<font color=\"blue\">WARNING: ".
                   5392:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5393:                  "</font>");
                   5394:     }
                   5395: 
                   5396:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5397:                          &escape('Checkout '.$infostr.' - '.
                   5398:                                                  $token)) ne 'ok') {
                   5399:         return '';
                   5400:     } else {
                   5401:         &logthis("<font color=\"blue\">WARNING: ".
                   5402:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5403:                  "</font>");
                   5404:     }
                   5405:     return $token;
                   5406: }
                   5407: 
                   5408: # ------------------------------------------------------------ Check in an item
                   5409: 
                   5410: sub checkin {
                   5411:     my $token=shift;
                   5412:     my $now=time;
                   5413:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   5414:     $lonhost=~tr/A-Z/a-z/;
                   5415:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
                   5416:     $dtoken=~s/\W/\_/g;
                   5417:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                   5418:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   5419: 
                   5420:     unless (($tuname) && ($tudom)) {
                   5421:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   5422:         return '';
                   5423:     }
                   5424: 
                   5425:     unless (&allowed('mgr',$tcrsid)) {
                   5426:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   5427:                  $env{'user.name'}.' - '.$env{'user.domain'});
                   5428:         return '';
                   5429:     }
                   5430: 
                   5431:     my %infohash=('resource.0.intoken' => $token,
                   5432:                   'resource.0.checkintime' => $now,
                   5433:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
                   5434: 
                   5435:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5436:        return '';
                   5437:     }
                   5438: 
                   5439:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5440:                          &escape('Checkin - '.$token)) ne 'ok') {
                   5441:         return '';
                   5442:     }
                   5443: 
                   5444:     return ($symb,$tuname,$tudom,$tcrsid);
                   5445: }
                   5446: 
1.110     www      5447: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5448: 
                   5449: sub expirespread {
                   5450:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5451:     my $cid=$env{'request.course.id'}; 
1.110     www      5452:     if ($cid) {
                   5453:        my $now=time;
                   5454:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5455:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5456:                             $env{'course.'.$cid.'.num'}.
1.110     www      5457: 	        	    ':nohist_expirationdates:'.
                   5458:                             &escape($key).'='.$now,
1.620     albertel 5459:                             $env{'course.'.$cid.'.home'})
1.110     www      5460:     }
                   5461:     return 'ok';
1.14      www      5462: }
                   5463: 
1.109     www      5464: # ----------------------------------------------------- Devalidate Spreadsheets
                   5465: 
                   5466: sub devalidate {
1.325     www      5467:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5468:     my $cid=$env{'request.course.id'}; 
1.109     www      5469:     if ($cid) {
1.391     matthew  5470:         # delete the stored spreadsheets for
                   5471:         # - the student level sheet of this user in course's homespace
                   5472:         # - the assessment level sheet for this resource 
                   5473:         #   for this user in user's homespace
1.553     albertel 5474: 	# - current conditional state info
1.325     www      5475: 	my $key=$uname.':'.$udom.':';
1.109     www      5476:         my $status=
1.299     matthew  5477: 	    &del('nohist_calculatedsheets',
1.391     matthew  5478: 		 [$key.'studentcalc:'],
1.620     albertel 5479: 		 $env{'course.'.$cid.'.domain'},
                   5480: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5481: 		.' '.
                   5482: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5483: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5484:         unless ($status eq 'ok ok') {
                   5485:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5486:                     $uname.' at '.$udom.' for '.
1.109     www      5487: 		    $symb.': '.$status);
1.133     albertel 5488:         }
1.553     albertel 5489: 	&delenv('user.state.'.$cid);
1.109     www      5490:     }
                   5491: }
                   5492: 
1.265     albertel 5493: sub get_scalar {
                   5494:     my ($string,$end) = @_;
                   5495:     my $value;
                   5496:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5497: 	$value = $1;
                   5498:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5499: 	$value = $1;
                   5500:     }
                   5501:     return &unescape($value);
                   5502: }
                   5503: 
                   5504: sub array2str {
                   5505:   my (@array) = @_;
                   5506:   my $result=&arrayref2str(\@array);
                   5507:   $result=~s/^__ARRAY_REF__//;
                   5508:   $result=~s/__END_ARRAY_REF__$//;
                   5509:   return $result;
                   5510: }
                   5511: 
1.204     albertel 5512: sub arrayref2str {
                   5513:   my ($arrayref) = @_;
1.265     albertel 5514:   my $result='__ARRAY_REF__';
1.204     albertel 5515:   foreach my $elem (@$arrayref) {
1.265     albertel 5516:     if(ref($elem) eq 'ARRAY') {
                   5517:       $result.=&arrayref2str($elem).'&';
                   5518:     } elsif(ref($elem) eq 'HASH') {
                   5519:       $result.=&hashref2str($elem).'&';
                   5520:     } elsif(ref($elem)) {
                   5521:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5522:     } else {
                   5523:       $result.=&escape($elem).'&';
                   5524:     }
                   5525:   }
                   5526:   $result=~s/\&$//;
1.265     albertel 5527:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5528:   return $result;
                   5529: }
                   5530: 
1.168     albertel 5531: sub hash2str {
1.204     albertel 5532:   my (%hash) = @_;
                   5533:   my $result=&hashref2str(\%hash);
1.265     albertel 5534:   $result=~s/^__HASH_REF__//;
                   5535:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5536:   return $result;
                   5537: }
                   5538: 
                   5539: sub hashref2str {
                   5540:   my ($hashref)=@_;
1.265     albertel 5541:   my $result='__HASH_REF__';
1.800     albertel 5542:   foreach my $key (sort(keys(%$hashref))) {
                   5543:     if (ref($key) eq 'ARRAY') {
                   5544:       $result.=&arrayref2str($key).'=';
                   5545:     } elsif (ref($key) eq 'HASH') {
                   5546:       $result.=&hashref2str($key).'=';
                   5547:     } elsif (ref($key)) {
1.265     albertel 5548:       $result.='=';
1.800     albertel 5549:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5550:     } else {
1.1132    raeburn  5551: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5552:     }
                   5553: 
1.800     albertel 5554:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5555:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5556:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5557:       $result.=&hashref2str($hashref->{$key}).'&';
                   5558:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5559:        $result.='&';
1.800     albertel 5560:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5561:     } else {
1.800     albertel 5562:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5563:     }
                   5564:   }
1.168     albertel 5565:   $result=~s/\&$//;
1.265     albertel 5566:   $result .= '__END_HASH_REF__';
1.168     albertel 5567:   return $result;
                   5568: }
                   5569: 
                   5570: sub str2hash {
1.265     albertel 5571:     my ($string)=@_;
                   5572:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5573:     return %$hash;
                   5574: }
                   5575: 
                   5576: sub str2hashref {
1.168     albertel 5577:   my ($string) = @_;
1.265     albertel 5578: 
                   5579:   my %hash;
                   5580: 
                   5581:   if($string !~ /^__HASH_REF__/) {
                   5582:       if (! ($string eq '' || !defined($string))) {
                   5583: 	  $hash{'error'}='Not hash reference';
                   5584:       }
                   5585:       return (\%hash, $string);
                   5586:   }
                   5587: 
                   5588:   $string =~ s/^__HASH_REF__//;
                   5589: 
                   5590:   while($string !~ /^__END_HASH_REF__/) {
                   5591:       #key
                   5592:       my $key='';
                   5593:       if($string =~ /^__HASH_REF__/) {
                   5594:           ($key, $string)=&str2hashref($string);
                   5595:           if(defined($key->{'error'})) {
                   5596:               $hash{'error'}='Bad data';
                   5597:               return (\%hash, $string);
                   5598:           }
                   5599:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5600:           ($key, $string)=&str2arrayref($string);
                   5601:           if($key->[0] eq 'Array reference error') {
                   5602:               $hash{'error'}='Bad data';
                   5603:               return (\%hash, $string);
                   5604:           }
                   5605:       } else {
                   5606:           $string =~ s/^(.*?)=//;
1.267     albertel 5607: 	  $key=&unescape($1);
1.265     albertel 5608:       }
                   5609:       $string =~ s/^=//;
                   5610: 
                   5611:       #value
                   5612:       my $value='';
                   5613:       if($string =~ /^__HASH_REF__/) {
                   5614:           ($value, $string)=&str2hashref($string);
                   5615:           if(defined($value->{'error'})) {
                   5616:               $hash{'error'}='Bad data';
                   5617:               return (\%hash, $string);
                   5618:           }
                   5619:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5620:           ($value, $string)=&str2arrayref($string);
                   5621:           if($value->[0] eq 'Array reference error') {
                   5622:               $hash{'error'}='Bad data';
                   5623:               return (\%hash, $string);
                   5624:           }
                   5625:       } else {
                   5626: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5627:       }
                   5628:       $string =~ s/^&//;
                   5629: 
                   5630:       $hash{$key}=$value;
1.204     albertel 5631:   }
1.265     albertel 5632: 
                   5633:   $string =~ s/^__END_HASH_REF__//;
                   5634: 
                   5635:   return (\%hash, $string);
1.204     albertel 5636: }
                   5637: 
                   5638: sub str2array {
1.265     albertel 5639:     my ($string)=@_;
                   5640:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5641:     return @$array;
                   5642: }
                   5643: 
                   5644: sub str2arrayref {
1.204     albertel 5645:   my ($string) = @_;
1.265     albertel 5646:   my @array;
                   5647: 
                   5648:   if($string !~ /^__ARRAY_REF__/) {
                   5649:       if (! ($string eq '' || !defined($string))) {
                   5650: 	  $array[0]='Array reference error';
                   5651:       }
                   5652:       return (\@array, $string);
                   5653:   }
                   5654: 
                   5655:   $string =~ s/^__ARRAY_REF__//;
                   5656: 
                   5657:   while($string !~ /^__END_ARRAY_REF__/) {
                   5658:       my $value='';
                   5659:       if($string =~ /^__HASH_REF__/) {
                   5660:           ($value, $string)=&str2hashref($string);
                   5661:           if(defined($value->{'error'})) {
                   5662:               $array[0] ='Array reference error';
                   5663:               return (\@array, $string);
                   5664:           }
                   5665:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5666:           ($value, $string)=&str2arrayref($string);
                   5667:           if($value->[0] eq 'Array reference error') {
                   5668:               $array[0] ='Array reference error';
                   5669:               return (\@array, $string);
                   5670:           }
                   5671:       } else {
                   5672: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5673:       }
                   5674:       $string =~ s/^&//;
                   5675: 
                   5676:       push(@array, $value);
1.191     harris41 5677:   }
1.265     albertel 5678: 
                   5679:   $string =~ s/^__END_ARRAY_REF__//;
                   5680: 
                   5681:   return (\@array, $string);
1.168     albertel 5682: }
                   5683: 
1.167     albertel 5684: # -------------------------------------------------------------------Temp Store
                   5685: 
1.168     albertel 5686: sub tmpreset {
                   5687:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5688:   if (!$symb) {
                   5689:     $symb=&symbread();
1.620     albertel 5690:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5691:   }
                   5692:   $symb=escape($symb);
                   5693: 
1.620     albertel 5694:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5695:   $namespace=~s/\//\_/g;
                   5696:   $namespace=~s/\W//g;
                   5697: 
1.620     albertel 5698:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5699:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5700:   if ($domain eq 'public' && $stuname eq 'public') {
                   5701:       $stuname=$ENV{'REMOTE_ADDR'};
                   5702:   }
1.1117    foxr     5703:   my $path=LONCAPA::tempdir();
1.168     albertel 5704:   my %hash;
                   5705:   if (tie(%hash,'GDBM_File',
                   5706: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5707: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5708:     foreach my $key (keys(%hash)) {
1.180     albertel 5709:       if ($key=~ /:$symb/) {
1.168     albertel 5710: 	delete($hash{$key});
                   5711:       }
                   5712:     }
                   5713:   }
                   5714: }
                   5715: 
1.167     albertel 5716: sub tmpstore {
1.168     albertel 5717:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5718: 
                   5719:   if (!$symb) {
                   5720:     $symb=&symbread();
1.620     albertel 5721:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5722:   }
                   5723:   $symb=escape($symb);
                   5724: 
                   5725:   if (!$namespace) {
                   5726:     # I don't think we would ever want to store this for a course.
                   5727:     # it seems this will only be used if we don't have a course.
1.620     albertel 5728:     #$namespace=$env{'request.course.id'};
1.168     albertel 5729:     #if (!$namespace) {
1.620     albertel 5730:       $namespace=$env{'request.state'};
1.168     albertel 5731:     #}
                   5732:   }
                   5733:   $namespace=~s/\//\_/g;
                   5734:   $namespace=~s/\W//g;
1.620     albertel 5735:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5736:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5737:   if ($domain eq 'public' && $stuname eq 'public') {
                   5738:       $stuname=$ENV{'REMOTE_ADDR'};
                   5739:   }
1.168     albertel 5740:   my $now=time;
                   5741:   my %hash;
1.1117    foxr     5742:   my $path=LONCAPA::tempdir();
1.168     albertel 5743:   if (tie(%hash,'GDBM_File',
                   5744: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5745: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5746:     $hash{"version:$symb"}++;
                   5747:     my $version=$hash{"version:$symb"};
                   5748:     my $allkeys=''; 
                   5749:     foreach my $key (keys(%$storehash)) {
                   5750:       $allkeys.=$key.':';
1.591     albertel 5751:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5752:     }
                   5753:     $hash{"$version:$symb:timestamp"}=$now;
                   5754:     $allkeys.='timestamp';
                   5755:     $hash{"$version:keys:$symb"}=$allkeys;
                   5756:     if (untie(%hash)) {
                   5757:       return 'ok';
                   5758:     } else {
                   5759:       return "error:$!";
                   5760:     }
                   5761:   } else {
                   5762:     return "error:$!";
                   5763:   }
                   5764: }
1.167     albertel 5765: 
1.168     albertel 5766: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5767: 
1.168     albertel 5768: sub tmprestore {
                   5769:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5770: 
1.168     albertel 5771:   if (!$symb) {
                   5772:     $symb=&symbread();
1.620     albertel 5773:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5774:   }
                   5775:   $symb=escape($symb);
                   5776: 
1.620     albertel 5777:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5778: 
1.620     albertel 5779:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5780:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5781:   if ($domain eq 'public' && $stuname eq 'public') {
                   5782:       $stuname=$ENV{'REMOTE_ADDR'};
                   5783:   }
1.168     albertel 5784:   my %returnhash;
                   5785:   $namespace=~s/\//\_/g;
                   5786:   $namespace=~s/\W//g;
                   5787:   my %hash;
1.1117    foxr     5788:   my $path=LONCAPA::tempdir();
1.168     albertel 5789:   if (tie(%hash,'GDBM_File',
                   5790: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5791: 	  &GDBM_READER(),0640)) {
1.168     albertel 5792:     my $version=$hash{"version:$symb"};
                   5793:     $returnhash{'version'}=$version;
                   5794:     my $scope;
                   5795:     for ($scope=1;$scope<=$version;$scope++) {
                   5796:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5797:       my @keys=split(/:/,$vkeys);
                   5798:       my $key;
                   5799:       $returnhash{"$scope:keys"}=$vkeys;
                   5800:       foreach $key (@keys) {
1.591     albertel 5801: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   5802: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 5803:       }
                   5804:     }
1.168     albertel 5805:     if (!(untie(%hash))) {
                   5806:       return "error:$!";
                   5807:     }
                   5808:   } else {
                   5809:     return "error:$!";
                   5810:   }
                   5811:   return %returnhash;
1.167     albertel 5812: }
                   5813: 
1.9       www      5814: # ----------------------------------------------------------------------- Store
                   5815: 
                   5816: sub store {
1.1172.2.64  raeburn  5817:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5818:     my $home='';
                   5819: 
1.168     albertel 5820:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5821: 
1.213     www      5822:     $symb=&symbclean($symb);
1.122     albertel 5823:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5824: 
1.620     albertel 5825:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5826:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5827: 
                   5828:     &devalidate($symb,$stuname,$domain);
1.109     www      5829: 
                   5830:     $symb=escape($symb);
1.187     www      5831:     if (!$namespace) { 
1.620     albertel 5832:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5833:           return ''; 
                   5834:        } 
                   5835:     }
1.620     albertel 5836:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5837: 
                   5838:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5839:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   5840: 
1.12      www      5841:     my $namevalue='';
1.800     albertel 5842:     foreach my $key (keys(%$storehash)) {
                   5843:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5844:     }
1.12      www      5845:     $namevalue=~s/\&$//;
1.187     www      5846:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64  raeburn  5847:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      5848: }
                   5849: 
1.47      www      5850: # -------------------------------------------------------------- Critical Store
                   5851: 
                   5852: sub cstore {
1.1172.2.64  raeburn  5853:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5854:     my $home='';
                   5855: 
1.168     albertel 5856:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5857: 
1.213     www      5858:     $symb=&symbclean($symb);
1.122     albertel 5859:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5860: 
1.620     albertel 5861:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5862:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5863: 
                   5864:     &devalidate($symb,$stuname,$domain);
1.109     www      5865: 
                   5866:     $symb=escape($symb);
1.187     www      5867:     if (!$namespace) { 
1.620     albertel 5868:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5869:           return ''; 
                   5870:        } 
                   5871:     }
1.620     albertel 5872:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5873: 
                   5874:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5875:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 5876: 
1.47      www      5877:     my $namevalue='';
1.800     albertel 5878:     foreach my $key (keys(%$storehash)) {
                   5879:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5880:     }
1.47      www      5881:     $namevalue=~s/\&$//;
1.187     www      5882:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      5883:     return critical
1.1172.2.64  raeburn  5884:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      5885: }
                   5886: 
1.9       www      5887: # --------------------------------------------------------------------- Restore
                   5888: 
                   5889: sub restore {
1.124     www      5890:     my ($symb,$namespace,$domain,$stuname) = @_;
                   5891:     my $home='';
                   5892: 
1.168     albertel 5893:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5894: 
1.122     albertel 5895:     if (!$symb) {
1.1172.2.26  raeburn  5896:         return if ($namespace eq 'courserequests');
                   5897:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 5898:     } else {
1.1172.2.26  raeburn  5899:         unless ($namespace eq 'courserequests') {
                   5900:             $symb=&escape(&symbclean($symb));
                   5901:         }
1.122     albertel 5902:     }
1.188     www      5903:     if (!$namespace) { 
1.620     albertel 5904:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      5905:           return ''; 
                   5906:        } 
                   5907:     }
1.620     albertel 5908:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5909:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   5910:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 5911:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   5912: 
1.12      www      5913:     my %returnhash=();
1.800     albertel 5914:     foreach my $line (split(/\&/,$answer)) {
                   5915: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 5916:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 5917:     }
1.75      www      5918:     my $version;
                   5919:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 5920:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   5921:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 5922:        }
1.75      www      5923:     }
1.13      www      5924:     return %returnhash;
1.34      www      5925: }
                   5926: 
                   5927: # ---------------------------------------------------------- Course Description
1.1118    foxr     5928: #
                   5929: #  
1.34      www      5930: 
                   5931: sub coursedescription {
1.731     albertel 5932:     my ($courseid,$args)=@_;
1.34      www      5933:     $courseid=~s/^\///;
1.49      www      5934:     $courseid=~s/\_/\//g;
1.34      www      5935:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 5936:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 5937:     my $normalid=$cdomain.'_'.$cnum;
                   5938:     # need to always cache even if we get errors otherwise we keep 
                   5939:     # trying and trying and trying to get the course description.
                   5940:     my %envhash=();
                   5941:     my %returnhash=();
1.731     albertel 5942:     
                   5943:     my $expiretime=600;
                   5944:     if ($env{'request.course.id'} eq $normalid) {
                   5945: 	$expiretime=120;
                   5946:     }
                   5947: 
                   5948:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   5949:     if (!$args->{'freshen_cache'}
                   5950: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   5951: 	foreach my $key (keys(%env)) {
                   5952: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   5953: 	    my ($setting) = $1;
                   5954: 	    $returnhash{$setting} = $env{$key};
                   5955: 	}
                   5956: 	return %returnhash;
                   5957:     }
                   5958: 
1.1118    foxr     5959:     # get the data again
                   5960: 
1.731     albertel 5961:     if (!$args->{'one_time'}) {
                   5962: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   5963:     }
1.811     albertel 5964: 
1.34      www      5965:     if ($chome ne 'no_host') {
1.302     albertel 5966:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 5967:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     5968: 	   my $username = $env{'user.name'}; # Defult username
                   5969: 	   if(defined $args->{'user'}) {
                   5970: 	       $username = $args->{'user'};
                   5971: 	   }
1.129     albertel 5972:            $returnhash{'home'}= $chome;
                   5973: 	   $returnhash{'domain'} = $cdomain;
                   5974: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  5975:            if (!defined($returnhash{'type'})) {
                   5976:                $returnhash{'type'} = 'Course';
                   5977:            }
1.130     albertel 5978:            while (my ($name,$value) = each %returnhash) {
1.53      www      5979:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 5980:            }
1.270     www      5981:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     5982:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     5983: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      5984:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   5985:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   5986:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      5987:        }
                   5988:     }
1.731     albertel 5989:     if (!$args->{'one_time'}) {
1.949     raeburn  5990: 	&appenv(\%envhash);
1.731     albertel 5991:     }
1.302     albertel 5992:     return %returnhash;
1.461     www      5993: }
                   5994: 
1.1080    raeburn  5995: sub update_released_required {
                   5996:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   5997:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   5998:         $cid = $env{'request.course.id'};
                   5999:         $cdom = $env{'course.'.$cid.'.domain'};
                   6000:         $cnum = $env{'course.'.$cid.'.num'};
                   6001:         $chome = $env{'course.'.$cid.'.home'};
                   6002:     }
                   6003:     if ($needsrelease) {
                   6004:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   6005:         my $needsupdate;
                   6006:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   6007:             $needsupdate = 1;
                   6008:         } else {
                   6009:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   6010:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   6011:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   6012:                 $needsupdate = 1;
                   6013:             }
                   6014:         }
                   6015:         if ($needsupdate) {
                   6016:             my %needshash = (
                   6017:                              'internal.releaserequired' => $needsrelease,
                   6018:                             );
                   6019:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   6020:             if ($putresult eq 'ok') {
                   6021:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   6022:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6023:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   6024:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   6025:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   6026:                 }
                   6027:             }
                   6028:         }
                   6029:     }
                   6030:     return;
                   6031: }
                   6032: 
1.461     www      6033: # -------------------------------------------------See if a user is privileged
                   6034: 
                   6035: sub privileged {
1.1172.2.23  raeburn  6036:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 6037:     my $now = time;
1.1172.2.23  raeburn  6038:     my $roles;
                   6039:     if (ref($possroles) eq 'ARRAY') {
                   6040:         $roles = $possroles;
                   6041:     } else {
                   6042:         $roles = ['dc','su'];
                   6043:     }
                   6044:     if (ref($possdomains) eq 'ARRAY') {
                   6045:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   6046:         foreach my $dom (@{$possdomains}) {
                   6047:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   6048:                 (ref($privileged{$dom}) eq 'HASH')) {
                   6049:                 foreach my $role (@{$roles}) {
                   6050:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6051:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   6052:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   6053:                             return 1 unless (($end && $end < $now) ||
                   6054:                                              ($start && $start > $now));
                   6055:                         }
                   6056:                     }
                   6057:                 }
                   6058:             }
                   6059:         }
                   6060:     } else {
                   6061:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   6062:         my $now = time;
1.1170    droeschl 6063: 
1.1172.2.58  raeburn  6064:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 6065:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  6066:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   6067:                 return 1 unless ($tend && $tend < $now)
                   6068:                         or ($tstart && $tstart > $now);
1.1170    droeschl 6069:             }
1.1172.2.23  raeburn  6070:         }
                   6071:     }
1.461     www      6072:     return 0;
1.9       www      6073: }
1.1       albertel 6074: 
1.1172.2.23  raeburn  6075: sub privileged_by_domain {
                   6076:     my ($domains,$roles) = @_;
                   6077:     my %privileged = ();
                   6078:     my $cachetime = 60*60*24;
                   6079:     my $now = time;
                   6080:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   6081:         return %privileged;
                   6082:     }
                   6083:     foreach my $dom (@{$domains}) {
                   6084:         next if (ref($privileged{$dom}) eq 'HASH');
                   6085:         my $needroles;
                   6086:         foreach my $role (@{$roles}) {
                   6087:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   6088:             if (defined($cached)) {
                   6089:                 if (ref($result) eq 'HASH') {
                   6090:                     $privileged{$dom}{$role} = $result;
                   6091:                 }
                   6092:             } else {
                   6093:                 $needroles = 1;
                   6094:             }
                   6095:         }
                   6096:         if ($needroles) {
                   6097:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   6098:             $privileged{$dom} = {};
                   6099:             foreach my $server (keys(%dompersonnel)) {
                   6100:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   6101:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   6102:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   6103:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   6104:                         next if ($end && $end < $now);
                   6105:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   6106:                             $dompersonnel{$server}{$item};
                   6107:                     }
                   6108:                 }
                   6109:             }
                   6110:             if (ref($privileged{$dom}) eq 'HASH') {
                   6111:                 foreach my $role (@{$roles}) {
                   6112:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6113:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   6114:                     } else {
                   6115:                         my %hash = ();
                   6116:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   6117:                     }
                   6118:                 }
                   6119:             }
                   6120:         }
                   6121:     }
                   6122:     return %privileged;
                   6123: }
                   6124: 
1.103     harris41 6125: # -------------------------------------------------------- Get user privileges
1.11      www      6126: 
                   6127: sub rolesinit {
1.1169    droeschl 6128:     my ($domain, $username) = @_;
                   6129:     my %userroles = ('user.login.time' => time);
                   6130:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   6131: 
                   6132:     # firstaccess and timerinterval are related to timed maps/resources. 
                   6133:     # also, blocking can be triggered by an activating timer
                   6134:     # it's saved in the user's %env.
                   6135:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   6136:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   6137:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   6138:         %timerintchk, %timerintenv);
                   6139: 
1.1162    raeburn  6140:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 6141:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  6142:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   6143:     }
1.1169    droeschl 6144: 
1.1162    raeburn  6145:     foreach my $key (keys(%timerinterval)) {
                   6146:         my ($cid,$rest) = split(/\0/,$key);
                   6147:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   6148:     }
1.1169    droeschl 6149: 
1.11      www      6150:     my %allroles=();
1.1162    raeburn  6151:     my %allgroups=();
1.11      www      6152: 
1.1172.2.58  raeburn  6153:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 6154:         my $role = $rolesdump{$area};
                   6155:         $area =~ s/\_\w\w$//;
                   6156: 
                   6157:         my ($trole, $tend, $tstart, $group_privs);
                   6158: 
                   6159:         if ($role =~ /^cr/) {
                   6160:         # Custom role, defined by a user 
                   6161:         # e.g., user.role.cr/msu/smith/mynewrole
                   6162:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   6163:                 $trole = $1;
                   6164:                 ($tend, $tstart) = split('_', $2);
                   6165:             } else {
                   6166:                 $trole = $role;
                   6167:             }
                   6168:         } elsif ($role =~ m|^gr/|) {
                   6169:         # Role of member in a group, defined within a course/community
                   6170:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   6171:             ($trole, $tend, $tstart) = split(/_/, $role);
                   6172:             next if $tstart eq '-1';
                   6173:             ($trole, $group_privs) = split(/\//, $trole);
                   6174:             $group_privs = &unescape($group_privs);
                   6175:         } else {
                   6176:         # Just a normal role, defined in roles.tab
                   6177:             ($trole, $tend, $tstart) = split(/_/,$role);
                   6178:         }
                   6179: 
                   6180:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   6181:                  $username);
                   6182:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   6183: 
                   6184:         # role expired or not available yet?
                   6185:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   6186:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   6187: 
                   6188:         next if $area eq '' or $trole eq '';
                   6189: 
                   6190:         my $spec = "$trole.$area";
                   6191:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   6192: 
                   6193:         if ($trole =~ /^cr\//) {
                   6194:         # Custom role, defined by a user
                   6195:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6196:         } elsif ($trole eq 'gr') {
                   6197:         # Role of a member in a group, defined within a course/community
                   6198:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   6199:             next;
                   6200:         } else {
                   6201:         # Normal role, defined in roles.tab
                   6202:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6203:         }
                   6204: 
                   6205:         my $cid = $tdomain.'_'.$trest;
                   6206:         unless ($firstaccchk{$cid}) {
                   6207:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6208:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6209:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6210:                         $coursetimerstarts{$cid}{$item}; 
                   6211:                 }
                   6212:             }
                   6213:             $firstaccchk{$cid} = 1;
                   6214:         }
                   6215:         unless ($timerintchk{$cid}) {
                   6216:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6217:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6218:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6219:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6220:                 }
1.12      www      6221:             }
1.1169    droeschl 6222:             $timerintchk{$cid} = 1;
1.191     harris41 6223:         }
1.11      www      6224:     }
1.1169    droeschl 6225: 
1.1172.2.91  raeburn  6226:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6227:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6228:     $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91  raeburn  6229:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6230: 
1.1162    raeburn  6231:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6232: }
                   6233: 
1.567     raeburn  6234: sub set_arearole {
1.1172.2.19  raeburn  6235:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6236:     unless ($nolog) {
1.567     raeburn  6237: # log the associated role with the area
1.1172.2.19  raeburn  6238:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6239:     }
1.743     albertel 6240:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6241: }
                   6242: 
                   6243: sub custom_roleprivs {
                   6244:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6245:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40  raeburn  6246:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6247:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6248:         my ($rdummy,$roledef)=
                   6249:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6250:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6251:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6252:             if (defined($syspriv)) {
1.1043    raeburn  6253:                 if ($trest =~ /^$match_community$/) {
                   6254:                     $syspriv =~ s/bre\&S//; 
                   6255:                 }
1.567     raeburn  6256:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6257:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6258:             }
                   6259:             if ($tdomain ne '') {
                   6260:                 if (defined($dompriv)) {
                   6261:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6262:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6263:                 }
                   6264:                 if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89  raeburn  6265:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6266:                         my $rolename = $1;
                   6267:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6268:                     }
1.567     raeburn  6269:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6270:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6271:                 }
                   6272:             }
                   6273:         }
                   6274:     }
                   6275: }
                   6276: 
1.1172.2.89  raeburn  6277: sub course_adhocrole_privs {
                   6278:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6279:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6280:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6281:         my (%currprivs,%storeprivs);
                   6282:         foreach my $item (split(/:/,$coursepriv)) {
                   6283:             my ($priv,$restrict) = split(/\&/,$item);
                   6284:             $currprivs{$priv} = $restrict;
                   6285:         }
                   6286:         my (%possadd,%possremove,%full);
                   6287:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6288:             my ($priv,$restrict)=split(/\&/,$item);
                   6289:             $full{$priv} = $restrict;
                   6290:         }
                   6291:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   6292:              next if ($item eq '');
                   6293:              my ($rule,$rest) = split(/=/,$item);
                   6294:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   6295:              foreach my $priv (split(/:/,$rest)) {
                   6296:                  if ($priv ne '') {
                   6297:                      if ($rule eq 'off') {
                   6298:                          $possremove{$priv} = 1;
                   6299:                      } else {
                   6300:                          $possadd{$priv} = 1;
                   6301:                      }
                   6302:                  }
                   6303:              }
                   6304:          }
                   6305:          foreach my $priv (sort(keys(%full))) {
                   6306:              if (exists($currprivs{$priv})) {
                   6307:                  unless (exists($possremove{$priv})) {
                   6308:                      $storeprivs{$priv} = $currprivs{$priv};
                   6309:                  }
                   6310:              } elsif (exists($possadd{$priv})) {
                   6311:                  $storeprivs{$priv} = $full{$priv};
                   6312:              }
                   6313:          }
                   6314:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6315:      }
                   6316:      return $coursepriv;
                   6317: }
                   6318: 
1.678     raeburn  6319: sub group_roleprivs {
                   6320:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6321:     my $access = 1;
                   6322:     my $now = time;
                   6323:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6324:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6325:     if ($access) {
1.811     albertel 6326:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6327:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6328:     }
                   6329: }
1.567     raeburn  6330: 
                   6331: sub standard_roleprivs {
                   6332:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6333:     if (defined($pr{$trole.':s'})) {
                   6334:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6335:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6336:     }
                   6337:     if ($tdomain ne '') {
                   6338:         if (defined($pr{$trole.':d'})) {
                   6339:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6340:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6341:         }
                   6342:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6343:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6344:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6345:         }
                   6346:     }
                   6347: }
                   6348: 
                   6349: sub set_userprivs {
1.1064    raeburn  6350:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6351:     my $author=0;
                   6352:     my $adv=0;
1.1172.2.91  raeburn  6353:     my $rar=0;
1.678     raeburn  6354:     my %grouproles = ();
                   6355:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6356:         my @groupkeys; 
1.1000    raeburn  6357:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6358:             push(@groupkeys,$role);
                   6359:         }
                   6360:         if (ref($groups_roles) eq 'HASH') {
                   6361:             foreach my $key (keys(%{$groups_roles})) {
                   6362:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6363:                     push(@groupkeys,$key);
                   6364:                 }
                   6365:             }
                   6366:         }
                   6367:         if (@groupkeys > 0) {
                   6368:             foreach my $role (@groupkeys) {
                   6369:                 my ($trole,$area,$sec,$extendedarea);
                   6370:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6371:                     $trole = $1;
                   6372:                     $area = $2;
                   6373:                     $sec = $3;
                   6374:                     $extendedarea = $area.$sec;
                   6375:                     if (exists($$allgroups{$area})) {
                   6376:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6377:                             my $spec = $trole.'.'.$extendedarea;
                   6378:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6379:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6380:                         }
1.678     raeburn  6381:                     }
                   6382:                 }
                   6383:             }
                   6384:         }
                   6385:     }
1.800     albertel 6386:     foreach my $group (keys(%grouproles)) {
                   6387:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6388:     }
1.800     albertel 6389:     foreach my $role (keys(%{$allroles})) {
                   6390:         my %thesepriv;
1.941     raeburn  6391:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6392:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6393:             if ($item ne '') {
                   6394:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6395:                 if ($restrictions eq '') {
                   6396:                     $thesepriv{$privilege}='F';
                   6397:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6398:                     $thesepriv{$privilege}.=$restrictions;
                   6399:                 }
                   6400:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91  raeburn  6401:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6402:             }
                   6403:         }
                   6404:         my $thesestr='';
1.1104    raeburn  6405:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6406: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6407: 	}
                   6408:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6409:     }
1.1172.2.91  raeburn  6410:     return ($author,$adv,$rar);
1.567     raeburn  6411: }
                   6412: 
1.994     raeburn  6413: sub role_status {
1.1104    raeburn  6414:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6415:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40  raeburn  6416:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6417:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6418:         unless (!defined($$role) || $$role eq '') {
1.1172.2.40  raeburn  6419:             $$where = '/'.$two;
1.994     raeburn  6420:             $$trolecode=$$role.'.'.$$where;
                   6421:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6422:             $$tstatus='is';
1.1104    raeburn  6423:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6424:                 $$tstatus='future';
1.1034    raeburn  6425:                 if ($$tstart<$now) {
                   6426:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6427:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6428:                             my (%allroles,%allgroups,$group_privs,
                   6429:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6430:                             my %userroles = (
                   6431:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6432:                             );
1.1064    raeburn  6433:                             @rolecodes = ('cm'); 
1.1002    raeburn  6434:                             my $spec=$$role.'.'.$$where;
                   6435:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6436:                             if ($$role =~ /^cr\//) {
                   6437:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6438:                                 push(@rolecodes,'cr');
1.1002    raeburn  6439:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6440:                                 push(@rolecodes,$$role);
1.1002    raeburn  6441:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6442:                                                     $env{'user.name'});
1.1064    raeburn  6443:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6444:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6445:                                 $group_privs = &unescape($group_privs);
                   6446:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6447:                                 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  6448:                                 &get_groups_roles($tdomain,$trest,
                   6449:                                                   \%course_roles,\@rolecodes,
                   6450:                                                   \%groups_roles);
1.1002    raeburn  6451:                             } else {
1.1064    raeburn  6452:                                 push(@rolecodes,$$role);
1.1002    raeburn  6453:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6454:                             }
1.1172.2.91  raeburn  6455:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6456:                                                                    \%groups_roles);
1.1064    raeburn  6457:                             &appenv(\%userroles,\@rolecodes);
1.1172.2.92  raeburn  6458:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6459:                         }
                   6460:                     }
1.1034    raeburn  6461:                     $$tstatus = 'is';
1.1002    raeburn  6462:                 }
1.994     raeburn  6463:             }
                   6464:             if ($$tend) {
1.1104    raeburn  6465:                 if ($$tend<$update) {
1.994     raeburn  6466:                     $$tstatus='expired';
                   6467:                 } elsif ($$tend<$now) {
                   6468:                     $$tstatus='will_not';
                   6469:                 }
                   6470:             }
                   6471:         }
                   6472:     }
                   6473: }
                   6474: 
1.1104    raeburn  6475: sub get_groups_roles {
                   6476:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6477:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6478:                   (ref($rolecodes) eq 'ARRAY') && 
                   6479:                   (ref($groups_roles) eq 'HASH')); 
                   6480:     if (keys(%{$cdom_courseroles}) > 0) {
                   6481:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6482:         if ($cdom ne '' && $cnum ne '') {
                   6483:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6484:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6485:                     my $crsrole = $1;
                   6486:                     my $crssec = $2;
                   6487:                     if ($crsrole =~ /^cr/) {
                   6488:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6489:                             push(@{$rolecodes},'cr');
                   6490:                         }
                   6491:                     } else {
                   6492:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6493:                             push(@{$rolecodes},$crsrole);
                   6494:                         }
                   6495:                     }
                   6496:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6497:                     if ($crssec ne '') {
                   6498:                         $rolekey .= "/$crssec";
                   6499:                     }
                   6500:                     $rolekey .= './';
                   6501:                     $groups_roles->{$rolekey} = $rolecodes;
                   6502:                 }
                   6503:             }
                   6504:         }
                   6505:     }
                   6506:     return;
                   6507: }
                   6508: 
                   6509: sub delete_env_groupprivs {
                   6510:     my ($where,$courseroles,$possroles) = @_;
                   6511:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6512:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6513:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6514:         %{$courseroles->{$udom}} =
                   6515:             &get_my_roles('','','userroles',['active'],
                   6516:                           $possroles,[$udom],1);
                   6517:     }
                   6518:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6519:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6520:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6521:             my $area = '/'.$cdom.'/'.$cnum;
                   6522:             my $privkey = "user.priv.$crsrole.$area";
                   6523:             if ($crssec ne '') {
                   6524:                 $privkey .= '/'.$crssec;
                   6525:             }
                   6526:             $privkey .= ".$area/$group";
                   6527:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6528:         }
                   6529:     }
                   6530:     return;
                   6531: }
                   6532: 
1.994     raeburn  6533: sub check_adhoc_privs {
1.1172.2.86  raeburn  6534:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6535:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86  raeburn  6536:     if ($sec) {
                   6537:         $cckey .= '/'.$sec;
                   6538:     }
1.1172.2.9  raeburn  6539:     my $setprivs;
1.994     raeburn  6540:     if ($env{$cckey}) {
                   6541:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6542:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6543:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86  raeburn  6544:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6545:             $setprivs = 1;
1.994     raeburn  6546:         }
                   6547:     } else {
1.1172.2.87  raeburn  6548:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6549:         $setprivs = 1;
1.994     raeburn  6550:     }
1.1172.2.9  raeburn  6551:     return $setprivs;
1.994     raeburn  6552: }
                   6553: 
                   6554: sub set_adhoc_privileges {
1.1172.2.84  raeburn  6555: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86  raeburn  6556:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6557:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86  raeburn  6558:     if ($sec ne '') {
                   6559:         $area .= '/'.$sec;
                   6560:     }
1.994     raeburn  6561:     my $spec = $role.'.'.$area;
                   6562:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  6563:                                   $env{'user.name'},1);
1.1172.2.84  raeburn  6564:     my %rolehash = ();
1.1172.2.89  raeburn  6565:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6566:         my $rolename = $1;
1.1172.2.84  raeburn  6567:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89  raeburn  6568:         my %domdef = &get_domain_defaults($dcdom);
                   6569:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6570:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6571:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6572:             }
                   6573:         }
1.1172.2.84  raeburn  6574:     } else {
                   6575:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6576:     }
1.1172.2.91  raeburn  6577:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6578:     &appenv(\%userroles,[$role,'cm']);
1.1172.2.92  raeburn  6579:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088    raeburn  6580:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   6581:         &appenv( {'request.role'        => $spec,
                   6582:                   'request.role.domain' => $dcdom,
1.1172.2.89  raeburn  6583:                   'request.course.sec'  => $sec, 
1.1088    raeburn  6584:                  }
                   6585:                );
                   6586:         my $tadv=0;
                   6587:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6588:         &appenv({'request.role.adv'    => $tadv});
                   6589:     }
1.994     raeburn  6590: }
                   6591: 
1.12      www      6592: # --------------------------------------------------------------- get interface
                   6593: 
                   6594: sub get {
1.131     albertel 6595:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6596:    my $items='';
1.800     albertel 6597:    foreach my $item (@$storearr) {
                   6598:        $items.=&escape($item).'&';
1.191     harris41 6599:    }
1.12      www      6600:    $items=~s/\&$//;
1.620     albertel 6601:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6602:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6603:    my $uhome=&homeserver($uname,$udomain);
                   6604: 
1.133     albertel 6605:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6606:    my @pairs=split(/\&/,$rep);
1.273     albertel 6607:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6608:      return @pairs;
                   6609:    }
1.15      www      6610:    my %returnhash=();
1.42      www      6611:    my $i=0;
1.800     albertel 6612:    foreach my $item (@$storearr) {
                   6613:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6614:       $i++;
1.191     harris41 6615:    }
1.15      www      6616:    return %returnhash;
1.27      www      6617: }
                   6618: 
                   6619: # --------------------------------------------------------------- del interface
                   6620: 
                   6621: sub del {
1.133     albertel 6622:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6623:    my $items='';
1.800     albertel 6624:    foreach my $item (@$storearr) {
                   6625:        $items.=&escape($item).'&';
1.191     harris41 6626:    }
1.984     neumanie 6627: 
1.27      www      6628:    $items=~s/\&$//;
1.620     albertel 6629:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6630:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6631:    my $uhome=&homeserver($uname,$udomain);
                   6632:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6633: }
                   6634: 
                   6635: # -------------------------------------------------------------- dump interface
                   6636: 
1.1172.2.22  raeburn  6637: sub unserialize {
                   6638:     my ($rep, $escapedkeys) = @_;
                   6639: 
                   6640:     return {} if $rep =~ /^error/;
                   6641: 
                   6642:     my %returnhash=();
                   6643:     foreach my $item (split(/\&/,$rep)) {
                   6644:         my ($key, $value) = split(/=/, $item, 2);
                   6645:         $key = unescape($key) unless $escapedkeys;
                   6646:         next if $key =~ /^error: 2 /;
                   6647:         $returnhash{$key} = &thaw_unescape($value);
                   6648:     }
                   6649:     return \%returnhash;
                   6650: }
                   6651: 
                   6652: # see Lond::dump_with_regexp
                   6653: # if $escapedkeys hash keys won't get unescaped.
1.15      www      6654: sub dump {
1.1172.2.22  raeburn  6655:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 6656:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6657:     if (!$uname) { $uname=$env{'user.name'}; }
                   6658:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 6659: 
1.1172.2.55  raeburn  6660:     if ($regexp) {
                   6661:         $regexp=&escape($regexp);
                   6662:     } else {
                   6663:         $regexp='.';
                   6664:     }
1.1172.2.22  raeburn  6665:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   6666:         # user is hosted on this machine
1.1172.2.55  raeburn  6667:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  6668:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  6669:         return %{&unserialize($reply, $escapedkeys)};
                   6670:     }
1.1166    raeburn  6671:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 6672:     my @pairs=split(/\&/,$rep);
                   6673:     my %returnhash=();
1.1098    foxr     6674:     if (!($rep =~ /^error/ )) {
                   6675: 	foreach my $item (@pairs) {
                   6676: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  6677:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     6678: 	    next if ($key =~ /^error: 2 /);
                   6679: 	    $returnhash{$key}=&thaw_unescape($value);
                   6680: 	}
1.755     albertel 6681:     }
                   6682:     return %returnhash;
1.407     www      6683: }
                   6684: 
1.1098    foxr     6685: 
1.717     albertel 6686: # --------------------------------------------------------- dumpstore interface
                   6687: 
                   6688: sub dumpstore {
                   6689:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  6690:    # same as dump but keys must be escaped. They may contain colon separated
                   6691:    # lists of values that may themself contain colons (e.g. symbs).
                   6692:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 6693: }
                   6694: 
1.407     www      6695: # -------------------------------------------------------------- keys interface
                   6696: 
                   6697: sub getkeys {
                   6698:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 6699:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6700:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      6701:    my $uhome=&homeserver($uname,$udomain);
                   6702:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   6703:    my @keyarray=();
1.800     albertel 6704:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  6705:       next if ($key =~ /^error: 2 /);
1.800     albertel 6706:       push(@keyarray,&unescape($key));
1.407     www      6707:    }
                   6708:    return @keyarray;
1.318     matthew  6709: }
                   6710: 
1.319     matthew  6711: # --------------------------------------------------------------- currentdump
                   6712: sub currentdump {
1.328     matthew  6713:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 6714:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   6715:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   6716:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  6717:    my $uhome = &homeserver($sname,$sdom);
1.1172.2.50  raeburn  6718:    my $rep;
                   6719: 
                   6720:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   6721:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
                   6722:                    $courseid)));
                   6723:    } else {
                   6724:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6725:    }
                   6726: 
1.318     matthew  6727:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6728:    #
1.318     matthew  6729:    my %returnhash=();
1.319     matthew  6730:    #
                   6731:    if ($rep eq "unknown_cmd") { 
                   6732:        # an old lond will not know currentdump
                   6733:        # Do a dump and make it look like a currentdump
1.822     albertel 6734:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6735:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6736:        my %hash = @tmp;
                   6737:        @tmp=();
1.424     matthew  6738:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6739:    } else {
                   6740:        my @pairs=split(/\&/,$rep);
1.800     albertel 6741:        foreach my $pair (@pairs) {
                   6742:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6743:            my ($symb,$param) = split(/:/,$key);
                   6744:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6745:                                                         &thaw_unescape($value);
1.319     matthew  6746:        }
1.191     harris41 6747:    }
1.12      www      6748:    return %returnhash;
1.424     matthew  6749: }
                   6750: 
                   6751: sub convert_dump_to_currentdump{
                   6752:     my %hash = %{shift()};
                   6753:     my %returnhash;
                   6754:     # Code ripped from lond, essentially.  The only difference
                   6755:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6756:     # we might run in to problems with parameter names =~ /^v\./
                   6757:     while (my ($key,$value) = each(%hash)) {
                   6758:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6759: 	$symb  = &unescape($symb);
                   6760: 	$param = &unescape($param);
1.424     matthew  6761:         next if ($v eq 'version' || $symb eq 'keys');
                   6762:         next if (exists($returnhash{$symb}) &&
                   6763:                  exists($returnhash{$symb}->{$param}) &&
                   6764:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6765:         $returnhash{$symb}->{$param}=$value;
                   6766:         $returnhash{$symb}->{'v.'.$param}=$v;
                   6767:     }
                   6768:     #
                   6769:     # Remove all of the keys in the hashes which keep track of
                   6770:     # the version of the parameter.
                   6771:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   6772:         # use a foreach because we are going to delete from the hash.
                   6773:         foreach my $key (keys(%$param_hash)) {
                   6774:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   6775:         }
                   6776:     }
                   6777:     return \%returnhash;
1.12      www      6778: }
                   6779: 
1.627     albertel 6780: # ------------------------------------------------------ critical inc interface
                   6781: 
                   6782: sub cinc {
                   6783:     return &inc(@_,'critical');
                   6784: }
                   6785: 
1.449     matthew  6786: # --------------------------------------------------------------- inc interface
                   6787: 
                   6788: sub inc {
1.627     albertel 6789:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 6790:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6791:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  6792:     my $uhome=&homeserver($uname,$udomain);
                   6793:     my $items='';
                   6794:     if (! ref($store)) {
                   6795:         # got a single value, so use that instead
                   6796:         $items = &escape($store).'=&';
                   6797:     } elsif (ref($store) eq 'SCALAR') {
                   6798:         $items = &escape($$store).'=&';        
                   6799:     } elsif (ref($store) eq 'ARRAY') {
                   6800:         $items = join('=&',map {&escape($_);} @{$store});
                   6801:     } elsif (ref($store) eq 'HASH') {
                   6802:         while (my($key,$value) = each(%{$store})) {
                   6803:             $items.= &escape($key).'='.&escape($value).'&';
                   6804:         }
                   6805:     }
                   6806:     $items=~s/\&$//;
1.627     albertel 6807:     if ($critical) {
                   6808: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6809:     } else {
                   6810: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6811:     }
1.449     matthew  6812: }
                   6813: 
1.12      www      6814: # --------------------------------------------------------------- put interface
                   6815: 
                   6816: sub put {
1.134     albertel 6817:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6818:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6819:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6820:    my $uhome=&homeserver($uname,$udomain);
1.12      www      6821:    my $items='';
1.800     albertel 6822:    foreach my $item (keys(%$storehash)) {
                   6823:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6824:    }
1.12      www      6825:    $items=~s/\&$//;
1.134     albertel 6826:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      6827: }
                   6828: 
1.631     albertel 6829: # ------------------------------------------------------------ newput interface
                   6830: 
                   6831: sub newput {
                   6832:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   6833:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6834:    if (!$uname) { $uname=$env{'user.name'}; }
                   6835:    my $uhome=&homeserver($uname,$udomain);
                   6836:    my $items='';
                   6837:    foreach my $key (keys(%$storehash)) {
                   6838:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   6839:    }
                   6840:    $items=~s/\&$//;
                   6841:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   6842: }
                   6843: 
                   6844: # ---------------------------------------------------------  putstore interface
                   6845: 
1.524     raeburn  6846: sub putstore {
1.1172.2.59  raeburn  6847:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 6848:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6849:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  6850:    my $uhome=&homeserver($uname,$udomain);
                   6851:    my $items='';
1.715     albertel 6852:    foreach my $key (keys(%$storehash)) {
                   6853:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  6854:    }
1.715     albertel 6855:    $items=~s/\&$//;
1.716     albertel 6856:    my $esc_symb=&escape($symb);
                   6857:    my $esc_v=&escape($version);
1.715     albertel 6858:    my $reply =
1.716     albertel 6859:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 6860: 	      $uhome);
1.1172.2.59  raeburn  6861:    if (($tolog) && ($reply eq 'ok')) {
                   6862:        my $namevalue='';
                   6863:        foreach my $key (keys(%{$storehash})) {
                   6864:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   6865:        }
                   6866:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   6867:                      '&host='.&escape($perlvar{'lonHostID'}).
                   6868:                      '&version='.$esc_v.
                   6869:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   6870:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   6871:    }
1.715     albertel 6872:    if ($reply eq 'unknown_cmd') {
1.716     albertel 6873:        # gfall back to way things use to be done
1.715     albertel 6874:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   6875: 			    $uname);
1.524     raeburn  6876:    }
1.715     albertel 6877:    return $reply;
                   6878: }
                   6879: 
                   6880: sub old_putstore {
1.716     albertel 6881:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   6882:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6883:     if (!$uname) { $uname=$env{'user.name'}; }
                   6884:     my $uhome=&homeserver($uname,$udomain);
                   6885:     my %newstorehash;
1.800     albertel 6886:     foreach my $item (keys(%$storehash)) {
                   6887: 	my $key = $version.':'.&escape($symb).':'.$item;
                   6888: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 6889:     }
                   6890:     my $items='';
                   6891:     my %allitems = ();
1.800     albertel 6892:     foreach my $item (keys(%newstorehash)) {
                   6893: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 6894: 	    my $key = $1.':keys:'.$2;
                   6895: 	    $allitems{$key} .= $3.':';
                   6896: 	}
1.800     albertel 6897: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 6898:     }
1.800     albertel 6899:     foreach my $item (keys(%allitems)) {
                   6900: 	$allitems{$item} =~ s/\:$//;
                   6901: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 6902:     }
                   6903:     $items=~s/\&$//;
                   6904:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  6905: }
                   6906: 
1.47      www      6907: # ------------------------------------------------------ critical put interface
                   6908: 
                   6909: sub cput {
1.134     albertel 6910:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6911:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6912:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6913:    my $uhome=&homeserver($uname,$udomain);
1.47      www      6914:    my $items='';
1.800     albertel 6915:    foreach my $item (keys(%$storehash)) {
                   6916:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6917:    }
1.47      www      6918:    $items=~s/\&$//;
1.134     albertel 6919:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6920: }
                   6921: 
                   6922: # -------------------------------------------------------------- eget interface
                   6923: 
                   6924: sub eget {
1.133     albertel 6925:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6926:    my $items='';
1.800     albertel 6927:    foreach my $item (@$storearr) {
                   6928:        $items.=&escape($item).'&';
1.191     harris41 6929:    }
1.12      www      6930:    $items=~s/\&$//;
1.620     albertel 6931:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6932:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6933:    my $uhome=&homeserver($uname,$udomain);
                   6934:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6935:    my @pairs=split(/\&/,$rep);
                   6936:    my %returnhash=();
1.42      www      6937:    my $i=0;
1.800     albertel 6938:    foreach my $item (@$storearr) {
                   6939:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6940:       $i++;
1.191     harris41 6941:    }
1.12      www      6942:    return %returnhash;
                   6943: }
                   6944: 
1.667     albertel 6945: # ------------------------------------------------------------ tmpput interface
                   6946: sub tmpput {
1.802     raeburn  6947:     my ($storehash,$server,$context)=@_;
1.667     albertel 6948:     my $items='';
1.800     albertel 6949:     foreach my $item (keys(%$storehash)) {
                   6950: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 6951:     }
                   6952:     $items=~s/\&$//;
1.802     raeburn  6953:     if (defined($context)) {
                   6954:         $items .= ':'.&escape($context);
                   6955:     }
1.667     albertel 6956:     return &reply("tmpput:$items",$server);
                   6957: }
                   6958: 
                   6959: # ------------------------------------------------------------ tmpget interface
                   6960: sub tmpget {
1.688     albertel 6961:     my ($token,$server)=@_;
                   6962:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6963:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 6964:     my %returnhash;
1.1172.2.85  raeburn  6965:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   6966:         return %returnhash;
                   6967:     }
1.667     albertel 6968:     foreach my $item (split(/\&/,$rep)) {
                   6969: 	my ($key,$value)=split(/=/,$item);
                   6970: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   6971:     }
                   6972:     return %returnhash;
                   6973: }
                   6974: 
1.1113    raeburn  6975: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 6976: sub tmpdel {
                   6977:     my ($token,$server)=@_;
                   6978:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6979:     return &reply("tmpdel:$token",$server);
                   6980: }
                   6981: 
1.1172.2.13  raeburn  6982: # ------------------------------------------------------------ get_timebased_id
                   6983: 
                   6984: sub get_timebased_id {
                   6985:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   6986:         $maxtries) = @_;
                   6987:     my ($newid,$error,$dellock);
                   6988:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   6989:         return ('','ok','invalid call to get suffix');
                   6990:     }
                   6991: 
                   6992: # set defaults for any optional args for which values were not supplied
                   6993:     if ($who eq '') {
                   6994:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   6995:     }
                   6996:     if (!$locktries) {
                   6997:         $locktries = 3;
                   6998:     }
                   6999:     if (!$maxtries) {
                   7000:         $maxtries = 10;
                   7001:     }
                   7002: 
                   7003:     if (($cdom eq '') || ($cnum eq '')) {
                   7004:         if ($env{'request.course.id'}) {
                   7005:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7006:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7007:         }
                   7008:         if (($cdom eq '') || ($cnum eq '')) {
                   7009:             return ('','ok','call to get suffix not in course context');
                   7010:         }
                   7011:     }
                   7012: 
                   7013: # construct locking item
                   7014:     my $lockhash = {
                   7015:                       $prefix."\0".'locked_'.$keyid => $who,
                   7016:                    };
                   7017:     my $tries = 0;
                   7018: 
                   7019: # attempt to get lock on nohist_$namespace file
                   7020:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7021:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   7022:         $tries ++;
                   7023:         sleep 1;
                   7024:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7025:     }
                   7026: 
                   7027: # attempt to get unique identifier, based on current timestamp
                   7028:     if ($gotlock eq 'ok') {
                   7029:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   7030:         my $id = time;
                   7031:         $newid = $id;
1.1172.2.56  raeburn  7032:         if ($idtype eq 'addcode') {
                   7033:             $newid .= &sixnum_code();
                   7034:         }
1.1172.2.13  raeburn  7035:         my $idtries = 0;
                   7036:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   7037:             if ($idtype eq 'concat') {
                   7038:                 $newid = $id.$idtries;
1.1172.2.56  raeburn  7039:             } elsif ($idtype eq 'addcode') {
                   7040:                 $newid = $newid.&sixnum_code();
1.1172.2.13  raeburn  7041:             } else {
                   7042:                 $newid ++;
                   7043:             }
                   7044:             $idtries ++;
                   7045:         }
                   7046:         if (!exists($inuse{$prefix."\0".$newid})) {
                   7047:             my %new_item =  (
                   7048:                               $prefix."\0".$newid => $who,
                   7049:                             );
                   7050:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   7051:                                                  $cdom,$cnum);
                   7052:             if ($putresult ne 'ok') {
                   7053:                 undef($newid);
                   7054:                 $error = 'error saving new item: '.$putresult;
                   7055:             }
                   7056:         } else {
1.1172.2.56  raeburn  7057:              undef($newid);
1.1172.2.13  raeburn  7058:              $error = ('error: no unique suffix available for the new item ');
                   7059:         }
                   7060: #  remove lock
                   7061:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   7062:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   7063:     } else {
                   7064:         $error = "error: could not obtain lockfile\n";
                   7065:         $dellock = 'ok';
1.1172.2.58  raeburn  7066:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   7067:             $dellock = 'nolock';
                   7068:         }
1.1172.2.13  raeburn  7069:     }
                   7070:     return ($newid,$dellock,$error);
                   7071: }
                   7072: 
1.1172.2.56  raeburn  7073: sub sixnum_code {
                   7074:     my $code;
                   7075:     for (0..6) {
                   7076:         $code .= int( rand(9) );
                   7077:     }
                   7078:     return $code;
                   7079: }
                   7080: 
1.765     albertel 7081: # -------------------------------------------------- portfolio access checking
                   7082: 
                   7083: sub portfolio_access {
1.1172.2.77  raeburn  7084:     my ($requrl,$clientip) = @_;
1.765     albertel 7085:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77  raeburn  7086:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  7087:     if ($result) {
                   7088:         my %setters;
                   7089:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7090:             my ($startblock,$endblock) =
                   7091:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   7092:             if ($startblock && $endblock) {
                   7093:                 return 'B';
                   7094:             }
                   7095:         } else {
                   7096:             my ($startblock,$endblock) =
                   7097:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   7098:             if ($startblock && $endblock) {
                   7099:                 return 'B';
                   7100:             }
                   7101:         }
                   7102:     }
1.765     albertel 7103:     if ($result eq 'ok') {
1.766     albertel 7104:        return 'F';
1.765     albertel 7105:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 7106:        return 'A';
1.765     albertel 7107:     }
1.766     albertel 7108:     return '';
1.765     albertel 7109: }
                   7110: 
                   7111: sub get_portfolio_access {
1.1172.2.77  raeburn  7112:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 7113: 
                   7114:     if (!ref($access_hash)) {
                   7115: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   7116: 	my %access_controls = &get_access_controls($current_perms,$group,
                   7117: 						   $file_name);
                   7118: 	$access_hash = $access_controls{$file_name};
                   7119:     }
                   7120: 
1.1172.2.77  raeburn  7121:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 7122:     my $now = time;
                   7123:     if (ref($access_hash) eq 'HASH') {
                   7124:         foreach my $key (keys(%{$access_hash})) {
                   7125:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7126:             if ($start > $now) {
                   7127:                 next;
                   7128:             }
                   7129:             if ($end && $end<$now) {
                   7130:                 next;
                   7131:             }
                   7132:             if ($scope eq 'public') {
                   7133:                 $public = $key;
                   7134:                 last;
                   7135:             } elsif ($scope eq 'guest') {
                   7136:                 $guest = $key;
                   7137:             } elsif ($scope eq 'domains') {
                   7138:                 push(@domains,$key);
                   7139:             } elsif ($scope eq 'users') {
                   7140:                 push(@users,$key);
                   7141:             } elsif ($scope eq 'course') {
                   7142:                 push(@courses,$key);
                   7143:             } elsif ($scope eq 'group') {
                   7144:                 push(@groups,$key);
1.1172.2.77  raeburn  7145:             } elsif ($scope eq 'ip') {
                   7146:                 push(@ips,$key);
1.765     albertel 7147:             }
                   7148:         }
                   7149:         if ($public) {
                   7150:             return 'ok';
1.1172.2.77  raeburn  7151:         } elsif (@ips > 0) {
                   7152:             my $allowed;
                   7153:             foreach my $ipkey (@ips) {
                   7154:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   7155:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   7156:                         $allowed = 1;
                   7157:                         last;
                   7158:                     }
                   7159:                 }
                   7160:             }
                   7161:             if ($allowed) {
                   7162:                 return 'ok';
                   7163:             }
1.765     albertel 7164:         }
                   7165:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7166:             if ($guest) {
                   7167:                 return $guest;
                   7168:             }
                   7169:         } else {
                   7170:             if (@domains > 0) {
                   7171:                 foreach my $domkey (@domains) {
                   7172:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   7173:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   7174:                             return 'ok';
                   7175:                         }
                   7176:                     }
                   7177:                 }
                   7178:             }
                   7179:             if (@users > 0) {
                   7180:                 foreach my $userkey (@users) {
1.865     raeburn  7181:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   7182:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   7183:                             if (ref($item) eq 'HASH') {
                   7184:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   7185:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   7186:                                     return 'ok';
                   7187:                                 }
                   7188:                             }
                   7189:                         }
                   7190:                     } 
1.765     albertel 7191:                 }
                   7192:             }
                   7193:             my %roleshash;
                   7194:             my @courses_and_groups = @courses;
                   7195:             push(@courses_and_groups,@groups); 
                   7196:             if (@courses_and_groups > 0) {
                   7197:                 my (%allgroups,%allroles); 
                   7198:                 my ($start,$end,$role,$sec,$group);
                   7199:                 foreach my $envkey (%env) {
1.1060    raeburn  7200:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7201:                         my $cid = $2.'_'.$3; 
                   7202:                         if ($1 eq 'gr') {
                   7203:                             $group = $4;
                   7204:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7205:                         } else {
                   7206:                             if ($4 eq '') {
                   7207:                                 $sec = 'none';
                   7208:                             } else {
                   7209:                                 $sec = $4;
                   7210:                             }
                   7211:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7212:                         }
1.811     albertel 7213:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7214:                         my $cid = $2.'_'.$3;
                   7215:                         if ($4 eq '') {
                   7216:                             $sec = 'none';
                   7217:                         } else {
                   7218:                             $sec = $4;
                   7219:                         }
                   7220:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7221:                     }
                   7222:                 }
                   7223:                 if (keys(%allroles) == 0) {
                   7224:                     return;
                   7225:                 }
                   7226:                 foreach my $key (@courses_and_groups) {
                   7227:                     my %content = %{$$access_hash{$key}};
                   7228:                     my $cnum = $content{'number'};
                   7229:                     my $cdom = $content{'domain'};
                   7230:                     my $cid = $cdom.'_'.$cnum;
                   7231:                     if (!exists($allroles{$cid})) {
                   7232:                         next;
                   7233:                     }    
                   7234:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7235:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7236:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7237:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7238:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7239:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7240:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7241:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7242:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7243:                                         if (grep/^all$/,@sections) {
                   7244:                                             return 'ok';
                   7245:                                         } else {
                   7246:                                             if (grep/^$sec$/,@sections) {
                   7247:                                                 return 'ok';
                   7248:                                             }
                   7249:                                         }
                   7250:                                     }
                   7251:                                 }
                   7252:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7253:                                     if (grep/^none$/,@groups) {
                   7254:                                         return 'ok';
                   7255:                                     }
                   7256:                                 } else {
                   7257:                                     if (grep/^all$/,@groups) {
                   7258:                                         return 'ok';
                   7259:                                     } 
                   7260:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7261:                                         if (grep/^$group$/,@groups) {
                   7262:                                             return 'ok';
                   7263:                                         }
                   7264:                                     }
                   7265:                                 } 
                   7266:                             }
                   7267:                         }
                   7268:                     }
                   7269:                 }
                   7270:             }
                   7271:             if ($guest) {
                   7272:                 return $guest;
                   7273:             }
                   7274:         }
                   7275:     }
                   7276:     return;
                   7277: }
                   7278: 
                   7279: sub course_group_datechecker {
                   7280:     my ($dates,$now,$status) = @_;
                   7281:     my ($start,$end) = split(/\./,$dates);
                   7282:     if (!$start && !$end) {
                   7283:         return 'ok';
                   7284:     }
                   7285:     if (grep/^active$/,@{$status}) {
                   7286:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7287:             return 'ok';
                   7288:         }
                   7289:     }
                   7290:     if (grep/^previous$/,@{$status}) {
                   7291:         if ($end > $now ) {
                   7292:             return 'ok';
                   7293:         }
                   7294:     }
                   7295:     if (grep/^future$/,@{$status}) {
                   7296:         if ($start > $now) {
                   7297:             return 'ok';
                   7298:         }
                   7299:     }
                   7300:     return; 
                   7301: }
                   7302: 
                   7303: sub parse_portfolio_url {
                   7304:     my ($url) = @_;
                   7305: 
                   7306:     my ($type,$udom,$unum,$group,$file_name);
                   7307:     
1.823     albertel 7308:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7309: 	$type = 1;
                   7310:         $udom = $1;
                   7311:         $unum = $2;
                   7312:         $file_name = $3;
1.823     albertel 7313:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7314: 	$type = 2;
                   7315:         $udom = $1;
                   7316:         $unum = $2;
                   7317:         $group = $3;
                   7318:         $file_name = $3.'/'.$4;
                   7319:     }
                   7320:     if (wantarray) {
                   7321: 	return ($type,$udom,$unum,$file_name,$group);
                   7322:     }
                   7323:     return $type;
                   7324: }
                   7325: 
                   7326: sub is_portfolio_url {
                   7327:     my ($url) = @_;
                   7328:     return scalar(&parse_portfolio_url($url));
                   7329: }
                   7330: 
1.798     raeburn  7331: sub is_portfolio_file {
                   7332:     my ($file) = @_;
1.820     raeburn  7333:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7334:         return 1;
                   7335:     }
                   7336:     return;
                   7337: }
                   7338: 
1.976     raeburn  7339: sub usertools_access {
1.1084    raeburn  7340:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7341:     my ($access,%tools);
                   7342:     if ($context eq '') {
                   7343:         $context = 'tools';
                   7344:     }
                   7345:     if ($context eq 'requestcourses') {
                   7346:         %tools = (
                   7347:                       official   => 1,
                   7348:                       unofficial => 1,
1.1006    raeburn  7349:                       community  => 1,
1.1172.2.37  raeburn  7350:                       textbook   => 1,
1.985     raeburn  7351:                  );
1.1172.2.9  raeburn  7352:     } elsif ($context eq 'requestauthor') {
                   7353:         %tools = (
                   7354:                       requestauthor => 1,
                   7355:                  );
1.985     raeburn  7356:     } else {
                   7357:         %tools = (
                   7358:                       aboutme   => 1,
                   7359:                       blog      => 1,
1.1172.2.6  raeburn  7360:                       webdav    => 1,
1.985     raeburn  7361:                       portfolio => 1,
                   7362:                  );
                   7363:     }
1.976     raeburn  7364:     return if (!defined($tools{$tool}));
                   7365: 
1.1172.2.35  raeburn  7366:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7367:         $udom = $env{'user.domain'};
                   7368:         $uname = $env{'user.name'};
                   7369:     }
                   7370: 
1.978     raeburn  7371:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7372:         if ($action ne 'reload') {
1.985     raeburn  7373:             if ($context eq 'requestcourses') {
                   7374:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  7375:             } elsif ($context eq 'requestauthor') {
                   7376:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7377:             } else {
                   7378:                 return $env{'environment.availabletools.'.$tool};
                   7379:             }
                   7380:         }
1.976     raeburn  7381:     }
                   7382: 
1.1172.2.9  raeburn  7383:     my ($toolstatus,$inststatus,$envkey);
                   7384:     if ($context eq 'requestauthor') {
                   7385:         $envkey = $context;
                   7386:     } else {
                   7387:         $envkey = $context.'.'.$tool;
                   7388:     }
1.976     raeburn  7389: 
1.985     raeburn  7390:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7391:          ($action ne 'reload')) {
1.1172.2.9  raeburn  7392:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7393:         $inststatus = $env{'environment.inststatus'};
                   7394:     } else {
1.1084    raeburn  7395:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  7396:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7397:             $inststatus = $userenvref->{'inststatus'};
                   7398:         } else {
1.1172.2.9  raeburn  7399:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7400:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7401:             $inststatus = $userenv{'inststatus'};
                   7402:         }
1.976     raeburn  7403:     }
                   7404: 
                   7405:     if ($toolstatus ne '') {
                   7406:         if ($toolstatus) {
                   7407:             $access = 1;
                   7408:         } else {
                   7409:             $access = 0;
                   7410:         }
                   7411:         return $access;
                   7412:     }
                   7413: 
1.1084    raeburn  7414:     my ($is_adv,%domdef);
                   7415:     if (ref($is_advref) eq 'HASH') {
                   7416:         $is_adv = $is_advref->{'is_adv'};
                   7417:     } else {
                   7418:         $is_adv = &is_advanced_user($udom,$uname);
                   7419:     }
                   7420:     if (ref($domdefref) eq 'HASH') {
                   7421:         %domdef = %{$domdefref};
                   7422:     } else {
                   7423:         %domdef = &get_domain_defaults($udom);
                   7424:     }
1.976     raeburn  7425:     if (ref($domdef{$tool}) eq 'HASH') {
                   7426:         if ($is_adv) {
                   7427:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7428:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7429:                     $access = 1;
                   7430:                 } else {
                   7431:                     $access = 0;
                   7432:                 }
                   7433:                 return $access;
                   7434:             }
                   7435:         }
                   7436:         if ($inststatus ne '') {
                   7437:             my ($hasaccess,$hasnoaccess);
                   7438:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7439:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7440:                     if ($domdef{$tool}{$affiliation}) {
                   7441:                         $hasaccess = 1;
                   7442:                     } else {
                   7443:                         $hasnoaccess = 1;
                   7444:                     }
                   7445:                 }
                   7446:             }
                   7447:             if ($hasaccess || $hasnoaccess) {
                   7448:                 if ($hasaccess) {
                   7449:                     $access = 1;
                   7450:                 } elsif ($hasnoaccess) {
                   7451:                     $access = 0; 
                   7452:                 }
                   7453:                 return $access;
                   7454:             }
                   7455:         } else {
                   7456:             if ($domdef{$tool}{'default'} ne '') {
                   7457:                 if ($domdef{$tool}{'default'}) {
                   7458:                     $access = 1;
                   7459:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7460:                     $access = 0;
                   7461:                 }
                   7462:                 return $access;
                   7463:             }
                   7464:         }
                   7465:     } else {
1.1172.2.6  raeburn  7466:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7467:             $access = 1;
                   7468:         } else {
                   7469:             $access = 0;
                   7470:         }
1.976     raeburn  7471:         return $access;
                   7472:     }
                   7473: }
                   7474: 
1.1050    raeburn  7475: sub is_course_owner {
                   7476:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7477:     if (($udom eq '') || ($uname eq '')) {
                   7478:         $udom = $env{'user.domain'};
                   7479:         $uname = $env{'user.name'};
                   7480:     }
                   7481:     unless (($udom eq '') || ($uname eq '')) {
                   7482:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7483:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7484:                 return 1;
                   7485:             } else {
                   7486:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7487:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7488:                     return 1;
                   7489:                 }
                   7490:             }
                   7491:         }
                   7492:     }
                   7493:     return;
                   7494: }
                   7495: 
1.976     raeburn  7496: sub is_advanced_user {
                   7497:     my ($udom,$uname) = @_;
1.1085    raeburn  7498:     if ($udom ne '' && $uname ne '') {
                   7499:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7500:             if (wantarray) {
                   7501:                 return ($env{'user.adv'},$env{'user.author'});
                   7502:             } else {
                   7503:                 return $env{'user.adv'};
                   7504:             }
1.1085    raeburn  7505:         }
                   7506:     }
1.976     raeburn  7507:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7508:     my %allroles;
1.1128    raeburn  7509:     my ($is_adv,$is_author);
1.976     raeburn  7510:     foreach my $role (keys(%roleshash)) {
                   7511:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7512:         my $area = '/'.$tdomain.'/'.$trest;
                   7513:         if ($sec ne '') {
                   7514:             $area .= '/'.$sec;
                   7515:         }
                   7516:         if (($area ne '') && ($trole ne '')) {
                   7517:             my $spec=$trole.'.'.$area;
                   7518:             if ($trole =~ /^cr\//) {
                   7519:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7520:             } elsif ($trole ne 'gr') {
                   7521:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7522:             }
1.1128    raeburn  7523:             if ($trole eq 'au') {
                   7524:                 $is_author = 1;
                   7525:             }
1.976     raeburn  7526:         }
                   7527:     }
                   7528:     foreach my $role (keys(%allroles)) {
                   7529:         last if ($is_adv);
                   7530:         foreach my $item (split(/:/,$allroles{$role})) {
                   7531:             if ($item ne '') {
                   7532:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7533:                 if ($privilege eq 'adv') {
                   7534:                     $is_adv = 1;
                   7535:                     last;
                   7536:                 }
                   7537:             }
                   7538:         }
                   7539:     }
1.1128    raeburn  7540:     if (wantarray) {
                   7541:         return ($is_adv,$is_author);
                   7542:     }
1.976     raeburn  7543:     return $is_adv;
                   7544: }
1.798     raeburn  7545: 
1.1035    raeburn  7546: sub check_can_request {
1.1036    raeburn  7547:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  7548:     my $canreq = 0;
                   7549:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7550:     my @options = ('approval','validate','autolimit');
                   7551:     my $optregex = join('|',@options);
                   7552:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7553:         foreach my $type (@{$types}) {
                   7554:             if (&usertools_access($env{'user.name'},
                   7555:                                   $env{'user.domain'},
                   7556:                                   $type,undef,'requestcourses')) {
                   7557:                 $canreq ++;
1.1036    raeburn  7558:                 if (ref($request_domains) eq 'HASH') {
                   7559:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   7560:                 }
1.1035    raeburn  7561:                 if ($dom eq $env{'user.domain'}) {
                   7562:                     $can_request->{$type} = 1;
                   7563:                 }
                   7564:             }
                   7565:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   7566:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7567:                 if (@curr > 0) {
1.1036    raeburn  7568:                     foreach my $item (@curr) {
                   7569:                         if (ref($request_domains) eq 'HASH') {
                   7570:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7571:                             if ($otherdom ne '') {
                   7572:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7573:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7574:                                         push(@{$request_domains->{$type}},$otherdom);
                   7575:                                     }
                   7576:                                 } else {
                   7577:                                     push(@{$request_domains->{$type}},$otherdom);
                   7578:                                 }
                   7579:                             }
                   7580:                         }
                   7581:                     }
                   7582:                     unless($dom eq $env{'user.domain'}) {
                   7583:                         $canreq ++;
1.1035    raeburn  7584:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7585:                             $can_request->{$type} = 1;
                   7586:                         }
                   7587:                     }
                   7588:                 }
                   7589:             }
                   7590:         }
                   7591:     }
                   7592:     return $canreq;
                   7593: }
                   7594: 
1.341     www      7595: # ---------------------------------------------- Custom access rule evaluation
                   7596: 
                   7597: sub customaccess {
                   7598:     my ($priv,$uri)=@_;
1.807     albertel 7599:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7600:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7601:     $udom = &LONCAPA::clean_domain($udom);
                   7602:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7603:     my $access=0;
1.800     albertel 7604:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7605: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7606: 	if ($type eq 'user') {
                   7607: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7608: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7609: 		if ($tdom) {
                   7610: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7611: 		}
1.896     albertel 7612: 		if ($tuname) {
                   7613: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7614: 		}
                   7615: 		$access=($effect eq 'allow');
                   7616: 		last;
                   7617: 	    }
                   7618: 	} else {
                   7619: 	    if ($role) {
                   7620: 		if ($role ne $urole) { next; }
                   7621: 	    }
                   7622: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7623: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7624: 		if ($tdom) {
                   7625: 		    if ($tdom ne $udom) { next; }
                   7626: 		}
                   7627: 		if ($tcrs) {
                   7628: 		    if ($tcrs ne $ucrs) { next; }
                   7629: 		}
                   7630: 		if ($tsec) {
                   7631: 		    if ($tsec ne $usec) { next; }
                   7632: 		}
                   7633: 		$access=($effect eq 'allow');
                   7634: 		last;
                   7635: 	    }
                   7636: 	    if ($realm eq '' && $role eq '') {
                   7637: 		$access=($effect eq 'allow');
                   7638: 	    }
1.402     bowersj2 7639: 	}
1.341     www      7640:     }
                   7641:     return $access;
                   7642: }
                   7643: 
1.103     harris41 7644: # ------------------------------------------------- Check for a user privilege
1.12      www      7645: 
                   7646: sub allowed {
1.1172.2.65  raeburn  7647:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 7648:     my $ver_orguri=$uri;
1.439     www      7649:     $uri=&deversion($uri);
1.152     www      7650:     my $orguri=$uri;
1.52      www      7651:     $uri=&declutter($uri);
1.809     raeburn  7652: 
1.810     raeburn  7653:     if ($priv eq 'evb') {
                   7654: # Evade communication block restrictions for specified role in a course
                   7655:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   7656:             return $1;
                   7657:         } else {
                   7658:             return;
                   7659:         }
                   7660:     }
                   7661: 
1.620     albertel 7662:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      7663: # Free bre access to adm and meta resources
1.775     albertel 7664:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 7665: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   7666: 	&& ($priv eq 'bre')) {
1.14      www      7667: 	return 'F';
1.159     www      7668:     }
                   7669: 
1.545     banghart 7670: # Free bre access to user's own portfolio contents
1.714     raeburn  7671:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  7672:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  7673: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  7674:         my %setters;
                   7675:         my ($startblock,$endblock) = 
                   7676:             &Apache::loncommon::blockcheck(\%setters,'port');
                   7677:         if ($startblock && $endblock) {
                   7678:             return 'B';
                   7679:         } else {
                   7680:             return 'F';
                   7681:         }
1.545     banghart 7682:     }
                   7683: 
1.762     raeburn  7684: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  7685:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   7686:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   7687:         if (exists($env{'request.course.id'})) {
                   7688:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7689:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7690:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   7691:                 my $courseprivid=$env{'request.course.id'};
                   7692:                 $courseprivid=~s/\_/\//;
                   7693:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   7694:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   7695:                     return $1; 
1.762     raeburn  7696:                 } else {
                   7697:                     if ($env{'request.course.sec'}) {
                   7698:                         $courseprivid.='/'.$env{'request.course.sec'};
                   7699:                     }
                   7700:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   7701:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   7702:                         return $2;
                   7703:                     }
1.714     raeburn  7704:                 }
                   7705:             }
                   7706:         }
                   7707:     }
                   7708: 
1.159     www      7709: # Free bre to public access
                   7710: 
                   7711:     if ($priv eq 'bre') {
1.238     www      7712:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 7713: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      7714:            return 'F'; 
                   7715:         }
1.238     www      7716:         if ($copyright eq 'priv') {
                   7717:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7718: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      7719: 		return '';
                   7720:             }
                   7721:         }
                   7722:         if ($copyright eq 'domain') {
                   7723:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7724: 	    unless (($env{'user.domain'} eq $1) ||
                   7725:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7726: 		return '';
                   7727:             }
1.262     matthew  7728:         }
1.620     albertel 7729:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7730:             # Library role, so allow browsing of resources in this domain.
                   7731:             return 'F';
1.238     www      7732:         }
1.341     www      7733:         if ($copyright eq 'custom') {
                   7734: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7735:         }
1.14      www      7736:     }
1.264     matthew  7737:     # Domain coordinator is trying to create a course
1.620     albertel 7738:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7739:         # uri is the requested domain in this case.
                   7740:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7741:         # a role of dc for the domain in question.
1.620     albertel 7742:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7743:     }
1.29      www      7744: 
1.52      www      7745:     my $thisallowed='';
                   7746:     my $statecond=0;
                   7747:     my $courseprivid='';
                   7748: 
1.1039    raeburn  7749:     my $ownaccess;
1.1043    raeburn  7750:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7751:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7752:         if ($uri eq '') {
                   7753:             $ownaccess = 1;
                   7754:         } else {
                   7755:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7756:                 my $udom = $env{'user.domain'};
                   7757:                 my $uname = $env{'user.name'};
                   7758:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7759:                     $ownaccess = 1;
1.1040    raeburn  7760:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7761:                     unless ($uri =~ m{\.\./}) {
                   7762:                         $ownaccess = 1;
                   7763:                     }
                   7764:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   7765:                     my $now = time;
                   7766:                     if ($uri =~ m{^([^/]+)/?$}) {
                   7767:                         my $adom = $1;
                   7768:                         foreach my $key (keys(%env)) {
1.1042    raeburn  7769:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  7770:                                 my ($start,$end) = split('.',$env{$key});
                   7771:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7772:                                     $ownaccess = 1;
                   7773:                                     last;
                   7774:                                 }
                   7775:                             }
                   7776:                         }
                   7777:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   7778:                         my $adom = $1;
                   7779:                         my $aname = $2;
1.1042    raeburn  7780:                         foreach my $role ('ca','aa') { 
                   7781:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   7782:                                 my ($start,$end) =
                   7783:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   7784:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7785:                                     $ownaccess = 1;
                   7786:                                     last;
                   7787:                                 }
1.1039    raeburn  7788:                             }
                   7789:                         }
                   7790:                     }
                   7791:                 }
                   7792:             }
                   7793:         }
                   7794:     }
                   7795: 
1.52      www      7796: # Course
                   7797: 
1.620     albertel 7798:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7799:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7800:             $thisallowed.=$1;
                   7801:         }
1.52      www      7802:     }
1.29      www      7803: 
1.52      www      7804: # Domain
                   7805: 
1.620     albertel 7806:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 7807:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7808:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7809:             $thisallowed.=$1;
                   7810:         }
1.12      www      7811:     }
1.52      www      7812: 
1.1141    raeburn  7813: # User who is not author or co-author might still be able to edit
                   7814: # resource of an author in the domain (e.g., if Domain Coordinator).
                   7815:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   7816:         (&allowed('mdc',$env{'request.course.id'}))) {
                   7817:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   7818:             $thisallowed.=$1;
                   7819:         }
                   7820:     }
                   7821: 
1.52      www      7822: # Course: uri itself is a course
1.66      www      7823:     my $courseuri=$uri;
                   7824:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      7825:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      7826: 
1.620     albertel 7827:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 7828:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7829:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7830:             $thisallowed.=$1;
                   7831:         }
1.12      www      7832:     }
1.29      www      7833: 
1.665     albertel 7834: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 7835: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 7836:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 7837: 	$thisallowed='';
1.671     raeburn  7838:         my ($match)=&is_on_map($uri);
                   7839:         if ($match) {
                   7840:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   7841:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65  raeburn  7842:                 my $value = $1;
                   7843:                 if ($noblockcheck) {
                   7844:                     $thisallowed.=$value;
1.1162    raeburn  7845:                 } else {
1.1172.2.65  raeburn  7846:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7847:                     if (@blockers > 0) {
                   7848:                         $thisallowed = 'B';
                   7849:                     } else {
                   7850:                         $thisallowed.=$value;
                   7851:                     }
1.1162    raeburn  7852:                 }
1.671     raeburn  7853:             }
                   7854:         } else {
1.705     albertel 7855:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  7856:             if ($refuri) {
                   7857:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  7858:                     $thisallowed='F';
1.671     raeburn  7859:                 } else {
                   7860:                     $refuri=&declutter($refuri);
                   7861:                     my ($match) = &is_on_map($refuri);
                   7862:                     if ($match) {
1.1172.2.65  raeburn  7863:                         if ($noblockcheck) {
1.1162    raeburn  7864:                             $thisallowed='F';
1.1172.2.65  raeburn  7865:                         } else {
                   7866:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7867:                             if (@blockers > 0) {
                   7868:                                 $thisallowed = 'B';
                   7869:                             } else {
                   7870:                                 $thisallowed='F';
                   7871:                             }
1.1162    raeburn  7872:                         }
1.671     raeburn  7873:                     }
1.669     raeburn  7874:                 }
1.671     raeburn  7875:             }
                   7876:         }
1.314     www      7877:     }
1.492     albertel 7878: 
1.766     albertel 7879:     if ($priv eq 'bre'
                   7880: 	&& $thisallowed ne 'F' 
                   7881: 	&& $thisallowed ne '2'
                   7882: 	&& &is_portfolio_url($uri)) {
1.1172.2.77  raeburn  7883: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 7884:     }
                   7885:     
1.52      www      7886: # Full access at system, domain or course-wide level? Exit.
1.29      www      7887:     if ($thisallowed=~/F/) {
                   7888: 	return 'F';
                   7889:     }
                   7890: 
1.52      www      7891: # If this is generating or modifying users, exit with special codes
1.29      www      7892: 
1.643     www      7893:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   7894: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 7895: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      7896: # no author name given, so this just checks on the general right to make a co-author in this domain
                   7897: 	    unless ($auname) { return $thisallowed; }
                   7898: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 7899: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   7900: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   7901: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   7902: 	}
1.52      www      7903: 	return $thisallowed;
                   7904:     }
                   7905: #
1.103     harris41 7906: # Gathered so far: system, domain and course wide privileges
1.52      www      7907: #
                   7908: # Course: See if uri or referer is an individual resource that is part of 
                   7909: # the course
                   7910: 
1.620     albertel 7911:     if ($env{'request.course.id'}) {
1.232     www      7912: 
1.620     albertel 7913:        $courseprivid=$env{'request.course.id'};
                   7914:        if ($env{'request.course.sec'}) {
                   7915:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      7916:        }
                   7917:        $courseprivid=~s/\_/\//;
                   7918:        my $checkreferer=1;
1.232     www      7919:        my ($match,$cond)=&is_on_map($uri);
                   7920:        if ($match) {
                   7921:            $statecond=$cond;
1.620     albertel 7922:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7923:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7924:                my $value = $1;
                   7925:                if ($priv eq 'bre') {
1.1172.2.65  raeburn  7926:                    if ($noblockcheck) {
1.1162    raeburn  7927:                        $thisallowed.=$value;
1.1172.2.65  raeburn  7928:                    } else {
                   7929:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7930:                        if (@blockers > 0) {
                   7931:                            $thisallowed = 'B';
                   7932:                        } else {
                   7933:                            $thisallowed.=$value;
                   7934:                        }
1.1162    raeburn  7935:                    }
                   7936:                } else {
                   7937:                    $thisallowed.=$value;
                   7938:                }
1.52      www      7939:                $checkreferer=0;
                   7940:            }
1.29      www      7941:        }
1.83      www      7942:        
1.148     www      7943:        if ($checkreferer) {
1.620     albertel 7944: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      7945:             unless ($refuri) {
1.800     albertel 7946:                 foreach my $key (keys(%env)) {
                   7947: 		    if ($key=~/^httpref\..*\*/) {
                   7948: 			my $pattern=$key;
1.156     www      7949:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      7950:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   7951:                         $pattern=~s/\//\\\//g;
1.152     www      7952:                         if ($orguri=~/$pattern/) {
1.800     albertel 7953: 			    $refuri=$env{$key};
1.148     www      7954:                         }
                   7955:                     }
1.191     harris41 7956:                 }
1.148     www      7957:             }
1.232     www      7958: 
1.148     www      7959:          if ($refuri) { 
1.152     www      7960: 	  $refuri=&declutter($refuri);
1.232     www      7961:           my ($match,$cond)=&is_on_map($refuri);
                   7962:             if ($match) {
                   7963:               my $refstatecond=$cond;
1.620     albertel 7964:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7965:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7966:                   my $value = $1;
                   7967:                   if ($priv eq 'bre') {
1.1172.2.65  raeburn  7968:                       if ($noblockcheck) {
1.1162    raeburn  7969:                           $thisallowed.=$value;
1.1172.2.65  raeburn  7970:                       } else {
                   7971:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7972:                           if (@blockers > 0) {
                   7973:                               $thisallowed = 'B';
                   7974:                           } else {
                   7975:                               $thisallowed.=$value;
                   7976:                           }
1.1162    raeburn  7977:                       }
                   7978:                   } else {
                   7979:                       $thisallowed.=$value;
                   7980:                   }
1.53      www      7981:                   $uri=$refuri;
                   7982:                   $statecond=$refstatecond;
1.52      www      7983:               }
                   7984:           }
1.148     www      7985:         }
1.29      www      7986:        }
1.52      www      7987:    }
1.29      www      7988: 
1.52      www      7989: #
1.103     harris41 7990: # Gathered now: all privileges that could apply, and condition number
1.52      www      7991: # 
                   7992: #
                   7993: # Full or no access?
                   7994: #
1.29      www      7995: 
1.52      www      7996:     if ($thisallowed=~/F/) {
                   7997: 	return 'F';
                   7998:     }
1.29      www      7999: 
1.52      www      8000:     unless ($thisallowed) {
                   8001:         return '';
                   8002:     }
1.29      www      8003: 
1.52      www      8004: # Restrictions exist, deal with them
                   8005: #
                   8006: #   C:according to course preferences
                   8007: #   R:according to resource settings
                   8008: #   L:unless locked
                   8009: #   X:according to user session state
                   8010: #
                   8011: 
                   8012: # Possibly locked functionality, check all courses
1.54      www      8013: # Locks might take effect only after 10 minutes cache expiration for other
                   8014: # courses, and 2 minutes for current course
1.52      www      8015: 
                   8016:     my $envkey;
                   8017:     if ($thisallowed=~/L/) {
1.1000    raeburn  8018:         foreach $envkey (keys(%env)) {
1.54      www      8019:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   8020:                my $courseid=$2;
                   8021:                my $roleid=$1.'.'.$2;
1.92      www      8022:                $courseid=~s/^\///;
1.54      www      8023:                my $expiretime=600;
1.620     albertel 8024:                if ($env{'request.role'} eq $roleid) {
1.54      www      8025: 		  $expiretime=120;
                   8026:                }
                   8027: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   8028:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 8029:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 8030: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      8031:                }
1.620     albertel 8032:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8033:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   8034: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   8035:                        &log($env{'user.domain'},$env{'user.name'},
                   8036:                             $env{'user.home'},
1.57      www      8037:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      8038:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8039:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8040: 		       return '';
                   8041:                    }
                   8042:                }
1.620     albertel 8043:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8044:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   8045: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   8046:                        &log($env{'user.domain'},$env{'user.name'},
                   8047:                             $env{'user.home'},
1.57      www      8048:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      8049:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8050:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8051: 		       return '';
                   8052:                    }
                   8053:                }
                   8054: 	   }
1.29      www      8055:        }
1.52      www      8056:     }
                   8057:    
                   8058: #
                   8059: # Rest of the restrictions depend on selected course
                   8060: #
                   8061: 
1.620     albertel 8062:     unless ($env{'request.course.id'}) {
1.766     albertel 8063: 	if ($thisallowed eq 'A') {
                   8064: 	    return 'A';
1.814     raeburn  8065:         } elsif ($thisallowed eq 'B') {
                   8066:             return 'B';
1.766     albertel 8067: 	} else {
                   8068: 	    return '1';
                   8069: 	}
1.52      www      8070:     }
1.29      www      8071: 
1.52      www      8072: #
                   8073: # Now user is definitely in a course
                   8074: #
1.53      www      8075: 
                   8076: 
                   8077: # Course preferences
                   8078: 
                   8079:    if ($thisallowed=~/C/) {
1.620     albertel 8080:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   8081:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   8082:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 8083: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  8084: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8085: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8086: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   8087: 			$env{'request.course.id'});
                   8088: 	   }
1.237     www      8089:            return '';
                   8090:        }
                   8091: 
1.620     albertel 8092:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 8093: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  8094: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8095: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   8096: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   8097: 			$env{'request.course.id'});
                   8098: 	   }
1.54      www      8099:            return '';
                   8100:        }
1.53      www      8101:    }
                   8102: 
                   8103: # Resource preferences
                   8104: 
                   8105:    if ($thisallowed=~/R/) {
1.620     albertel 8106:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 8107:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  8108: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8109: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8110: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   8111: 	   }
                   8112: 	   return '';
1.54      www      8113:        }
1.53      www      8114:    }
1.30      www      8115: 
1.246     www      8116: # Restricted by state or randomout?
1.30      www      8117: 
1.52      www      8118:    if ($thisallowed=~/X/) {
1.620     albertel 8119:       if ($env{'acc.randomout'}) {
1.579     albertel 8120: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 8121:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      8122:             return ''; 
                   8123:          }
1.247     www      8124:       }
                   8125:       if (&condval($statecond)) {
1.52      www      8126: 	 return '2';
                   8127:       } else {
                   8128:          return '';
                   8129:       }
                   8130:    }
1.30      www      8131: 
1.766     albertel 8132:     if ($thisallowed eq 'A') {
                   8133: 	return 'A';
1.814     raeburn  8134:     } elsif ($thisallowed eq 'B') {
                   8135:         return 'B';
1.766     albertel 8136:     }
1.52      www      8137:    return 'F';
1.232     www      8138: }
1.1162    raeburn  8139: 
1.1172.2.13  raeburn  8140: # ------------------------------------------- Check construction space access
                   8141: 
                   8142: sub constructaccess {
                   8143:     my ($url,$setpriv)=@_;
                   8144: 
                   8145: # We do not allow editing of previous versions of files
                   8146:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   8147: 
                   8148: # Get username and domain from URL
                   8149:     my ($ownername,$ownerdomain,$ownerhome);
                   8150: 
                   8151:     ($ownerdomain,$ownername) =
1.1172.2.83  raeburn  8152:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13  raeburn  8153: 
                   8154: # The URL does not really point to any authorspace, forget it
                   8155:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   8156: 
                   8157: # Now we need to see if the user has access to the authorspace of
                   8158: # $ownername at $ownerdomain
                   8159: 
                   8160:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   8161: # Real author for this?
                   8162:        $ownerhome = $env{'user.home'};
                   8163:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   8164:           return ($ownername,$ownerdomain,$ownerhome);
                   8165:        }
                   8166:     } else {
                   8167: # Co-author for this?
                   8168:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   8169:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   8170:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   8171:             return ($ownername,$ownerdomain,$ownerhome);
                   8172:         }
                   8173:     }
                   8174: 
                   8175: # We don't have any access right now. If we are not possibly going to do anything about this,
                   8176: # we might as well leave
                   8177:    unless ($setpriv) { return ''; }
                   8178: 
                   8179: # Backdoor access?
                   8180:     my $allowed=&allowed('eco',$ownerdomain);
                   8181: # Nope
                   8182:     unless ($allowed) { return ''; }
                   8183: # Looks like we may have access, but could be locked by the owner of the construction space
                   8184:     if ($allowed eq 'U') {
                   8185:         my %blocked=&get('environment',['domcoord.author'],
                   8186:                          $ownerdomain,$ownername);
                   8187: # Is blocked by owner
                   8188:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8189:     }
                   8190:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8191: # Grant temporary access
                   8192:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  8193:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  8194:         if (!$update) { $update = $then; }
                   8195:         my $refresh=$env{'user.refresh.time'};
                   8196:         if (!$refresh) { $refresh = $update; }
                   8197:         my $now = time;
                   8198:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8199:                            $now,'ca','constructaccess');
                   8200:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8201:         return($ownername,$ownerdomain,$ownerhome);
                   8202:     }
                   8203: # No business here
                   8204:     return '';
                   8205: }
                   8206: 
1.1172.2.66  raeburn  8207: # ----------------------------------------------------------- Content Blocking
                   8208: 
                   8209: {
                   8210: # Caches for faster Course Contents display where content blocking
                   8211: # is in operation (i.e., interval param set) for timed quiz.
                   8212: #
                   8213: # User for whom data are being temporarily cached.
                   8214: my $cacheduser='';
                   8215: # Cached blockers for this user (a hash of blocking items).
                   8216: my %cachedblockers=();
                   8217: # When the data were last cached.
                   8218: my $cachedlast='';
                   8219: 
                   8220: sub load_all_blockers {
                   8221:     my ($uname,$udom,$blocks)=@_;
                   8222:     if (($uname ne '') && ($udom ne '')) {
                   8223:         if (($cacheduser eq $uname.':'.$udom) &&
                   8224:             (abs($cachedlast-time)<5)) {
                   8225:             return;
                   8226:         }
                   8227:     }
                   8228:     $cachedlast=time;
                   8229:     $cacheduser=$uname.':'.$udom;
                   8230:     %cachedblockers = &get_commblock_resources($blocks);
                   8231: }
                   8232: 
1.1162    raeburn  8233: sub get_comm_blocks {
                   8234:     my ($cdom,$cnum) = @_;
                   8235:     if ($cdom eq '' || $cnum eq '') {
                   8236:         return unless ($env{'request.course.id'});
                   8237:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8238:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8239:     }
                   8240:     my %commblocks;
                   8241:     my $hashid=$cdom.'_'.$cnum;
                   8242:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8243:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8244:         %commblocks = %{$blocksref};
                   8245:     } else {
                   8246:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8247:         my $cachetime = 600;
                   8248:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8249:     }
                   8250:     return %commblocks;
                   8251: }
                   8252: 
1.1172.2.66  raeburn  8253: sub get_commblock_resources {
                   8254:     my ($blocks) = @_;
                   8255:     my %blockers = ();
                   8256:     return %blockers unless ($env{'request.course.id'});
                   8257:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  8258:     my %commblocks;
                   8259:     if (ref($blocks) eq 'HASH') {
                   8260:         %commblocks = %{$blocks};
                   8261:     } else {
                   8262:         %commblocks = &get_comm_blocks();
                   8263:     }
1.1172.2.66  raeburn  8264:     return %blockers unless (keys(%commblocks) > 0);
1.1163    raeburn  8265:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66  raeburn  8266:     return %blockers unless (ref($navmap));
                   8267:     my $now = time;
1.1162    raeburn  8268:     foreach my $block (keys(%commblocks)) {
                   8269:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8270:             my ($start,$end) = ($1,$2);
                   8271:             if ($start <= $now && $end >= $now) {
                   8272:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8273:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8274:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66  raeburn  8275:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8276:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162    raeburn  8277:                             }
                   8278:                         }
                   8279:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66  raeburn  8280:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8281:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8282:                             }
                   8283:                         }
                   8284:                     }
                   8285:                 }
                   8286:             }
                   8287:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8288:             my $item = $1;
1.1163    raeburn  8289:             my @to_test;
1.1162    raeburn  8290:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8291:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.66  raeburn  8292:                     my @interval;
                   8293:                     my $type = 'map';
                   8294:                     if ($item eq 'course') {
                   8295:                         $type = 'course';
                   8296:                         @interval=&EXT("resource.0.interval");
                   8297:                     } else {
                   8298:                         if ($item =~ /___\d+___/) {
                   8299:                             $type = 'resource';
                   8300:                             @interval=&EXT("resource.0.interval",$item);
                   8301:                             if (ref($navmap)) {
                   8302:                                 my $res = $navmap->getBySymb($item);
                   8303:                                 push(@to_test,$res);
                   8304:                             }
1.1162    raeburn  8305:                         } else {
1.1172.2.66  raeburn  8306:                             my $mapsymb = &symbread($item,1);
                   8307:                             if ($mapsymb) {
                   8308:                                 if (ref($navmap)) {
                   8309:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   8310:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   8311:                                     foreach my $res (@to_test) {
                   8312:                                         my $symb = $res->symb();
                   8313:                                         next if ($symb eq $mapsymb);
                   8314:                                         if ($symb ne '') {
                   8315:                                             @interval=&EXT("resource.0.interval",$symb);
                   8316:                                             if ($interval[1] eq 'map') {
                   8317:                                                 last;
1.1162    raeburn  8318:                                             }
                   8319:                                         }
                   8320:                                     }
                   8321:                                 }
                   8322:                             }
                   8323:                         }
1.1172.2.66  raeburn  8324:                     }
                   8325:                     if ($interval[0] =~ /^\d+$/) {
                   8326:                         my $first_access;
                   8327:                         if ($type eq 'resource') {
                   8328:                             $first_access=&get_first_access($interval[1],$item);
                   8329:                         } elsif ($type eq 'map') {
                   8330:                             $first_access=&get_first_access($interval[1],undef,$item);
                   8331:                         } else {
                   8332:                             $first_access=&get_first_access($interval[1]);
                   8333:                         }
                   8334:                         if ($first_access) {
                   8335:                             my $timesup = $first_access+$interval[0];
                   8336:                             if ($timesup > $now) {
                   8337:                                 my $activeblock;
                   8338:                                 foreach my $res (@to_test) {
                   8339:                                     if ($res->answerable()) {
                   8340:                                         $activeblock = 1;
                   8341:                                         last;
                   8342:                                     }
                   8343:                                 }
                   8344:                                 if ($activeblock) {
                   8345:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   8346:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8347:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   8348:                                          }
                   8349:                                     }
                   8350:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   8351:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8352:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  8353:                                         }
1.1162    raeburn  8354:                                     }
                   8355:                                 }
                   8356:                             }
                   8357:                         }
                   8358:                     }
                   8359:                 }
                   8360:             }
                   8361:         }
                   8362:     }
1.1172.2.66  raeburn  8363:     return %blockers;
1.1162    raeburn  8364: }
                   8365: 
1.1172.2.66  raeburn  8366: sub has_comm_blocking {
                   8367:     my ($priv,$symb,$uri,$blocks) = @_;
                   8368:     my @blockers;
                   8369:     return unless ($env{'request.course.id'});
                   8370:     return unless ($priv eq 'bre');
                   8371:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   8372:     return if ($env{'request.state'} eq 'construct');
                   8373:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   8374:     return unless (keys(%cachedblockers) > 0);
                   8375:     my (%possibles,@symbs);
                   8376:     if (!$symb) {
                   8377:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  8378:     }
1.1172.2.66  raeburn  8379:     if ($symb) {
                   8380:         @symbs = ($symb);
                   8381:     } elsif (keys(%possibles)) {
                   8382:         @symbs = keys(%possibles);
                   8383:     }
                   8384:     my $noblock;
                   8385:     foreach my $symb (@symbs) {
                   8386:         last if ($noblock);
                   8387:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   8388:         foreach my $block (keys(%cachedblockers)) {
                   8389:             if ($block =~ /^firstaccess____(.+)$/) {
                   8390:                 my $item = $1;
                   8391:                 if (($item eq $map) || ($item eq $symb)) {
                   8392:                     $noblock = 1;
                   8393:                     last;
                   8394:                 }
1.1162    raeburn  8395:             }
1.1172.2.66  raeburn  8396:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   8397:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   8398:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   8399:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8400:                             push(@blockers,$block);
                   8401:                         }
                   8402:                     }
                   8403:                 }
                   8404:             }
                   8405:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   8406:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   8407:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   8408:                         push(@blockers,$block);
                   8409:                     }
                   8410:                 }
1.1162    raeburn  8411:             }
                   8412:         }
                   8413:     }
1.1172.2.66  raeburn  8414:     return if ($noblock);
                   8415:     return @blockers;
                   8416: }
1.1162    raeburn  8417: }
                   8418: 
1.1172.2.66  raeburn  8419: # -------------------------------- Deversion and split uri into path an filename
                   8420: 
1.1133    foxr     8421: #
1.1172.2.66  raeburn  8422: #   Removes the version from a URI and
1.1133    foxr     8423: #   splits it in to its filename and path to the filename.
                   8424: #   Seems like File::Basename could have done this more clearly.
                   8425: #   Parameters:
                   8426: #      $uri   - input URI
                   8427: #   Returns:
                   8428: #     Two element list consisting of 
                   8429: #     $pathname  - the URI up to and excluding the trailing /
                   8430: #     $filename  - The part of the URI following the last /
                   8431: #  NOTE:
                   8432: #    Another realization of this is simply:
                   8433: #    use File::Basename;
                   8434: #    ...
                   8435: #    $uri = shift;
                   8436: #    $filename = basename($uri);
                   8437: #    $path     = dirname($uri);
                   8438: #    return ($filename, $path);
                   8439: #
                   8440: #     The implementation below is probably faster however.
                   8441: #
1.710     albertel 8442: sub split_uri_for_cond {
                   8443:     my $uri=&deversion(&declutter(shift));
                   8444:     my @uriparts=split(/\//,$uri);
                   8445:     my $filename=pop(@uriparts);
                   8446:     my $pathname=join('/',@uriparts);
                   8447:     return ($pathname,$filename);
                   8448: }
1.232     www      8449: # --------------------------------------------------- Is a resource on the map?
                   8450: 
                   8451: sub is_on_map {
1.710     albertel 8452:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 8453:     #Trying to find the conditional for the file
1.620     albertel 8454:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 8455: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      8456:     if ($match) {
1.289     bowersj2 8457: 	return (1,$1);
                   8458:     } else {
1.434     www      8459: 	return (0,0);
1.289     bowersj2 8460:     }
1.12      www      8461: }
                   8462: 
1.427     www      8463: # --------------------------------------------------------- Get symb from alias
                   8464: 
                   8465: sub get_symb_from_alias {
                   8466:     my $symb=shift;
                   8467:     my ($map,$resid,$url)=&decode_symb($symb);
                   8468: # Already is a symb
                   8469:     if ($url) { return $symb; }
                   8470: # Must be an alias
                   8471:     my $aliassymb='';
                   8472:     my %bighash;
1.620     albertel 8473:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      8474:                             &GDBM_READER(),0640)) {
                   8475:         my $rid=$bighash{'mapalias_'.$symb};
                   8476: 	if ($rid) {
                   8477: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 8478: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   8479: 				    $resid,$bighash{'src_'.$rid});
1.427     www      8480: 	}
                   8481:         untie %bighash;
                   8482:     }
                   8483:     return $aliassymb;
                   8484: }
                   8485: 
1.12      www      8486: # ----------------------------------------------------------------- Define Role
                   8487: 
                   8488: sub definerole {
                   8489:   if (allowed('mcr','/')) {
1.1172.2.84  raeburn  8490:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 8491:     foreach my $role (split(':',$sysrole)) {
                   8492: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8493:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   8494:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   8495: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8496:                return "refused:s:$crole&$cqual"; 
                   8497:             }
                   8498:         }
1.191     harris41 8499:     }
1.800     albertel 8500:     foreach my $role (split(':',$domrole)) {
                   8501: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8502:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   8503:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   8504: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      8505:                return "refused:d:$crole&$cqual"; 
                   8506:             }
                   8507:         }
1.191     harris41 8508:     }
1.800     albertel 8509:     foreach my $role (split(':',$courole)) {
                   8510: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8511:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   8512:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   8513: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8514:                return "refused:c:$crole&$cqual"; 
                   8515:             }
                   8516:         }
1.191     harris41 8517:     }
1.1172.2.84  raeburn  8518:     my $uhome;
                   8519:     if (($uname ne '') && ($udom ne '')) {
                   8520:         $uhome = &homeserver($uname,$udom);
                   8521:         return $uhome if ($uhome eq 'no_host');
                   8522:     } else {
                   8523:         $uname = $env{'user.name'};
                   8524:         $udom = $env{'user.domain'};
                   8525:         $uhome = $env{'user.home'};
                   8526:     }
1.620     albertel 8527:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84  raeburn  8528:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      8529:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84  raeburn  8530:     return reply($command,$uhome);
1.12      www      8531:   } else {
                   8532:     return 'refused';
                   8533:   }
1.105     harris41 8534: }
                   8535: 
                   8536: # ---------------- Make a metadata query against the network of library servers
                   8537: 
                   8538: sub metadata_query {
1.1172.2.33  raeburn  8539:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 8540:     my %rhash;
1.845     albertel 8541:     my %libserv = &all_library();
1.244     matthew  8542:     my @server_list = (defined($server_array) ? @$server_array
                   8543:                                               : keys(%libserv) );
                   8544:     for my $server (@server_list) {
1.1172.2.33  raeburn  8545:         my $domains = '';
                   8546:         if (ref($domains_hash) eq 'HASH') {
                   8547:             $domains = $domains_hash->{$server};    
                   8548:         }
1.118     harris41 8549: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  8550: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 8551: 	    $rhash{$server}=$reply;
                   8552: 	}
                   8553: 	else {
                   8554: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  8555: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 8556: 			     $server);
                   8557: 	    $rhash{$server}=$reply;
                   8558: 	}
1.112     harris41 8559:     }
1.118     harris41 8560:     return \%rhash;
1.240     www      8561: }
                   8562: 
                   8563: # ----------------------------------------- Send log queries and wait for reply
                   8564: 
                   8565: sub log_query {
                   8566:     my ($uname,$udom,$query,%filters)=@_;
                   8567:     my $uhome=&homeserver($uname,$udom);
                   8568:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 8569:     my $uhost=&hostname($uhome);
1.800     albertel 8570:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      8571:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   8572:                        $uhome);
1.479     albertel 8573:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      8574:     return get_query_reply($queryid);
                   8575: }
                   8576: 
1.818     raeburn  8577: # -------------------------- Update MySQL table for portfolio file
                   8578: 
                   8579: sub update_portfolio_table {
1.821     raeburn  8580:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  8581:     if ($group ne '') {
                   8582:         $file_name =~s /^\Q$group\E//;
                   8583:     }
1.818     raeburn  8584:     my $homeserver = &homeserver($uname,$udom);
                   8585:     my $queryid=
1.821     raeburn  8586:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   8587:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  8588:     my $reply = &get_query_reply($queryid);
                   8589:     return $reply;
                   8590: }
                   8591: 
1.899     raeburn  8592: # -------------------------- Update MySQL allusers table
                   8593: 
                   8594: sub update_allusers_table {
                   8595:     my ($uname,$udom,$names) = @_;
                   8596:     my $homeserver = &homeserver($uname,$udom);
                   8597:     my $queryid=
                   8598:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   8599:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   8600:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   8601:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   8602:                'generation='.&escape($names->{'generation'}).'%%'.
                   8603:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   8604:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  8605:     return;
1.899     raeburn  8606: }
                   8607: 
1.508     raeburn  8608: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  8609: 
                   8610: sub fetch_enrollment_query {
1.511     raeburn  8611:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79  raeburn  8612:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  8613:     my $maxtries = 1;
1.508     raeburn  8614:     if ($context eq 'automated') {
                   8615:         $homeserver = $perlvar{'lonHostID'};
1.1172.2.79  raeburn  8616:         $sleep = 2;
                   8617:         $loopmax = 100;
1.547     raeburn  8618:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  8619:     } else {
                   8620:         $homeserver = &homeserver($cnum,$dom);
                   8621:     }
1.838     albertel 8622:     my $host=&hostname($homeserver);
1.506     raeburn  8623:     my $cmd = '';
1.1000    raeburn  8624:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 8625:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  8626:     }
                   8627:     $cmd =~ s/%%$//;
                   8628:     $cmd = &escape($cmd);
                   8629:     my $query = 'fetchenrollment';
1.620     albertel 8630:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  8631:     unless ($queryid=~/^\Q$host\E\_/) { 
                   8632:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   8633:         return 'error: '.$queryid;
                   8634:     }
1.1172.2.93  raeburn  8635:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8636:     my $tries = 1;
                   8637:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79  raeburn  8638:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8639:         $tries ++;
                   8640:     }
1.526     raeburn  8641:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 8642:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  8643:     } else {
1.901     albertel 8644:         my @responses = split(/:/,$reply);
1.1172.2.82  raeburn  8645:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 8646:             foreach my $line (@responses) {
                   8647:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  8648:                 $$replyref{$key} = $value;
                   8649:             }
                   8650:         } else {
1.1117    foxr     8651:             my $pathname = LONCAPA::tempdir();
1.800     albertel 8652:             foreach my $line (@responses) {
                   8653:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  8654:                 $$replyref{$key} = $value;
                   8655:                 if ($value > 0) {
1.800     albertel 8656:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   8657:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  8658:                         my $destname = $pathname.'/'.$filename;
                   8659:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  8660:                         if ($xml_classlist =~ /^error/) {
                   8661:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   8662:                         } else {
1.1172.2.96  raeburn  8663:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  8664:                                 print FILE &unescape($xml_classlist);
                   8665:                                 close(FILE);
1.526     raeburn  8666:                             } else {
                   8667:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  8668:                             }
                   8669:                         }
                   8670:                     }
                   8671:                 }
                   8672:             }
                   8673:         }
                   8674:         return 'ok';
                   8675:     }
                   8676:     return 'error';
                   8677: }
                   8678: 
1.242     www      8679: sub get_query_reply {
1.1172.2.79  raeburn  8680:     my ($queryid,$sleep,$loopmax) = @_;
                   8681:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   8682:         $sleep = 0.2;
                   8683:     }
                   8684:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   8685:         $loopmax = 100;
                   8686:     }
1.1117    foxr     8687:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      8688:     my $reply='';
1.1172.2.79  raeburn  8689:     for (1..$loopmax) {
                   8690: 	sleep($sleep);
1.240     www      8691:         if (-e $replyfile.'.end') {
1.1172.2.96  raeburn  8692: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 8693: 		$reply = join('',<$fh>);
                   8694: 		close($fh);
1.240     www      8695: 	   } else { return 'error: reply_file_error'; }
1.242     www      8696:            return &unescape($reply);
                   8697: 	}
1.240     www      8698:     }
1.242     www      8699:     return 'timeout:'.$queryid;
1.240     www      8700: }
                   8701: 
                   8702: sub courselog_query {
1.241     www      8703: #
                   8704: # possible filters:
                   8705: # url: url or symb
                   8706: # username
                   8707: # domain
                   8708: # action: view, submit, grade
                   8709: # start: timestamp
                   8710: # end: timestamp
                   8711: #
1.240     www      8712:     my (%filters)=@_;
1.620     albertel 8713:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      8714:     if ($filters{'url'}) {
                   8715: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   8716:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   8717:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   8718:     }
1.620     albertel 8719:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8720:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      8721:     return &log_query($cname,$cdom,'courselog',%filters);
                   8722: }
                   8723: 
                   8724: sub userlog_query {
1.858     raeburn  8725: #
                   8726: # possible filters:
                   8727: # action: log check role
                   8728: # start: timestamp
                   8729: # end: timestamp
                   8730: #
1.240     www      8731:     my ($uname,$udom,%filters)=@_;
                   8732:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      8733: }
                   8734: 
1.506     raeburn  8735: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   8736: 
                   8737: sub auto_run {
1.508     raeburn  8738:     my ($cnum,$cdom) = @_;
1.876     raeburn  8739:     my $response = 0;
                   8740:     my $settings;
                   8741:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   8742:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   8743:         $settings = $domconfig{'autoenroll'};
                   8744:         if ($settings->{'run'} eq '1') {
                   8745:             $response = 1;
                   8746:         }
                   8747:     } else {
1.934     raeburn  8748:         my $homeserver;
                   8749:         if (&is_course($cdom,$cnum)) {
                   8750:             $homeserver = &homeserver($cnum,$cdom);
                   8751:         } else {
                   8752:             $homeserver = &domain($cdom,'primary');
                   8753:         }
                   8754:         if ($homeserver ne 'no_host') {
                   8755:             $response = &reply('autorun:'.$cdom,$homeserver);
                   8756:         }
1.876     raeburn  8757:     }
1.506     raeburn  8758:     return $response;
                   8759: }
1.776     albertel 8760: 
1.506     raeburn  8761: sub auto_get_sections {
1.508     raeburn  8762:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  8763:     my $homeserver;
                   8764:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   8765:         $homeserver = &homeserver($cnum,$cdom);
                   8766:     }
                   8767:     if (!defined($homeserver)) { 
                   8768:         if ($cdom =~ /^$match_domain$/) {
                   8769:             $homeserver = &domain($cdom,'primary');
                   8770:         }
                   8771:     }
                   8772:     my @secs;
                   8773:     if (defined($homeserver)) {
                   8774:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   8775:         unless ($response eq 'refused') {
                   8776:             @secs = split(/:/,$response);
                   8777:         }
1.506     raeburn  8778:     }
                   8779:     return @secs;
                   8780: }
1.776     albertel 8781: 
1.506     raeburn  8782: sub auto_new_course {
1.1099    raeburn  8783:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  8784:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  8785:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  8786:     return $response;
                   8787: }
1.776     albertel 8788: 
1.506     raeburn  8789: sub auto_validate_courseID {
1.508     raeburn  8790:     my ($cnum,$cdom,$inst_course_id) = @_;
                   8791:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  8792:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  8793:     return $response;
                   8794: }
1.776     albertel 8795: 
1.1007    raeburn  8796: sub auto_validate_instcode {
1.1020    raeburn  8797:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  8798:     my ($homeserver,$response);
                   8799:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8800:         $homeserver = &homeserver($cnum,$cdom);
                   8801:     }
                   8802:     if (!defined($homeserver)) {
                   8803:         if ($cdom =~ /^$match_domain$/) {
                   8804:             $homeserver = &domain($cdom,'primary');
                   8805:         }
                   8806:     }
1.1065    raeburn  8807:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   8808:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  8809:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   8810:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  8811: }
                   8812: 
1.506     raeburn  8813: sub auto_create_password {
1.873     raeburn  8814:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   8815:     my ($homeserver,$response);
1.506     raeburn  8816:     my $create_passwd = 0;
                   8817:     my $authchk = '';
1.873     raeburn  8818:     if ($udom =~ /^$match_domain$/) {
                   8819:         $homeserver = &domain($udom,'primary');
                   8820:     }
                   8821:     if ($homeserver eq '') {
                   8822:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8823:             $homeserver = &homeserver($cnum,$cdom);
                   8824:         }
                   8825:     }
                   8826:     if ($homeserver eq '') {
                   8827:         $authchk = 'nodomain';
1.506     raeburn  8828:     } else {
1.873     raeburn  8829:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   8830:         if ($response eq 'refused') {
                   8831:             $authchk = 'refused';
                   8832:         } else {
1.901     albertel 8833:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  8834:         }
1.506     raeburn  8835:     }
                   8836:     return ($authparam,$create_passwd,$authchk);
                   8837: }
                   8838: 
1.706     raeburn  8839: sub auto_photo_permission {
                   8840:     my ($cnum,$cdom,$students) = @_;
                   8841:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 8842:     my ($outcome,$perm_reqd,$conditions) = 
                   8843: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 8844:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8845: 	return (undef,undef);
                   8846:     }
1.706     raeburn  8847:     return ($outcome,$perm_reqd,$conditions);
                   8848: }
                   8849: 
                   8850: sub auto_checkphotos {
                   8851:     my ($uname,$udom,$pid) = @_;
                   8852:     my $homeserver = &homeserver($uname,$udom);
                   8853:     my ($result,$resulttype);
                   8854:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 8855: 				   &escape($uname).':'.&escape($pid),
                   8856: 				   $homeserver));
1.709     albertel 8857:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8858: 	return (undef,undef);
                   8859:     }
1.706     raeburn  8860:     if ($outcome) {
                   8861:         ($result,$resulttype) = split(/:/,$outcome);
                   8862:     } 
                   8863:     return ($result,$resulttype);
                   8864: }
                   8865: 
                   8866: sub auto_photochoice {
                   8867:     my ($cnum,$cdom) = @_;
                   8868:     my $homeserver = &homeserver($cnum,$cdom);
                   8869:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 8870: 						       &escape($cdom),
                   8871: 						       $homeserver)));
1.709     albertel 8872:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8873: 	return (undef,undef);
                   8874:     }
1.706     raeburn  8875:     return ($update,$comment);
                   8876: }
                   8877: 
                   8878: sub auto_photoupdate {
                   8879:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   8880:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 8881:     my $host=&hostname($homeserver);
1.706     raeburn  8882:     my $cmd = '';
                   8883:     my $maxtries = 1;
1.800     albertel 8884:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   8885:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  8886:     }
                   8887:     $cmd =~ s/%%$//;
                   8888:     $cmd = &escape($cmd);
                   8889:     my $query = 'institutionalphotos';
                   8890:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   8891:     unless ($queryid=~/^\Q$host\E\_/) {
                   8892:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   8893:         return 'error: '.$queryid;
                   8894:     }
                   8895:     my $reply = &get_query_reply($queryid);
                   8896:     my $tries = 1;
                   8897:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   8898:         $reply = &get_query_reply($queryid);
                   8899:         $tries ++;
                   8900:     }
                   8901:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   8902:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   8903:     } else {
                   8904:         my @responses = split(/:/,$reply);
                   8905:         my $outcome = shift(@responses); 
                   8906:         foreach my $item (@responses) {
                   8907:             my ($key,$value) = split(/=/,$item);
                   8908:             $$photo{$key} = $value;
                   8909:         }
                   8910:         return $outcome;
                   8911:     }
                   8912:     return 'error';
                   8913: }
                   8914: 
1.521     raeburn  8915: sub auto_instcode_format {
1.793     albertel 8916:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   8917: 	$cat_order) = @_;
1.521     raeburn  8918:     my $courses = '';
1.772     raeburn  8919:     my @homeservers;
1.521     raeburn  8920:     if ($caller eq 'global') {
1.841     albertel 8921: 	my %servers = &get_servers($codedom,'library');
                   8922: 	foreach my $tryserver (keys(%servers)) {
                   8923: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8924: 		push(@homeservers,$tryserver);
                   8925: 	    }
1.584     raeburn  8926:         }
1.1022    raeburn  8927:     } elsif ($caller eq 'requests') {
                   8928:         if ($codedom =~ /^$match_domain$/) {
                   8929:             my $chome = &domain($codedom,'primary');
                   8930:             unless ($chome eq 'no_host') {
                   8931:                 push(@homeservers,$chome);
                   8932:             }
                   8933:         }
1.521     raeburn  8934:     } else {
1.772     raeburn  8935:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  8936:     }
1.793     albertel 8937:     foreach my $code (keys(%{$instcodes})) {
                   8938:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  8939:     }
                   8940:     chop($courses);
1.772     raeburn  8941:     my $ok_response = 0;
                   8942:     my $response;
                   8943:     while (@homeservers > 0 && $ok_response == 0) {
                   8944:         my $server = shift(@homeservers); 
                   8945:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   8946:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   8947:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 8948: 		split(/:/,$response);
1.772     raeburn  8949:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   8950:             push(@{$codetitles},&str2array($codetitles_str));
                   8951:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   8952:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   8953:             $ok_response = 1;
                   8954:         }
                   8955:     }
                   8956:     if ($ok_response) {
1.521     raeburn  8957:         return 'ok';
1.772     raeburn  8958:     } else {
                   8959:         return $response;
1.521     raeburn  8960:     }
                   8961: }
                   8962: 
1.792     raeburn  8963: sub auto_instcode_defaults {
                   8964:     my ($domain,$returnhash,$code_order) = @_;
                   8965:     my @homeservers;
1.841     albertel 8966: 
                   8967:     my %servers = &get_servers($domain,'library');
                   8968:     foreach my $tryserver (keys(%servers)) {
                   8969: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8970: 	    push(@homeservers,$tryserver);
                   8971: 	}
1.792     raeburn  8972:     }
1.841     albertel 8973: 
1.792     raeburn  8974:     my $response;
1.841     albertel 8975:     foreach my $server (@homeservers) {
1.792     raeburn  8976:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 8977:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   8978: 	
                   8979: 	foreach my $pair (split(/\&/,$response)) {
                   8980: 	    my ($name,$value)=split(/\=/,$pair);
                   8981: 	    if ($name eq 'code_order') {
                   8982: 		@{$code_order} = split(/\&/,&unescape($value));
                   8983: 	    } else {
                   8984: 		$returnhash->{&unescape($name)}=&unescape($value);
                   8985: 	    }
                   8986: 	}
                   8987: 	return 'ok';
1.792     raeburn  8988:     }
1.841     albertel 8989: 
                   8990:     return $response;
1.1003    raeburn  8991: }
                   8992: 
                   8993: sub auto_possible_instcodes {
1.1007    raeburn  8994:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   8995:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   8996:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8997:         return;
                   8998:     }
1.1003    raeburn  8999:     my (@homeservers,$uhome);
                   9000:     if (defined(&domain($domain,'primary'))) {
                   9001:         $uhome=&domain($domain,'primary');
                   9002:         push(@homeservers,&domain($domain,'primary'));
                   9003:     } else {
                   9004:         my %servers = &get_servers($domain,'library');
                   9005:         foreach my $tryserver (keys(%servers)) {
                   9006:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9007:                 push(@homeservers,$tryserver);
                   9008:             }
                   9009:         }
                   9010:     }
                   9011:     my $response;
                   9012:     foreach my $server (@homeservers) {
                   9013:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   9014:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  9015:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   9016:             split(':',$response);
                   9017:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   9018:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  9019:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  9020:             my ($name,$value)=split('=',$item);
                   9021:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9022:         }
                   9023:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  9024:             my ($name,$value)=split('=',$item);
                   9025:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9026:         }
                   9027:         return 'ok';
                   9028:     }
                   9029:     return $response;
                   9030: }
1.792     raeburn  9031: 
1.1010    raeburn  9032: sub auto_courserequest_checks {
                   9033:     my ($dom) = @_;
1.1020    raeburn  9034:     my ($homeserver,%validations);
                   9035:     if ($dom =~ /^$match_domain$/) {
                   9036:         $homeserver = &domain($dom,'primary');
                   9037:     }
                   9038:     unless ($homeserver eq 'no_host') {
                   9039:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   9040:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9041:             my @items = split(/&/,$response);
                   9042:             foreach my $item (@items) {
                   9043:                 my ($key,$value) = split('=',$item);
                   9044:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   9045:             }
                   9046:         }
                   9047:     }
1.1010    raeburn  9048:     return %validations; 
                   9049: }
                   9050: 
1.1020    raeburn  9051: sub auto_courserequest_validation {
1.1172.2.43  raeburn  9052:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  9053:     my ($homeserver,$response);
                   9054:     if ($dom =~ /^$match_domain$/) {
                   9055:         $homeserver = &domain($dom,'primary');
                   9056:     }
1.1172.2.43  raeburn  9057:     unless ($homeserver eq 'no_host') {
                   9058:         my $customdata;
                   9059:         if (ref($custominfo) eq 'HASH') {
                   9060:             $customdata = &freeze_escape($custominfo);
                   9061:         }
1.1020    raeburn  9062:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  9063:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43  raeburn  9064:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   9065:                                     $customdata,$homeserver));
1.1020    raeburn  9066:     }
                   9067:     return $response;
                   9068: }
                   9069: 
1.777     albertel 9070: sub auto_validate_class_sec {
1.918     raeburn  9071:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  9072:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  9073:     my $ownerlist;
                   9074:     if (ref($owners) eq 'ARRAY') {
                   9075:         $ownerlist = join(',',@{$owners});
                   9076:     } else {
                   9077:         $ownerlist = $owners;
                   9078:     }
1.773     raeburn  9079:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  9080:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  9081:     return $response;
                   9082: }
                   9083: 
1.1172.2.94  raeburn  9084: sub auto_validate_instclasses {
                   9085:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   9086:     my ($homeserver,%validations);
                   9087:     $homeserver = &homeserver($cnum,$cdom);
                   9088:     unless ($homeserver eq 'no_host') {
                   9089:         my $ownerlist;
                   9090:         if (ref($owners) eq 'ARRAY') {
                   9091:             $ownerlist = join(',',@{$owners});
                   9092:         } else {
                   9093:             $ownerlist = $owners;
                   9094:         }
                   9095:         if (ref($classesref) eq 'HASH') {
                   9096:             my $classes = &freeze_escape($classesref);
                   9097:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   9098:                                 ':'.$cdom.':'.$classes,$homeserver);
                   9099:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9100:                 my @items = split(/&/,$response);
                   9101:                 foreach my $item (@items) {
                   9102:                     my ($key,$value) = split('=',$item);
                   9103:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   9104:                 }
                   9105:             }
                   9106:         }
                   9107:     }
                   9108:     return %validations;
                   9109: }
                   9110: 
1.1172.2.38  raeburn  9111: sub auto_crsreq_update {
                   9112:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45  raeburn  9113:         $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38  raeburn  9114:     my ($homeserver,%crsreqresponse);
                   9115:     if ($cdom =~ /^$match_domain$/) {
                   9116:         $homeserver = &domain($cdom,'primary');
                   9117:     }
                   9118:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9119:         my $info;
                   9120:         if (ref($inbound) eq 'HASH') {
                   9121:             $info = &freeze_escape($inbound);
                   9122:         }
                   9123:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   9124:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   9125:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45  raeburn  9126:                             &escape($title).':'.&escape($code).':'.
                   9127:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38  raeburn  9128:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9129:             my @items = split(/&/,$response);
                   9130:             foreach my $item (@items) {
                   9131:                 my ($key,$value) = split('=',$item);
                   9132:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   9133:             }
                   9134:         }
                   9135:     }
                   9136:     return \%crsreqresponse;
                   9137: }
                   9138: 
1.1172.2.78  raeburn  9139: sub auto_export_grades {
                   9140:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   9141:     my ($homeserver,%exportresponse);
                   9142:     if ($cdom =~ /^$match_domain$/) {
                   9143:         $homeserver = &domain($cdom,'primary');
                   9144:     }
                   9145:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9146:         my $info;
                   9147:         if (ref($inforef) eq 'HASH') {
                   9148:             $info = &freeze_escape($inforef);
                   9149:         }
                   9150:         if (ref($gradesref) eq 'HASH') {
                   9151:             my $grades = &freeze_escape($gradesref);
                   9152:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   9153:                                 $info.':'.$grades,$homeserver);
                   9154:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   9155:                 my @items = split(/&/,$response);
                   9156:                 foreach my $item (@items) {
                   9157:                     my ($key,$value) = split('=',$item);
                   9158:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   9159:                 }
                   9160:             }
                   9161:         }
                   9162:     }
                   9163:     return \%exportresponse;
                   9164: }
                   9165: 
1.1172.2.68  raeburn  9166: sub check_instcode_cloning {
                   9167:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   9168:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9169:         return;
                   9170:     }
                   9171:     my $canclone;
                   9172:     if (@{$code_order} > 0) {
                   9173:         my $instcoderegexp ='^';
                   9174:         my @clonecodes = split(/\&/,$cloner);
                   9175:         foreach my $item (@{$code_order}) {
                   9176:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   9177:                 foreach my $pair (@clonecodes) {
                   9178:                     my ($key,$val) = split(/\=/,$pair,2);
                   9179:                     $val = &unescape($val);
                   9180:                     if ($key eq $item) {
                   9181:                         $instcoderegexp .= '('.$val.')';
                   9182:                         last;
                   9183:                     }
                   9184:                 }
                   9185:             } else {
                   9186:                 $instcoderegexp .= $codedefaults->{$item};
                   9187:             }
                   9188:         }
                   9189:         $instcoderegexp .= '$';
                   9190:         my (@from,@to);
                   9191:         eval {
                   9192:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9193:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9194:         };
                   9195:         if ((@from > 0) && (@to > 0)) {
                   9196:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9197:             if (!@diffs) {
                   9198:                 $canclone = 1;
                   9199:             }
                   9200:         }
                   9201:     }
                   9202:     return $canclone;
                   9203: }
                   9204: 
                   9205: sub default_instcode_cloning {
                   9206:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   9207:     my (%codedefaults,@code_order,$canclone);
                   9208:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   9209:         %codedefaults = %{$codedefaultsref};
                   9210:         @code_order = @{$codeorderref};
                   9211:     } elsif ($clonedom) {
                   9212:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   9213:     }
                   9214:     if (($domdefclone) && (@code_order)) {
                   9215:         my @clonecodes = split(/\+/,$domdefclone);
                   9216:         my $instcoderegexp ='^';
                   9217:         foreach my $item (@code_order) {
                   9218:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   9219:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   9220:             } else {
                   9221:                 $instcoderegexp .= $codedefaults{$item};
                   9222:             }
                   9223:         }
                   9224:         $instcoderegexp .= '$';
                   9225:         my (@from,@to);
                   9226:         eval {
                   9227:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9228:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9229:         };
                   9230:         if ((@from > 0) && (@to > 0)) {
                   9231:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9232:             if (!@diffs) {
                   9233:                 $canclone = 1;
                   9234:             }
                   9235:         }
                   9236:     }
                   9237:     return $canclone;
                   9238: }
                   9239: 
1.679     raeburn  9240: # ------------------------------------------------------- Course Group routines
                   9241: 
                   9242: sub get_coursegroups {
1.809     raeburn  9243:     my ($cdom,$cnum,$group,$namespace) = @_;
                   9244:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  9245: }
                   9246: 
1.679     raeburn  9247: sub modify_coursegroup {
                   9248:     my ($cdom,$cnum,$groupsettings) = @_;
                   9249:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   9250: }
                   9251: 
1.809     raeburn  9252: sub toggle_coursegroup_status {
                   9253:     my ($cdom,$cnum,$group,$action) = @_;
                   9254:     my ($from_namespace,$to_namespace);
                   9255:     if ($action eq 'delete') {
                   9256:         $from_namespace = 'coursegroups';
                   9257:         $to_namespace = 'deleted_groups';
                   9258:     } else {
                   9259:         $from_namespace = 'deleted_groups';
                   9260:         $to_namespace = 'coursegroups';
                   9261:     }
                   9262:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  9263:     if (my $tmp = &error(%curr_group)) {
                   9264:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   9265:         return ('read error',$tmp);
                   9266:     } else {
                   9267:         my %savedsettings = %curr_group; 
1.809     raeburn  9268:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  9269:         my $deloutcome;
                   9270:         if ($result eq 'ok') {
1.809     raeburn  9271:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  9272:         } else {
                   9273:             return ('write error',$result);
                   9274:         }
                   9275:         if ($deloutcome eq 'ok') {
                   9276:             return 'ok';
                   9277:         } else {
                   9278:             return ('delete error',$deloutcome);
                   9279:         }
                   9280:     }
                   9281: }
                   9282: 
1.679     raeburn  9283: sub modify_group_roles {
1.957     raeburn  9284:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  9285:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   9286:     my $role = 'gr/'.&escape($userprivs);
                   9287:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  9288:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  9289:     if ($result eq 'ok') {
                   9290:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   9291:     }
1.679     raeburn  9292:     return $result;
                   9293: }
                   9294: 
                   9295: sub modify_coursegroup_membership {
                   9296:     my ($cdom,$cnum,$membership) = @_;
                   9297:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   9298:     return $result;
                   9299: }
                   9300: 
1.682     raeburn  9301: sub get_active_groups {
                   9302:     my ($udom,$uname,$cdom,$cnum) = @_;
                   9303:     my $now = time;
                   9304:     my %groups = ();
                   9305:     foreach my $key (keys(%env)) {
1.811     albertel 9306:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  9307:             my ($start,$end) = split(/\./,$env{$key});
                   9308:             if (($end!=0) && ($end<$now)) { next; }
                   9309:             if (($start!=0) && ($start>$now)) { next; }
                   9310:             if ($1 eq $cdom && $2 eq $cnum) {
                   9311:                 $groups{$3} = $env{$key} ;
                   9312:             }
                   9313:         }
                   9314:     }
                   9315:     return %groups;
                   9316: }
                   9317: 
1.683     raeburn  9318: sub get_group_membership {
                   9319:     my ($cdom,$cnum,$group) = @_;
                   9320:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   9321: }
                   9322: 
                   9323: sub get_users_groups {
                   9324:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  9325:     my @usersgroups;
1.683     raeburn  9326:     my $cachetime=1800;
                   9327: 
                   9328:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  9329:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   9330:     if (defined($cached)) {
1.734     albertel 9331:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  9332:     } else {  
                   9333:         $grouplist = '';
1.816     raeburn  9334:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  9335:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  9336:         my $access_end = $env{'course.'.$courseid.
                   9337:                               '.default_enrollment_end_date'};
                   9338:         my $now = time;
                   9339:         foreach my $key (keys(%roleshash)) {
                   9340:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   9341:                 my $group = $1;
                   9342:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   9343:                     my $start = $2;
                   9344:                     my $end = $1;
                   9345:                     if ($start == -1) { next; } # deleted from group
                   9346:                     if (($start!=0) && ($start>$now)) { next; }
                   9347:                     if (($end!=0) && ($end<$now)) {
                   9348:                         if ($access_end && $access_end < $now) {
                   9349:                             if ($access_end - $end < 86400) {
                   9350:                                 push(@usersgroups,$group);
1.733     raeburn  9351:                             }
                   9352:                         }
1.817     raeburn  9353:                         next;
1.733     raeburn  9354:                     }
1.817     raeburn  9355:                     push(@usersgroups,$group);
1.683     raeburn  9356:                 }
                   9357:             }
                   9358:         }
1.817     raeburn  9359:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   9360:         $grouplist = join(':',@usersgroups);
                   9361:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  9362:     }
1.733     raeburn  9363:     return @usersgroups;
1.683     raeburn  9364: }
                   9365: 
                   9366: sub devalidate_getgroups_cache {
                   9367:     my ($udom,$uname,$cdom,$cnum)=@_;
                   9368:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 9369: 
1.683     raeburn  9370:     my $hashid="$udom:$uname:$courseid";
                   9371:     &devalidate_cache_new('getgroups',$hashid);
                   9372: }
                   9373: 
1.12      www      9374: # ------------------------------------------------------------------ Plain Text
                   9375: 
                   9376: sub plaintext {
1.988     raeburn  9377:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  9378:     if ($short =~ m{^cr/}) {
1.758     albertel 9379: 	return (split('/',$short))[-1];
                   9380:     }
1.742     raeburn  9381:     if (!defined($cid)) {
                   9382:         $cid = $env{'request.course.id'};
                   9383:     }
                   9384:     my %rolenames = (
1.1008    raeburn  9385:                       Course    => 'std',
                   9386:                       Community => 'alt1',
1.742     raeburn  9387:                     );
1.1037    raeburn  9388:     if ($cid ne '') {
                   9389:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   9390:             unless ($forcedefault) {
                   9391:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   9392:                 &Apache::lonlocal::mt_escape(\$roletext);
                   9393:                 return &Apache::lonlocal::mt($roletext);
                   9394:             }
                   9395:         }
                   9396:     }
                   9397:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   9398:         (defined($rolenames{$type})) && 
                   9399:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  9400:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  9401:     } elsif ($cid ne '') {
                   9402:         my $crstype = $env{'course.'.$cid.'.type'};
                   9403:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   9404:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   9405:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   9406:         }
1.742     raeburn  9407:     }
1.1037    raeburn  9408:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      9409: }
                   9410: 
                   9411: # ----------------------------------------------------------------- Assign Role
                   9412: 
                   9413: sub assignrole {
1.957     raeburn  9414:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   9415:         $context)=@_;
1.21      www      9416:     my $mrole;
                   9417:     if ($role =~ /^cr\//) {
1.393     www      9418:         my $cwosec=$url;
1.811     albertel 9419:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      9420: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  9421:            my $refused = 1;
                   9422:            if ($context eq 'requestcourses') {
                   9423:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   9424:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   9425:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   9426:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9427:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9428:                            if ($crsenv{'internal.courseowner'} eq
                   9429:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   9430:                                $refused = '';
                   9431:                            }
                   9432:                        }
                   9433:                    }
                   9434:                }
                   9435:            }
                   9436:            if ($refused) {
                   9437:                &logthis('Refused custom assignrole: '.
                   9438:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   9439:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   9440:                return 'refused';
                   9441:            }
1.104     www      9442:         }
1.21      www      9443:         $mrole='cr';
1.678     raeburn  9444:     } elsif ($role =~ /^gr\//) {
                   9445:         my $cwogrp=$url;
1.811     albertel 9446:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  9447:         unless (&allowed('mdg',$cwogrp)) {
                   9448:             &logthis('Refused group assignrole: '.
                   9449:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   9450:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   9451:             return 'refused';
                   9452:         }
                   9453:         $mrole='gr';
1.21      www      9454:     } else {
1.82      www      9455:         my $cwosec=$url;
1.811     albertel 9456:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  9457:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   9458:             my $refused;
                   9459:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   9460:                 if (!(&allowed('c'.$role,$url))) {
                   9461:                     $refused = 1;
                   9462:                 }
                   9463:             } else {
                   9464:                 $refused = 1;
                   9465:             }
1.947     raeburn  9466:             if ($refused) {
1.1045    raeburn  9467:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9468:                 if (!$selfenroll && $context eq 'course') {
                   9469:                     my %crsenv;
                   9470:                     if ($role eq 'cc' || $role eq 'co') {
                   9471:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9472:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   9473:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   9474:                                 if ($crsenv{'internal.courseowner'} eq 
                   9475:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9476:                                     $refused = '';
                   9477:                                 }
                   9478:                             }
                   9479:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   9480:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   9481:                                 if ($crsenv{'internal.courseowner'} eq 
                   9482:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9483:                                     $refused = '';
                   9484:                                 }
                   9485:                             }
                   9486:                         }
                   9487:                     }
                   9488:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  9489:                     $refused = '';
1.1017    raeburn  9490:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  9491:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  9492:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  9493:                         my $wrongcc;
                   9494:                         if ($cnum =~ /^$match_community$/) {
                   9495:                             $wrongcc = 1 if ($role eq 'cc');
                   9496:                         } else {
                   9497:                             $wrongcc = 1 if ($role eq 'co');
                   9498:                         }
                   9499:                         unless ($wrongcc) {
                   9500:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9501:                             if ($crsenv{'internal.courseowner'} eq 
                   9502:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   9503:                                 $refused = '';
                   9504:                             }
1.1017    raeburn  9505:                         }
                   9506:                     }
1.1172.2.9  raeburn  9507:                 } elsif ($context eq 'requestauthor') {
                   9508:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   9509:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   9510:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   9511:                             $refused = '';
                   9512:                         } else {
                   9513:                             my %domdefaults = &get_domain_defaults($udom);
                   9514:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   9515:                                 my $checkbystatus;
                   9516:                                 if ($env{'user.adv'}) {
                   9517:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   9518:                                     if ($disposition eq 'automatic') {
                   9519:                                         $refused = '';
                   9520:                                     } elsif ($disposition eq '') {
                   9521:                                         $checkbystatus = 1;
                   9522:                                     }
                   9523:                                 } else {
                   9524:                                     $checkbystatus = 1;
                   9525:                                 }
                   9526:                                 if ($checkbystatus) {
                   9527:                                     if ($env{'environment.inststatus'}) {
                   9528:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   9529:                                         foreach my $type (@inststatuses) {
                   9530:                                             if (($type ne '') &&
                   9531:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   9532:                                                 $refused = '';
                   9533:                                             }
                   9534:                                         }
                   9535:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   9536:                                         $refused = '';
                   9537:                                     }
                   9538:                                 }
                   9539:                             }
                   9540:                         }
                   9541:                     }
1.1017    raeburn  9542:                 }
                   9543:                 if ($refused) {
1.947     raeburn  9544:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   9545:                              ' '.$role.' '.$end.' '.$start.' by '.
                   9546: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   9547:                     return 'refused';
                   9548:                 }
1.932     raeburn  9549:             }
1.1131    raeburn  9550:         } elsif ($role eq 'au') {
                   9551:             if ($url ne '/'.$udom.'/') {
                   9552:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   9553:                          ' to assign author role for '.$uname.':'.$udom.
                   9554:                          ' in domain: '.$url.' refused (wrong domain).');
                   9555:                 return 'refused';
                   9556:             }
1.104     www      9557:         }
1.21      www      9558:         $mrole=$role;
                   9559:     }
1.620     albertel 9560:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      9561:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      9562:     if ($end) { $command.='_'.$end; }
1.21      www      9563:     if ($start) {
                   9564: 	if ($end) { 
1.81      www      9565:            $command.='_'.$start; 
1.21      www      9566:         } else {
1.81      www      9567:            $command.='_0_'.$start;
1.21      www      9568:         }
                   9569:     }
1.739     raeburn  9570:     my $origstart = $start;
                   9571:     my $origend = $end;
1.957     raeburn  9572:     my $delflag;
1.357     www      9573: # actually delete
                   9574:     if ($deleteflag) {
1.373     www      9575: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      9576: # modify command to delete the role
1.620     albertel 9577:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      9578:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 9579: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      9580: # set start and finish to negative values for userrolelog
                   9581:            $start=-1;
                   9582:            $end=-1;
1.957     raeburn  9583:            $delflag = 1;
1.357     www      9584:         }
                   9585:     }
                   9586: # send command
1.349     www      9587:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      9588: # log new user role if status is ok
1.349     www      9589:     if ($answer eq 'ok') {
1.663     raeburn  9590: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  9591:         if (($role eq 'cc') || ($role eq 'in') ||
                   9592:             ($role eq 'ep') || ($role eq 'ad') ||
                   9593:             ($role eq 'ta') || ($role eq 'st') ||
                   9594:             ($role=~/^cr/) || ($role eq 'gr') ||
                   9595:             ($role eq 'co')) {
1.1172.2.13  raeburn  9596: # for course roles, perform group memberships changes triggered by role change.
                   9597:             unless ($role =~ /^gr/) {
                   9598:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   9599:                                                  $origstart,$selfenroll,$context);
                   9600:             }
1.1172.2.9  raeburn  9601:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9602:                            $selfenroll,$context);
                   9603:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90  raeburn  9604:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   9605:                  ($role eq 'da')) {
1.1172.2.9  raeburn  9606:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9607:                            $context);
                   9608:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   9609:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9610:                              $context);
                   9611:         }
1.1053    raeburn  9612:         if ($role eq 'cc') {
                   9613:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   9614:         }
1.349     www      9615:     }
                   9616:     return $answer;
1.169     harris41 9617: }
                   9618: 
1.1053    raeburn  9619: sub autoupdate_coowners {
                   9620:     my ($url,$end,$start,$uname,$udom) = @_;
                   9621:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   9622:     if (($cdom ne '') && ($cnum ne '')) {
                   9623:         my $now = time;
                   9624:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   9625:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   9626:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   9627:             my $instcode = $coursehash{'internal.coursecode'};
                   9628:             if ($instcode ne '') {
1.1056    raeburn  9629:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   9630:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  9631:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  9632:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   9633:                         if ($result eq 'valid') {
                   9634:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  9635:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9636:                                     push(@newcoowners,$coowner);
                   9637:                                 }
                   9638:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   9639:                                     push(@newcoowners,$uname.':'.$udom);
                   9640:                                 }
                   9641:                                 @newcoowners = sort(@newcoowners);
                   9642:                             } else {
                   9643:                                 push(@newcoowners,$uname.':'.$udom);
                   9644:                             }
                   9645:                         } else {
                   9646:                             if ($coursehash{'internal.co-owners'}) {
                   9647:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9648:                                     unless ($coowner eq $uname.':'.$udom) {
                   9649:                                         push(@newcoowners,$coowner);
                   9650:                                     }
                   9651:                                 }
                   9652:                                 unless (@newcoowners > 0) {
                   9653:                                     $delcoowners = 1;
                   9654:                                     $coowners = '';
                   9655:                                 }
                   9656:                             }
                   9657:                         }
                   9658:                         if (@newcoowners || $delcoowners) {
                   9659:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   9660:                                             $delcoowners,@newcoowners);
                   9661:                         }
                   9662:                     }
                   9663:                 }
                   9664:             }
                   9665:         }
                   9666:     }
                   9667: }
                   9668: 
                   9669: sub store_coowners {
                   9670:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   9671:     my $cid = $cdom.'_'.$cnum;
                   9672:     my ($coowners,$delresult,$putresult);
                   9673:     if (@newcoowners) {
                   9674:         $coowners = join(',',@newcoowners);
                   9675:         my %coownershash = (
                   9676:                             'internal.co-owners' => $coowners,
                   9677:                            );
                   9678:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   9679:         if ($putresult eq 'ok') {
                   9680:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   9681:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   9682:             }
                   9683:         }
                   9684:     }
                   9685:     if ($delcoowners) {
                   9686:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   9687:         if ($delresult eq 'ok') {
                   9688:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   9689:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   9690:             }
                   9691:         }
                   9692:     }
                   9693:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   9694:         my %crsinfo =
                   9695:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   9696:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   9697:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   9698:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   9699:         }
                   9700:     }
                   9701: }
                   9702: 
1.169     harris41 9703: # -------------------------------------------------- Modify user authentication
1.197     www      9704: # Overrides without validation
                   9705: 
1.169     harris41 9706: sub modifyuserauth {
                   9707:     my ($udom,$uname,$umode,$upass)=@_;
                   9708:     my $uhome=&homeserver($uname,$udom);
1.197     www      9709:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   9710:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 9711:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9712:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 9713:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   9714: 		     &escape($upass),$uhome);
1.620     albertel 9715:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      9716:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   9717:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   9718:     &log($udom,,$uname,$uhome,
1.620     albertel 9719:         'Authentication changed by '.$env{'user.domain'}.', '.
                   9720:                                      $env{'user.name'}.', '.$umode.
1.197     www      9721:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 9722:     unless ($reply eq 'ok') {
1.197     www      9723:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 9724: 	return 'error: '.$reply;
                   9725:     }   
1.170     harris41 9726:     return 'ok';
1.80      www      9727: }
                   9728: 
1.81      www      9729: # --------------------------------------------------------------- Modify a user
1.80      www      9730: 
1.81      www      9731: sub modifyuser {
1.206     matthew  9732:     my ($udom,    $uname, $uid,
                   9733:         $umode,   $upass, $first,
                   9734:         $middle,  $last,  $gene,
1.1058    raeburn  9735:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 9736:     $udom= &LONCAPA::clean_domain($udom);
                   9737:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  9738:     my $showcandelete = 'none';
                   9739:     if (ref($candelete) eq 'ARRAY') {
                   9740:         if (@{$candelete} > 0) {
                   9741:             $showcandelete = join(', ',@{$candelete});
                   9742:         }
                   9743:     }
1.81      www      9744:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      9745:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  9746: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  9747:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   9748:                                      ' desiredhome not specified'). 
1.620     albertel 9749:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9750:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 9751:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  9752:     my $newuser;
                   9753:     if ($uhome eq 'no_host') {
                   9754:         $newuser = 1;
                   9755:     }
1.80      www      9756: # ----------------------------------------------------------------- Create User
1.406     albertel 9757:     if (($uhome eq 'no_host') && 
                   9758: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      9759:         my $unhome='';
1.844     albertel 9760:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  9761:             $unhome = $desiredhome;
1.620     albertel 9762: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   9763: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  9764:         } else { # load balancing routine for determining $unhome
1.81      www      9765:             my $loadm=10000000;
1.841     albertel 9766: 	    my %servers = &get_servers($udom,'library');
                   9767: 	    foreach my $tryserver (keys(%servers)) {
                   9768: 		my $answer=reply('load',$tryserver);
                   9769: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   9770: 		    $loadm=$answer;
                   9771: 		    $unhome=$tryserver;
                   9772: 		}
1.80      www      9773: 	    }
                   9774:         }
                   9775:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  9776: 	    return 'error: unable to find a home server for '.$uname.
                   9777:                    ' in domain '.$udom;
1.80      www      9778:         }
                   9779:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   9780:                          &escape($upass),$unhome);
                   9781: 	unless ($reply eq 'ok') {
                   9782:             return 'error: '.$reply;
                   9783:         }   
1.230     stredwic 9784:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      9785:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  9786: 	    return 'error: unable verify users home machine.';
1.80      www      9787:         }
1.209     matthew  9788:     }   # End of creation of new user
1.80      www      9789: # ---------------------------------------------------------------------- Add ID
                   9790:     if ($uid) {
                   9791:        $uid=~tr/A-Z/a-z/;
                   9792:        my %uidhash=&idrget($udom,$uname);
1.196     www      9793:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   9794:          && (!$forceid)) {
1.80      www      9795: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  9796: 	      return 'error: user id "'.$uid.'" does not match '.
                   9797:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      9798:           }
                   9799:        } else {
                   9800: 	  &idput($udom,($uname => $uid));
                   9801:        }
                   9802:     }
                   9803: # -------------------------------------------------------------- Add names, etc
1.313     matthew  9804:     my @tmp=&get('environment',
1.899     raeburn  9805: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  9806:                     'permanentemail','inststatus'],
1.134     albertel 9807: 		   $udom,$uname);
1.1075    raeburn  9808:     my (%names,%oldnames);
1.313     matthew  9809:     if ($tmp[0] =~ m/^error:.*/) { 
                   9810:         %names=(); 
                   9811:     } else {
                   9812:         %names = @tmp;
1.1075    raeburn  9813:         %oldnames = %names;
1.313     matthew  9814:     }
1.388     www      9815: #
1.1058    raeburn  9816: # If name, email and/or uid are blank (e.g., because an uploaded file
                   9817: # of users did not contain them), do not overwrite existing values
                   9818: # unless field is in $candelete array ref.  
                   9819: #
                   9820: 
                   9821:     my @fields = ('firstname','middlename','lastname','generation',
                   9822:                   'permanentemail','id');
                   9823:     my %newvalues;
                   9824:     if (ref($candelete) eq 'ARRAY') {
                   9825:         foreach my $field (@fields) {
                   9826:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   9827:                 if ($field eq 'firstname') {
                   9828:                     $names{$field} = $first;
                   9829:                 } elsif ($field eq 'middlename') {
                   9830:                     $names{$field} = $middle;
                   9831:                 } elsif ($field eq 'lastname') {
                   9832:                     $names{$field} = $last;
                   9833:                 } elsif ($field eq 'generation') { 
                   9834:                     $names{$field} = $gene;
                   9835:                 } elsif ($field eq 'permanentemail') {
                   9836:                     $names{$field} = $email;
                   9837:                 } elsif ($field eq 'id') {
                   9838:                     $names{$field}  = $uid;
                   9839:                 }
                   9840:             }
                   9841:         }
                   9842:     }
1.388     www      9843:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  9844:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      9845:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  9846:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      9847:     if ($email) {
                   9848:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  9849:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      9850:     }
1.899     raeburn  9851:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  9852:     if (defined($inststatus)) {
                   9853:         $names{'inststatus'} = '';
                   9854:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   9855:         if (ref($usertypes) eq 'HASH') {
                   9856:             my @okstatuses; 
                   9857:             foreach my $item (split(/:/,$inststatus)) {
                   9858:                 if (defined($usertypes->{$item})) {
                   9859:                     push(@okstatuses,$item);  
                   9860:                 }
                   9861:             }
                   9862:             if (@okstatuses) {
                   9863:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   9864:             }
                   9865:         }
                   9866:     }
1.1075    raeburn  9867:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  9868:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  9869:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  9870:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   9871:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   9872:     } else {
                   9873:         $logmsg .= ' during self creation';
                   9874:     }
1.1075    raeburn  9875:     my $changed;
                   9876:     if ($newuser) {
                   9877:         $changed = 1;
                   9878:     } else {
                   9879:         foreach my $field (@fields) {
                   9880:             if ($names{$field} ne $oldnames{$field}) {
                   9881:                 $changed = 1;
                   9882:                 last;
                   9883:             }
                   9884:         }
                   9885:     }
                   9886:     unless ($changed) {
                   9887:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   9888:         &logthis($logmsg);
                   9889:         return 'ok';
                   9890:     }
                   9891:     my $reply = &put('environment', \%names, $udom,$uname);
                   9892:     if ($reply ne 'ok') { 
                   9893:         return 'error: '.$reply;
                   9894:     }
1.1087    raeburn  9895:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   9896:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   9897:     }
1.1075    raeburn  9898:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   9899:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   9900:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  9901:     &logthis($logmsg);
1.134     albertel 9902:     return 'ok';
1.80      www      9903: }
                   9904: 
1.81      www      9905: # -------------------------------------------------------------- Modify student
1.80      www      9906: 
1.81      www      9907: sub modifystudent {
                   9908:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  9909:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76  raeburn  9910:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 9911:     if (!$cid) {
1.620     albertel 9912: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9913: 	    return 'not_in_class';
                   9914: 	}
1.80      www      9915:     }
                   9916: # --------------------------------------------------------------- Make the user
1.81      www      9917:     my $reply=&modifyuser
1.209     matthew  9918: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  9919:          $desiredhome,$email,$inststatus);
1.80      www      9920:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  9921:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  9922:     # student's environment
1.297     matthew  9923:     $uid = undef if (!$forceid);
1.455     albertel 9924:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  9925: 					$gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76  raeburn  9926:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  9927:     return $reply;
                   9928: }
                   9929: 
                   9930: sub modify_student_enrollment {
1.1172.2.23  raeburn  9931:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76  raeburn  9932:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 9933:     my ($cdom,$cnum,$chome);
                   9934:     if (!$cid) {
1.620     albertel 9935: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9936: 	    return 'not_in_class';
                   9937: 	}
1.620     albertel 9938: 	$cdom=$env{'course.'.$cid.'.domain'};
                   9939: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 9940:     } else {
                   9941: 	($cdom,$cnum)=split(/_/,$cid);
                   9942:     }
1.620     albertel 9943:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 9944:     if (!$chome) {
1.457     raeburn  9945: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  9946:     }
1.455     albertel 9947:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  9948:     # Make sure the user exists
1.81      www      9949:     my $uhome=&homeserver($uname,$udom);
                   9950:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9951: 	return 'error: no such user';
                   9952:     }
1.297     matthew  9953:     # Get student data if we were not given enough information
                   9954:     if (!defined($first)  || $first  eq '' || 
                   9955:         !defined($last)   || $last   eq '' || 
                   9956:         !defined($uid)    || $uid    eq '' || 
                   9957:         !defined($middle) || $middle eq '' || 
                   9958:         !defined($gene)   || $gene   eq '') {
1.294     matthew  9959:         # They did not supply us with enough data to enroll the student, so
                   9960:         # we need to pick up more information.
1.297     matthew  9961:         my %tmp = &get('environment',
1.294     matthew  9962:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  9963:                        ,$udom,$uname);
                   9964: 
1.800     albertel 9965:         #foreach my $key (keys(%tmp)) {
                   9966:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 9967:         #}
1.294     matthew  9968:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   9969:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   9970:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  9971:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  9972:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   9973:     }
1.556     albertel 9974:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  9975:     my $user = "$uname:$udom";
                   9976:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 9977:     my $reply=cput('classlist',
1.1148    raeburn  9978: 		   {$user => 
1.1172.2.76  raeburn  9979: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 9980: 		   $cdom,$cnum);
1.1148    raeburn  9981:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   9982:         &devalidate_getsection_cache($udom,$uname,$cid);
                   9983:     } else { 
1.81      www      9984: 	return 'error: '.$reply;
                   9985:     }
1.297     matthew  9986:     # Add student role to user
1.83      www      9987:     my $uurl='/'.$cid;
1.81      www      9988:     $uurl=~s/\_/\//g;
                   9989:     if ($usec) {
                   9990: 	$uurl.='/'.$usec;
                   9991:     }
1.1148    raeburn  9992:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   9993:                              $selfenroll,$context);
                   9994:     if ($result ne 'ok') {
                   9995:         if ($old_entry{$user} ne '') {
                   9996:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   9997:         } else {
                   9998:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   9999:         }
                   10000:     }
                   10001:     return $result; 
1.21      www      10002: }
                   10003: 
1.556     albertel 10004: sub format_name {
                   10005:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   10006:     my $name;
                   10007:     if ($first ne 'lastname') {
                   10008: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   10009:     } else {
                   10010: 	if ($lastname=~/\S/) {
                   10011: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   10012: 	    $name=~s/\s+,/,/;
                   10013: 	} else {
                   10014: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   10015: 	}
                   10016:     }
                   10017:     $name=~s/^\s+//;
                   10018:     $name=~s/\s+$//;
                   10019:     $name=~s/\s+/ /g;
                   10020:     return $name;
                   10021: }
                   10022: 
1.84      www      10023: # ------------------------------------------------- Write to course preferences
                   10024: 
                   10025: sub writecoursepref {
                   10026:     my ($courseid,%prefs)=@_;
                   10027:     $courseid=~s/^\///;
                   10028:     $courseid=~s/\_/\//g;
                   10029:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   10030:     my $chome=homeserver($cnum,$cdomain);
                   10031:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   10032: 	return 'error: no such course';
                   10033:     }
                   10034:     my $cstring='';
1.800     albertel 10035:     foreach my $pref (keys(%prefs)) {
                   10036: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 10037:     }
1.84      www      10038:     $cstring=~s/\&$//;
                   10039:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   10040: }
                   10041: 
                   10042: # ---------------------------------------------------------- Make/modify course
                   10043: 
                   10044: sub createcourse {
1.741     raeburn  10045:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  10046:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      10047:     $url=&declutter($url);
                   10048:     my $cid='';
1.1028    raeburn  10049:     if ($context eq 'requestcourses') {
                   10050:         my $can_create = 0;
                   10051:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   10052:         if ($udom eq $ownerdom) {
                   10053:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   10054:                                   $context)) {
                   10055:                 $can_create = 1;
                   10056:             }
                   10057:         } else {
                   10058:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   10059:                                            $category);
                   10060:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   10061:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   10062:                 if (@curr > 0) {
                   10063:                     my @options = qw(approval validate autolimit);
                   10064:                     my $optregex = join('|',@options);
                   10065:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   10066:                         $can_create = 1;
                   10067:                     }
                   10068:                 }
                   10069:             }
                   10070:         }
                   10071:         if ($can_create) {
                   10072:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   10073:                 unless (&allowed('ccc',$udom)) {
                   10074:                     return 'refused'; 
                   10075:                 }
1.1017    raeburn  10076:             }
                   10077:         } else {
                   10078:             return 'refused';
                   10079:         }
1.1028    raeburn  10080:     } elsif (!&allowed('ccc',$udom)) {
                   10081:         return 'refused';
1.84      www      10082:     }
1.1011    raeburn  10083: # --------------------------------------------------------------- Get Unique ID
                   10084:     my $uname;
                   10085:     if ($cnum =~ /^$match_courseid$/) {
                   10086:         my $chome=&homeserver($cnum,$udom,'true');
                   10087:         if (($chome eq '') || ($chome eq 'no_host')) {
                   10088:             $uname = $cnum;
                   10089:         } else {
1.1038    raeburn  10090:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10091:         }
                   10092:     } else {
1.1038    raeburn  10093:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10094:     }
                   10095:     return $uname if ($uname =~ /^error/);
                   10096: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  10097:     if (!defined($course_server)) {
                   10098:         if (defined(&domain($udom,'primary'))) {
                   10099:             $course_server = &domain($udom,'primary');
                   10100:         } else {
                   10101:             $course_server = $env{'user.home'}; 
                   10102:         }
                   10103:     }
                   10104:     my %host_servers =
                   10105:         &Apache::lonnet::get_servers($udom,'library');
                   10106:     unless ($host_servers{$course_server}) {
                   10107:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  10108:     }
1.84      www      10109: # ------------------------------------------------------------- Make the course
                   10110:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  10111:                       $course_server);
1.84      www      10112:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  10113:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      10114:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10115: 	return 'error: no such course';
                   10116:     }
1.271     www      10117: # ----------------------------------------------------------------- Course made
1.516     raeburn  10118: # log existence
1.1029    raeburn  10119:     my $now = time;
1.918     raeburn  10120:     my $newcourse = {
                   10121:                     $udom.'_'.$uname => {
1.921     raeburn  10122:                                      description => $description,
                   10123:                                      inst_code   => $inst_code,
                   10124:                                      owner       => $course_owner,
                   10125:                                      type        => $crstype,
1.1029    raeburn  10126:                                      creator     => $env{'user.name'}.':'.
                   10127:                                                     $env{'user.domain'},
                   10128:                                      created     => $now,
                   10129:                                      context     => $context,
1.918     raeburn  10130:                                                 },
                   10131:                     };
1.921     raeburn  10132:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      10133: # set toplevel url
1.271     www      10134:     my $topurl=$url;
                   10135:     unless ($nonstandard) {
                   10136: # ------------------------------------------ For standard courses, make top url
                   10137:         my $mapurl=&clutter($url);
1.278     www      10138:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 10139:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      10140: <map>
                   10141: <resource id="1" type="start"></resource>
                   10142: <resource id="2" src="$mapurl"></resource>
                   10143: <resource id="3" type="finish"></resource>
                   10144: <link index="1" from="1" to="2"></link>
                   10145: <link index="2" from="2" to="3"></link>
                   10146: </map>
                   10147: ENDINITMAP
                   10148:         $topurl=&declutter(
1.638     albertel 10149:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      10150:                           );
                   10151:     }
                   10152: # ----------------------------------------------------------- Write preferences
1.84      www      10153:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  10154:                      ('description'              => $description,
                   10155:                       'url'                      => $topurl,
                   10156:                       'internal.creator'         => $env{'user.name'}.':'.
                   10157:                                                     $env{'user.domain'},
                   10158:                       'internal.created'         => $now,
                   10159:                       'internal.creationcontext' => $context)
                   10160:                     );
1.84      www      10161:     return '/'.$udom.'/'.$uname;
                   10162: }
                   10163: 
1.1011    raeburn  10164: # ------------------------------------------------------------------- Create ID
                   10165: sub generate_coursenum {
1.1038    raeburn  10166:     my ($udom,$crstype) = @_;
1.1011    raeburn  10167:     my $domdesc = &domain($udom);
                   10168:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  10169:     my $first;
                   10170:     if ($crstype eq 'Community') {
                   10171:         $first = '0';
                   10172:     } else {
                   10173:         $first = int(1+rand(9)); 
                   10174:     } 
                   10175:     my $uname=$first.
1.1011    raeburn  10176:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10177:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10178:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10179: # ----------------------------------------------- Make sure that does not exist
                   10180:     my $uhome=&homeserver($uname,$udom,'true');
                   10181:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  10182:         if ($crstype eq 'Community') {
                   10183:             $first = '0';
                   10184:         } else {
                   10185:             $first = int(1+rand(9));
                   10186:         }
                   10187:         $uname=$first.
1.1011    raeburn  10188:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10189:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10190:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10191:         $uhome=&homeserver($uname,$udom,'true');
                   10192:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   10193:             return 'error: unable to generate unique course-ID';
                   10194:         }
                   10195:     }
                   10196:     return $uname;
                   10197: }
                   10198: 
1.813     albertel 10199: sub is_course {
1.1167    droeschl 10200:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   10201:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
1.1172.2.95  raeburn  10202:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   10203:     my $uhome=&homeserver($cnum,$cdom);
                   10204:     my $iscourse;
                   10205:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   10206:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
                   10207:     } else {
                   10208:         my $hashid = $cdom.':'.$cnum;
                   10209:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   10210:         unless (defined($cached)) {
                   10211:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   10212:                                         $cnum,undef,undef,'.');
                   10213:             $iscourse = 0;
                   10214:             if (exists($courses{$cdom.'_'.$cnum})) {
                   10215:                 $iscourse = 1;
                   10216:             }
                   10217:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   10218:         }
                   10219:     }
                   10220:     return unless($iscourse);
1.1167    droeschl 10221:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 10222: }
                   10223: 
1.1015    raeburn  10224: sub store_userdata {
                   10225:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  10226:     my $result;
1.1016    raeburn  10227:     if ($datakey ne '') {
1.1013    raeburn  10228:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  10229:             if ($udom eq '' || $uname eq '') {
                   10230:                 $udom = $env{'user.domain'};
                   10231:                 $uname = $env{'user.name'};
                   10232:             }
                   10233:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  10234:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   10235:                 $result = 'error: no_host';
                   10236:             } else {
                   10237:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   10238:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   10239: 
                   10240:                 my $namevalue='';
                   10241:                 foreach my $key (keys(%{$storehash})) {
                   10242:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   10243:                 }
                   10244:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  10245:                 unless ($namespace eq 'courserequests') {
                   10246:                     $datakey = &escape($datakey);
                   10247:                 }
1.1105    raeburn  10248:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   10249:                                   $namevalue,$uhome);
1.1013    raeburn  10250:             }
                   10251:         } else {
                   10252:             $result = 'error: data to store was not a hash reference'; 
                   10253:         }
                   10254:     } else {
                   10255:         $result= 'error: invalid requestkey'; 
                   10256:     }
                   10257:     return $result;
                   10258: }
                   10259: 
1.21      www      10260: # ---------------------------------------------------------- Assign Custom Role
                   10261: 
                   10262: sub assigncustomrole {
1.957     raeburn  10263:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10264:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  10265:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      10266: }
                   10267: 
                   10268: # ----------------------------------------------------------------- Revoke Role
                   10269: 
                   10270: sub revokerole {
1.957     raeburn  10271:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10272:     my $now=time;
1.965     raeburn  10273:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      10274: }
                   10275: 
                   10276: # ---------------------------------------------------------- Revoke Custom Role
                   10277: 
                   10278: sub revokecustomrole {
1.957     raeburn  10279:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10280:     my $now=time;
1.357     www      10281:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  10282:            $deleteflag,$selfenroll,$context);
1.17      www      10283: }
                   10284: 
1.533     banghart 10285: # ------------------------------------------------------------ Disk usage
1.535     albertel 10286: sub diskusage {
1.955     raeburn  10287:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   10288:     $directorypath =~ s/\/$//;
                   10289:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   10290:                        .&escape($getpropath).':'.&escape($uname).':'
                   10291:                        .&escape($udom),homeserver($uname,$udom));
                   10292:     if ($listing eq 'unknown_cmd') {
                   10293:         if ($getpropath) {
                   10294:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   10295:         }
                   10296:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   10297:     }
1.514     albertel 10298:     return $listing;
1.512     banghart 10299: }
                   10300: 
1.566     banghart 10301: sub is_locked {
1.1096    raeburn  10302:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 10303:     my @check;
                   10304:     my $is_locked;
1.1093    raeburn  10305:     push (@check,$file_name);
1.613     albertel 10306:     my %locked = &get('file_permissions',\@check,
1.620     albertel 10307: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 10308:     my ($tmp)=keys(%locked);
                   10309:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  10310:     
1.566     banghart 10311:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  10312:         $is_locked = 'false';
                   10313:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  10314:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  10315:                $is_locked = 'true';
1.1096    raeburn  10316:                if (ref($which) eq 'ARRAY') {
                   10317:                    push(@{$which},$entry);
                   10318:                } else {
                   10319:                    last;
                   10320:                }
1.745     raeburn  10321:            }
                   10322:        }
1.566     banghart 10323:     } else {
                   10324:         $is_locked = 'false';
                   10325:     }
1.1093    raeburn  10326:     return $is_locked;
1.566     banghart 10327: }
                   10328: 
1.759     albertel 10329: sub declutter_portfile {
                   10330:     my ($file) = @_;
1.833     albertel 10331:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 10332:     return $file;
                   10333: }
                   10334: 
1.559     banghart 10335: # ------------------------------------------------------------- Mark as Read Only
                   10336: 
                   10337: sub mark_as_readonly {
                   10338:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 10339:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10340:     my ($tmp)=keys(%current_permissions);
                   10341:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 10342:     foreach my $file (@{$files}) {
1.759     albertel 10343: 	$file = &declutter_portfile($file);
1.561     banghart 10344:         push(@{$current_permissions{$file}},$what);
1.559     banghart 10345:     }
1.613     albertel 10346:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10347:     return;
                   10348: }
                   10349: 
1.572     banghart 10350: # ------------------------------------------------------------Save Selected Files
                   10351: 
                   10352: sub save_selected_files {
                   10353:     my ($user, $path, @files) = @_;
                   10354:     my $filename = $user."savedfiles";
1.573     banghart 10355:     my @other_files = &files_not_in_path($user, $path);
1.1172.2.96  raeburn  10356:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 10357:     foreach my $file (@files) {
1.620     albertel 10358:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 10359:     }
                   10360:     foreach my $file (@other_files) {
1.574     banghart 10361:         print (OUT $file."\n");
1.572     banghart 10362:     }
1.574     banghart 10363:     close (OUT);
1.572     banghart 10364:     return 'ok';
                   10365: }
                   10366: 
1.574     banghart 10367: sub clear_selected_files {
                   10368:     my ($user) = @_;
                   10369:     my $filename = $user."savedfiles";
1.1172.2.96  raeburn  10370:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 10371:     print (OUT undef);
                   10372:     close (OUT);
                   10373:     return ("ok");    
                   10374: }
                   10375: 
1.572     banghart 10376: sub files_in_path {
                   10377:     my ($user, $path) = @_;
                   10378:     my $filename = $user."savedfiles";
                   10379:     my %return_files;
1.1172.2.96  raeburn  10380:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 10381:     while (my $line_in = <IN>) {
1.574     banghart 10382:         chomp ($line_in);
                   10383:         my @paths_and_file = split (m!/!, $line_in);
                   10384:         my $file_part = pop (@paths_and_file);
                   10385:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 10386:         $path_part.='/';
                   10387:         my $path_and_file = $path_part.$file_part;
                   10388:         if ($path_part eq $path) {
                   10389:             $return_files{$file_part}= 'selected';
                   10390:         }
                   10391:     }
1.574     banghart 10392:     close (IN);
                   10393:     return (\%return_files);
1.572     banghart 10394: }
                   10395: 
                   10396: # called in portfolio select mode, to show files selected NOT in current directory
                   10397: sub files_not_in_path {
                   10398:     my ($user, $path) = @_;
                   10399:     my $filename = $user."savedfiles";
                   10400:     my @return_files;
                   10401:     my $path_part;
1.1172.2.96  raeburn  10402:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 10403:     while (my $line = <IN>) {
1.572     banghart 10404:         #ok, I know it's clunky, but I want it to work
1.800     albertel 10405:         my @paths_and_file = split(m|/|, $line);
                   10406:         my $file_part = pop(@paths_and_file);
                   10407:         chomp($file_part);
                   10408:         my $path_part = join('/', @paths_and_file);
1.572     banghart 10409:         $path_part .= '/';
                   10410:         my $path_and_file = $path_part.$file_part;
                   10411:         if ($path_part ne $path) {
1.800     albertel 10412:             push(@return_files, ($path_and_file));
1.572     banghart 10413:         }
                   10414:     }
1.800     albertel 10415:     close(OUT);
1.574     banghart 10416:     return (@return_files);
1.572     banghart 10417: }
                   10418: 
1.745     raeburn  10419: #----------------------------------------------Get portfolio file permissions
1.629     banghart 10420: 
1.745     raeburn  10421: sub get_portfile_permissions {
                   10422:     my ($domain,$user) = @_;
1.613     albertel 10423:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10424:     my ($tmp)=keys(%current_permissions);
                   10425:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10426:     return \%current_permissions;
                   10427: }
                   10428: 
                   10429: #---------------------------------------------Get portfolio file access controls
                   10430: 
1.749     raeburn  10431: sub get_access_controls {
1.745     raeburn  10432:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 10433:     my %access;
                   10434:     my $real_file = $file;
                   10435:     $file =~ s/\.meta$//;
1.745     raeburn  10436:     if (defined($file)) {
1.749     raeburn  10437:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   10438:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 10439:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  10440:             }
                   10441:         }
1.745     raeburn  10442:     } else {
1.749     raeburn  10443:         foreach my $key (keys(%{$current_permissions})) {
                   10444:             if ($key =~ /\0accesscontrol$/) {
                   10445:                 if (defined($group)) {
                   10446:                     if ($key !~ m-^\Q$group\E/-) {
                   10447:                         next;
                   10448:                     }
                   10449:                 }
                   10450:                 my ($fullpath) = split(/\0/,$key);
                   10451:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   10452:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   10453:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   10454:                     }
                   10455:                 }
                   10456:             }
                   10457:         }
                   10458:     }
                   10459:     return %access;
                   10460: }
                   10461: 
                   10462: sub modify_access_controls {
                   10463:     my ($file_name,$changes,$domain,$user)=@_;
                   10464:     my ($outcome,$deloutcome);
                   10465:     my %store_permissions;
                   10466:     my %new_values;
                   10467:     my %new_control;
                   10468:     my %translation;
                   10469:     my @deletions = ();
                   10470:     my $now = time;
                   10471:     if (exists($$changes{'activate'})) {
                   10472:         if (ref($$changes{'activate'}) eq 'HASH') {
                   10473:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   10474:             my $numnew = scalar(@newitems);
                   10475:             for (my $i=0; $i<$numnew; $i++) {
                   10476:                 my $newkey = $newitems[$i];
                   10477:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  10478:                 if ($newkey =~ /^\d+:/) { 
                   10479:                     $newkey =~ s/^(\d+)/$newid/;
                   10480:                     $translation{$1} = $newid;
                   10481:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   10482:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   10483:                     $translation{$1} = $newid;
                   10484:                 }
1.749     raeburn  10485:                 $new_values{$file_name."\0".$newkey} = 
                   10486:                                           $$changes{'activate'}{$newitems[$i]};
                   10487:                 $new_control{$newkey} = $now;
                   10488:             }
                   10489:         }
                   10490:     }
                   10491:     my %todelete;
                   10492:     my %changed_items;
                   10493:     foreach my $action ('delete','update') {
                   10494:         if (exists($$changes{$action})) {
                   10495:             if (ref($$changes{$action}) eq 'HASH') {
                   10496:                 foreach my $key (keys(%{$$changes{$action}})) {
                   10497:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   10498:                     if ($action eq 'delete') { 
                   10499:                         $todelete{$itemnum} = 1;
                   10500:                     } else {
                   10501:                         $changed_items{$itemnum} = $key;
                   10502:                     }
                   10503:                 }
1.745     raeburn  10504:             }
                   10505:         }
1.749     raeburn  10506:     }
                   10507:     # get lock on access controls for file.
                   10508:     my $lockhash = {
                   10509:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   10510:                                                        ':'.$env{'user.domain'},
                   10511:                    }; 
                   10512:     my $tries = 0;
                   10513:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10514:    
1.1172.2.79  raeburn  10515:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  10516:         $tries ++;
1.1172.2.79  raeburn  10517:         sleep(0.1);
1.749     raeburn  10518:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10519:     }
                   10520:     if ($gotlock eq 'ok') {
                   10521:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   10522:         my ($tmp)=keys(%curr_permissions);
                   10523:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   10524:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   10525:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   10526:             if (ref($curr_controls) eq 'HASH') {
                   10527:                 foreach my $control_item (keys(%{$curr_controls})) {
                   10528:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   10529:                     if (defined($todelete{$itemnum})) {
                   10530:                         push(@deletions,$file_name."\0".$control_item);
                   10531:                     } else {
                   10532:                         if (defined($changed_items{$itemnum})) {
                   10533:                             $new_control{$changed_items{$itemnum}} = $now;
                   10534:                             push(@deletions,$file_name."\0".$control_item);
                   10535:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   10536:                         } else {
                   10537:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   10538:                         }
                   10539:                     }
1.745     raeburn  10540:                 }
                   10541:             }
                   10542:         }
1.970     raeburn  10543:         my ($group);
                   10544:         if (&is_course($domain,$user)) {
                   10545:             ($group,my $file) = split(/\//,$file_name,2);
                   10546:         }
1.749     raeburn  10547:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   10548:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   10549:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   10550:         #  remove lock
                   10551:         my @del_lock = ($file_name."\0".'locked_access_records');
                   10552:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  10553:         my $sqlresult =
1.970     raeburn  10554:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  10555:                                     $group);
1.749     raeburn  10556:     } else {
                   10557:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  10558:     }
1.749     raeburn  10559:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  10560: }
                   10561: 
1.827     raeburn  10562: sub make_public_indefinitely {
                   10563:     my ($requrl) = @_;
                   10564:     my $now = time;
                   10565:     my $action = 'activate';
                   10566:     my $aclnum = 0;
                   10567:     if (&is_portfolio_url($requrl)) {
                   10568:         my (undef,$udom,$unum,$file_name,$group) =
                   10569:             &parse_portfolio_url($requrl);
                   10570:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   10571:         my %access_controls = &get_access_controls($current_perms,
                   10572:                                                    $group,$file_name);
                   10573:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   10574:             my ($num,$scope,$end,$start) = 
                   10575:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   10576:             if ($scope eq 'public') {
                   10577:                 if ($start <= $now && $end == 0) {
                   10578:                     $action = 'none';
                   10579:                 } else {
                   10580:                     $action = 'update';
                   10581:                     $aclnum = $num;
                   10582:                 }
                   10583:                 last;
                   10584:             }
                   10585:         }
                   10586:         if ($action eq 'none') {
                   10587:              return 'ok';
                   10588:         } else {
                   10589:             my %changes;
                   10590:             my $newend = 0;
                   10591:             my $newstart = $now;
                   10592:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   10593:             $changes{$action}{$newkey} = {
                   10594:                 type => 'public',
                   10595:                 time => {
                   10596:                     start => $newstart,
                   10597:                     end   => $newend,
                   10598:                 },
                   10599:             };
                   10600:             my ($outcome,$deloutcome,$new_values,$translation) =
                   10601:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   10602:             return $outcome;
                   10603:         }
                   10604:     } else {
                   10605:         return 'invalid';
                   10606:     }
                   10607: }
                   10608: 
1.745     raeburn  10609: #------------------------------------------------------Get Marked as Read Only
                   10610: 
                   10611: sub get_marked_as_readonly {
                   10612:     my ($domain,$user,$what,$group) = @_;
                   10613:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 10614:     my @readonly_files;
1.629     banghart 10615:     my $cmp1=$what;
                   10616:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  10617:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10618:         if (defined($group)) {
                   10619:             if ($file_name !~ m-^\Q$group\E/-) {
                   10620:                 next;
                   10621:             }
                   10622:         }
1.561     banghart 10623:         if (ref($value) eq "ARRAY"){
                   10624:             foreach my $stored_what (@{$value}) {
1.629     banghart 10625:                 my $cmp2=$stored_what;
1.759     albertel 10626:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  10627:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  10628:                 }
1.629     banghart 10629:                 if ($cmp1 eq $cmp2) {
1.561     banghart 10630:                     push(@readonly_files, $file_name);
1.745     raeburn  10631:                     last;
1.563     banghart 10632:                 } elsif (!defined($what)) {
                   10633:                     push(@readonly_files, $file_name);
1.745     raeburn  10634:                     last;
1.561     banghart 10635:                 }
                   10636:             }
1.745     raeburn  10637:         }
1.561     banghart 10638:     }
                   10639:     return @readonly_files;
                   10640: }
1.577     banghart 10641: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 10642: 
1.577     banghart 10643: sub get_marked_as_readonly_hash {
1.745     raeburn  10644:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 10645:     my %readonly_files;
1.745     raeburn  10646:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10647:         if (defined($group)) {
                   10648:             if ($file_name !~ m-^\Q$group\E/-) {
                   10649:                 next;
                   10650:             }
                   10651:         }
1.577     banghart 10652:         if (ref($value) eq "ARRAY"){
                   10653:             foreach my $stored_what (@{$value}) {
1.745     raeburn  10654:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 10655:                     foreach my $lock_descriptor(@{$stored_what}) {
                   10656:                         if ($lock_descriptor eq 'graded') {
                   10657:                             $readonly_files{$file_name} = 'graded';
                   10658:                         } elsif ($lock_descriptor eq 'handback') {
                   10659:                             $readonly_files{$file_name} = 'handback';
                   10660:                         } else {
                   10661:                             if (!exists($readonly_files{$file_name})) {
                   10662:                                 $readonly_files{$file_name} = 'locked';
                   10663:                             }
                   10664:                         }
1.745     raeburn  10665:                     }
1.750     banghart 10666:                 } 
1.577     banghart 10667:             }
                   10668:         } 
                   10669:     }
                   10670:     return %readonly_files;
                   10671: }
1.559     banghart 10672: # ------------------------------------------------------------ Unmark as Read Only
                   10673: 
                   10674: sub unmark_as_readonly {
1.629     banghart 10675:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   10676:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  10677:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 10678:     $file_name = &declutter_portfile($file_name);
1.634     albertel 10679:     my $symb_crs = $what;
                   10680:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  10681:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 10682:     my ($tmp)=keys(%current_permissions);
                   10683:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10684:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 10685:     foreach my $file (@readonly_files) {
1.759     albertel 10686: 	my $clean_file = &declutter_portfile($file);
                   10687: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 10688: 	my $current_locks = $current_permissions{$file};
1.563     banghart 10689:         my @new_locks;
                   10690:         my @del_keys;
                   10691:         if (ref($current_locks) eq "ARRAY"){
                   10692:             foreach my $locker (@{$current_locks}) {
1.632     albertel 10693:                 my $compare=$locker;
1.749     raeburn  10694:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  10695:                     $compare=join('',@{$locker});
1.746     raeburn  10696:                     if ($compare ne $symb_crs) {
                   10697:                         push(@new_locks, $locker);
                   10698:                     }
1.563     banghart 10699:                 }
                   10700:             }
1.650     albertel 10701:             if (scalar(@new_locks) > 0) {
1.563     banghart 10702:                 $current_permissions{$file} = \@new_locks;
                   10703:             } else {
                   10704:                 push(@del_keys, $file);
1.613     albertel 10705:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 10706:                 delete($current_permissions{$file});
1.563     banghart 10707:             }
                   10708:         }
1.561     banghart 10709:     }
1.613     albertel 10710:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10711:     return;
                   10712: }
1.512     banghart 10713: 
1.17      www      10714: # ------------------------------------------------------------ Directory lister
                   10715: 
                   10716: sub dirlist {
1.955     raeburn  10717:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      10718:     $uri=~s/^\///;
                   10719:     $uri=~s/\/$//;
1.253     stredwic 10720:     my ($udom, $uname);
1.955     raeburn  10721:     if ($getuserdir) {
1.253     stredwic 10722:         $udom = $userdomain;
                   10723:         $uname = $username;
1.955     raeburn  10724:     } else {
                   10725:         (undef,$udom,$uname)=split(/\//,$uri);
                   10726:         if(defined($userdomain)) {
                   10727:             $udom = $userdomain;
                   10728:         }
                   10729:         if(defined($username)) {
                   10730:             $uname = $username;
                   10731:         }
1.253     stredwic 10732:     }
1.955     raeburn  10733:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 10734: 
1.955     raeburn  10735:     $dirRoot = $perlvar{'lonDocRoot'};
                   10736:     if (defined($getpropath)) {
                   10737:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 10738:         $dirRoot =~ s/\/$//;
1.955     raeburn  10739:     } elsif (defined($getuserdir)) {
                   10740:         my $subdir=$uname.'__';
                   10741:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   10742:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   10743:                    ."/$udom/$subdir/$uname";
                   10744:     } elsif (defined($alternateRoot)) {
                   10745:         $dirRoot = $alternateRoot;
1.751     banghart 10746:     }
1.253     stredwic 10747: 
                   10748:     if($udom) {
                   10749:         if($uname) {
1.1135    raeburn  10750:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  10751:             if ($uhome eq 'no_host') {
                   10752:                 return ([],'no_host');
                   10753:             }
1.955     raeburn  10754:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  10755:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  10756:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  10757:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10758:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  10759:             } else {
                   10760:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10761:             }
1.605     matthew  10762:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10763:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  10764:                 @listing_results = split(/:/,$listing);
                   10765:             } else {
                   10766:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10767:             }
1.1135    raeburn  10768:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  10769:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10770:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10771:                 return ([],$listing);
                   10772:             } else {
                   10773:                 return (\@listing_results);
1.1135    raeburn  10774:             }
1.955     raeburn  10775:         } elsif(!$alternateRoot) {
1.1136    raeburn  10776:             my (%allusers,%listerror);
1.841     albertel 10777: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  10778:  	    foreach my $tryserver (keys(%servers)) {
                   10779:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   10780:                                   &escape($udom),$tryserver);
                   10781:                 if ($listing eq 'unknown_cmd') {
                   10782: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10783: 				      $udom, $tryserver);
                   10784:                 } else {
                   10785:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10786:                 }
1.841     albertel 10787: 		if ($listing eq 'unknown_cmd') {
                   10788: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10789: 				      $udom, $tryserver);
                   10790: 		    @listing_results = split(/:/,$listing);
                   10791: 		} else {
                   10792: 		    @listing_results =
                   10793: 			map { &unescape($_); } split(/:/,$listing);
                   10794: 		}
1.1136    raeburn  10795:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   10796:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10797:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10798:                     $listerror{$tryserver} = $listing;
                   10799:                 } else {
1.841     albertel 10800: 		    foreach my $line (@listing_results) {
                   10801: 			my ($entry) = split(/&/,$line,2);
                   10802: 			$allusers{$entry} = 1;
                   10803: 		    }
                   10804: 		}
1.253     stredwic 10805:             }
1.1136    raeburn  10806:             my @alluserslist=();
1.800     albertel 10807:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  10808:                 push(@alluserslist,$user.'&user');
1.253     stredwic 10809:             }
1.1172.2.80  raeburn  10810:             if (!%listerror) {
                   10811:                 # no errors
                   10812:                 return (\@alluserslist);
                   10813:             } elsif (scalar(keys(%servers)) == 1) {
                   10814:                 # one library server, one error
                   10815:                 my ($key) = keys(%listerror);
                   10816:                 return (\@alluserslist, $listerror{$key});
                   10817:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   10818:                 # con_lost indicates that we might miss data from at least one
                   10819:                 # library server
                   10820:                 return (\@alluserslist, 'con_lost');
                   10821:             } else {
                   10822:                 # multiple library servers and no con_lost -> data should be
                   10823:                 # complete.
                   10824:                 return (\@alluserslist);
                   10825:             }
                   10826: 
1.253     stredwic 10827:         } else {
1.1136    raeburn  10828:             return ([],'missing username');
1.253     stredwic 10829:         }
1.955     raeburn  10830:     } elsif(!defined($getpropath)) {
1.1136    raeburn  10831:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   10832:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   10833:         return (\@all_domains);
1.955     raeburn  10834:     } else {
1.1136    raeburn  10835:         return ([],'missing domain');
1.275     stredwic 10836:     }
                   10837: }
                   10838: 
                   10839: # --------------------------------------------- GetFileTimestamp
                   10840: # This function utilizes dirlist and returns the date stamp for
                   10841: # when it was last modified.  It will also return an error of -1
                   10842: # if an error occurs
                   10843: 
                   10844: sub GetFileTimestamp {
1.955     raeburn  10845:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 10846:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   10847:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  10848:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   10849:                                     undef,$getuserdir);
                   10850:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10851:         return -1;
                   10852:     }
                   10853:     if (ref($fileref) eq 'ARRAY') {
                   10854:         my @stats = split('&',$fileref->[0]);
1.375     matthew  10855:         # @stats contains first the filename, then the stat output
                   10856:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 10857:     } else {
                   10858:         return -1;
1.253     stredwic 10859:     }
1.26      www      10860: }
                   10861: 
1.712     albertel 10862: sub stat_file {
                   10863:     my ($uri) = @_;
1.787     albertel 10864:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 10865: 
1.955     raeburn  10866:     my ($udom,$uname,$file);
1.712     albertel 10867:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   10868: 	($udom,$uname,$file) =
1.811     albertel 10869: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 10870: 	$file = 'userfiles/'.$file;
                   10871:     }
                   10872:     if ($uri =~ m-^/res/-) {
                   10873: 	($udom,$uname) = 
1.807     albertel 10874: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 10875: 	$file = $uri;
                   10876:     }
                   10877: 
                   10878:     if (!$udom || !$uname || !$file) {
                   10879: 	# unable to handle the uri
                   10880: 	return ();
                   10881:     }
1.956     raeburn  10882:     my $getpropath;
                   10883:     if ($file =~ /^userfiles\//) {
                   10884:         $getpropath = 1;
                   10885:     }
1.1136    raeburn  10886:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   10887:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10888:         return ();
                   10889:     } else {
                   10890:         if (ref($listref) eq 'ARRAY') {
                   10891:             my @stats = split('&',$listref->[0]);
                   10892: 	    shift(@stats); #filename is first
                   10893: 	    return @stats;
                   10894:         }
1.712     albertel 10895:     }
                   10896:     return ();
                   10897: }
                   10898: 
1.26      www      10899: # -------------------------------------------------------- Value of a Condition
                   10900: 
1.713     albertel 10901: # gets the value of a specific preevaluated condition
                   10902: #    stored in the string  $env{user.state.<cid>}
                   10903: # or looks up a condition reference in the bighash and if if hasn't
                   10904: # already been evaluated recurses into docondval to get the value of
                   10905: # the condition, then memoizing it to 
                   10906: #   $env{user.state.<cid>.<condition>}
1.40      www      10907: sub directcondval {
                   10908:     my $number=shift;
1.620     albertel 10909:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 10910: 	&Apache::lonuserstate::evalstate();
                   10911:     }
1.713     albertel 10912:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   10913: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   10914:     } elsif ($number =~ /^_/) {
                   10915: 	my $sub_condition;
                   10916: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10917: 		&GDBM_READER(),0640)) {
                   10918: 	    $sub_condition=$bighash{'conditions'.$number};
                   10919: 	    untie(%bighash);
                   10920: 	}
                   10921: 	my $value = &docondval($sub_condition);
1.949     raeburn  10922: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 10923: 	return $value;
                   10924:     }
1.620     albertel 10925:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   10926:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      10927:     } else {
                   10928:        return 2;
                   10929:     }
                   10930: }
                   10931: 
1.713     albertel 10932: # get the collection of conditions for this resource
1.26      www      10933: sub condval {
                   10934:     my $condidx=shift;
1.54      www      10935:     my $allpathcond='';
1.713     albertel 10936:     foreach my $cond (split(/\|/,$condidx)) {
                   10937: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   10938: 	    $allpathcond.=
                   10939: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   10940: 	}
1.191     harris41 10941:     }
1.54      www      10942:     $allpathcond=~s/\|$//;
1.713     albertel 10943:     return &docondval($allpathcond);
                   10944: }
                   10945: 
                   10946: #evaluates an expression of conditions
                   10947: sub docondval {
                   10948:     my ($allpathcond) = @_;
                   10949:     my $result=0;
                   10950:     if ($env{'request.course.id'}
                   10951: 	&& defined($allpathcond)) {
                   10952: 	my $operand='|';
                   10953: 	my @stack;
                   10954: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   10955: 	    if ($chunk eq '(') {
                   10956: 		push @stack,($operand,$result);
                   10957: 	    } elsif ($chunk eq ')') {
                   10958: 		my $before=pop @stack;
                   10959: 		if (pop @stack eq '&') {
                   10960: 		    $result=$result>$before?$before:$result;
                   10961: 		} else {
                   10962: 		    $result=$result>$before?$result:$before;
                   10963: 		}
                   10964: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   10965: 		$operand=$chunk;
                   10966: 	    } else {
                   10967: 		my $new=directcondval($chunk);
                   10968: 		if ($operand eq '&') {
                   10969: 		    $result=$result>$new?$new:$result;
                   10970: 		} else {
                   10971: 		    $result=$result>$new?$result:$new;
                   10972: 		}
                   10973: 	    }
                   10974: 	}
1.26      www      10975:     }
                   10976:     return $result;
1.421     albertel 10977: }
                   10978: 
                   10979: # ---------------------------------------------------- Devalidate courseresdata
                   10980: 
                   10981: sub devalidatecourseresdata {
                   10982:     my ($coursenum,$coursedomain)=@_;
                   10983:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10984:     &devalidate_cache_new('courseres',$hashid);
1.28      www      10985: }
                   10986: 
1.763     www      10987: 
1.200     www      10988: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     10989: #
                   10990: #  Parameters:
                   10991: #      $coursenum    - Number of the course.
                   10992: #      $coursedomain - Domain at which the course was created.
                   10993: #  Returns:
                   10994: #     A hash of the course parameters along (I think) with timestamps
                   10995: #     and version info.
1.877     foxr     10996: 
1.624     albertel 10997: sub get_courseresdata {
                   10998:     my ($coursenum,$coursedomain)=@_;
1.200     www      10999:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   11000:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11001:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 11002:     my %dumpreply;
1.417     albertel 11003:     unless (defined($cached)) {
1.624     albertel 11004: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 11005: 	$result=\%dumpreply;
1.251     albertel 11006: 	my ($tmp) = keys(%dumpreply);
                   11007: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 11008: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 11009: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   11010: 	    return $tmp;
1.416     albertel 11011: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 11012: 	    $result=undef;
1.599     albertel 11013: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 11014: 	}
                   11015:     }
1.624     albertel 11016:     return $result;
                   11017: }
                   11018: 
1.633     albertel 11019: sub devalidateuserresdata {
                   11020:     my ($uname,$udom)=@_;
                   11021:     my $hashid="$udom:$uname";
                   11022:     &devalidate_cache_new('userres',$hashid);
                   11023: }
                   11024: 
1.624     albertel 11025: sub get_userresdata {
                   11026:     my ($uname,$udom)=@_;
                   11027:     #most student don\'t have any data set, check if there is some data
                   11028:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   11029: 
                   11030:     my $hashid="$udom:$uname";
                   11031:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   11032:     if (!defined($cached)) {
                   11033: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   11034: 	$result=\%resourcedata;
                   11035: 	&do_cache_new('userres',$hashid,$result,600);
                   11036:     }
                   11037:     my ($tmp)=keys(%$result);
                   11038:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   11039: 	return $result;
                   11040:     }
                   11041:     #error 2 occurs when the .db doesn't exist
                   11042:     if ($tmp!~/error: 2 /) {
1.1172.2.71  raeburn  11043:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   11044: 	    &logthis("<font color=\"blue\">WARNING:".
                   11045: 		     " Trying to get resource data for ".
                   11046: 		     $uname." at ".$udom.": ".
                   11047: 		     $tmp."</font>");
                   11048:         }
1.624     albertel 11049:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 11050: 	#&EXT_cache_set($udom,$uname);
                   11051: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 11052: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 11053:     }
                   11054:     return $tmp;
                   11055: }
1.879     foxr     11056: #----------------------------------------------- resdata - return resource data
                   11057: #  Purpose:
                   11058: #    Return resource data for either users or for a course.
                   11059: #  Parameters:
                   11060: #     $name      - Course/user name.
                   11061: #     $domain    - Name of the domain the user/course is registered on.
                   11062: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   11063: #     @which     - Array of names of resources desired.
                   11064: #  Returns:
                   11065: #     The value of the first reasource in @which that is found in the
                   11066: #     resource hash.
                   11067: #  Exceptional Conditions:
                   11068: #     If the $type passed in is not valid (not the string 'course' or 
                   11069: #     'user', an undefined  reference is returned.
                   11070: #     If none of the resources are found, an undef is returned
1.624     albertel 11071: sub resdata {
                   11072:     my ($name,$domain,$type,@which)=@_;
                   11073:     my $result;
                   11074:     if ($type eq 'course') {
                   11075: 	$result=&get_courseresdata($name,$domain);
                   11076:     } elsif ($type eq 'user') {
                   11077: 	$result=&get_userresdata($name,$domain);
                   11078:     }
                   11079:     if (!ref($result)) { return $result; }    
1.251     albertel 11080:     foreach my $item (@which) {
1.927     albertel 11081: 	if (defined($result->{$item->[0]})) {
                   11082: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 11083: 	}
1.250     albertel 11084:     }
1.291     albertel 11085:     return undef;
1.200     www      11086: }
                   11087: 
1.1172.2.31  raeburn  11088: sub get_numsuppfiles {
                   11089:     my ($cnum,$cdom,$ignorecache)=@_;
                   11090:     my $hashid=$cnum.':'.$cdom;
                   11091:     my ($suppcount,$cached);
                   11092:     unless ($ignorecache) {
                   11093:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   11094:     }
                   11095:     unless (defined($cached)) {
                   11096:         my $chome=&homeserver($cnum,$cdom);
                   11097:         unless ($chome eq 'no_host') {
                   11098:             ($suppcount,my $errors) = (0,0);
                   11099:             my $suppmap = 'supplemental.sequence';
                   11100:             ($suppcount,$errors) =
                   11101:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   11102:         }
                   11103:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   11104:     }
                   11105:     return $suppcount;
                   11106: }
                   11107: 
1.379     matthew  11108: #
                   11109: # EXT resource caching routines
                   11110: #
                   11111: 
                   11112: sub clear_EXT_cache_status {
1.383     albertel 11113:     &delenv('cache.EXT.');
1.379     matthew  11114: }
                   11115: 
                   11116: sub EXT_cache_status {
                   11117:     my ($target_domain,$target_user) = @_;
1.383     albertel 11118:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 11119:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  11120:         # We know already the user has no data
                   11121:         return 1;
                   11122:     } else {
                   11123:         return 0;
                   11124:     }
                   11125: }
                   11126: 
                   11127: sub EXT_cache_set {
                   11128:     my ($target_domain,$target_user) = @_;
1.383     albertel 11129:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  11130:     #&appenv({$cachename => time});
1.379     matthew  11131: }
                   11132: 
1.28      www      11133: # --------------------------------------------------------- Value of a Variable
1.58      www      11134: sub EXT {
1.715     albertel 11135: 
1.1172.2.28  raeburn  11136:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      11137:     unless ($varname) { return ''; }
1.218     albertel 11138:     #get real user name/domain, courseid and symb
                   11139:     my $courseid;
1.359     albertel 11140:     my $publicuser;
1.427     www      11141:     if ($symbparm) {
                   11142: 	$symbparm=&get_symb_from_alias($symbparm);
                   11143:     }
1.218     albertel 11144:     if (!($uname && $udom)) {
1.790     albertel 11145:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 11146:       if (!$symbparm) {	$symbparm=$cursymb; }
                   11147:     } else {
1.620     albertel 11148: 	$courseid=$env{'request.course.id'};
1.218     albertel 11149:     }
1.48      www      11150:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   11151:     my $rest;
1.320     albertel 11152:     if (defined($therest[0])) {
1.48      www      11153:        $rest=join('.',@therest);
                   11154:     } else {
                   11155:        $rest='';
                   11156:     }
1.320     albertel 11157: 
1.57      www      11158:     my $qualifierrest=$qualifier;
                   11159:     if ($rest) { $qualifierrest.='.'.$rest; }
                   11160:     my $spacequalifierrest=$space;
                   11161:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      11162:     if ($realm eq 'user') {
1.48      www      11163: # --------------------------------------------------------------- user.resource
                   11164: 	if ($space eq 'resource') {
1.651     albertel 11165: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   11166: 		  || defined($Apache::lonhomework::parsing_a_task))
                   11167: 		 &&
1.744     albertel 11168: 		 ($symbparm eq &symbread()) ) {	
                   11169: 		# if we are in the middle of processing the resource the
                   11170: 		# get the value we are planning on committing
                   11171:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   11172:                     return $Apache::lonhomework::results{$qualifierrest};
                   11173:                 } else {
                   11174:                     return $Apache::lonhomework::history{$qualifierrest};
                   11175:                 }
1.335     albertel 11176: 	    } else {
1.359     albertel 11177: 		my %restored;
1.620     albertel 11178: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 11179: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   11180: 		} else {
                   11181: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   11182: 		}
1.335     albertel 11183: 		return $restored{$qualifierrest};
                   11184: 	    }
1.48      www      11185: # ----------------------------------------------------------------- user.access
                   11186:         } elsif ($space eq 'access') {
1.218     albertel 11187: 	    # FIXME - not supporting calls for a specific user
1.48      www      11188:             return &allowed($qualifier,$rest);
                   11189: # ------------------------------------------ user.preferences, user.environment
                   11190:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 11191: 	    if (($uname eq $env{'user.name'}) &&
                   11192: 		($udom eq $env{'user.domain'})) {
                   11193: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 11194: 	    } else {
1.359     albertel 11195: 		my %returnhash;
                   11196: 		if (!$publicuser) {
                   11197: 		    %returnhash=&userenvironment($udom,$uname,
                   11198: 						 $qualifierrest);
                   11199: 		}
1.218     albertel 11200: 		return $returnhash{$qualifierrest};
                   11201: 	    }
1.48      www      11202: # ----------------------------------------------------------------- user.course
                   11203:         } elsif ($space eq 'course') {
1.218     albertel 11204: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11205:             return $env{join('.',('request.course',$qualifier))};
1.48      www      11206: # ------------------------------------------------------------------- user.role
                   11207:         } elsif ($space eq 'role') {
1.218     albertel 11208: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11209:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      11210:             if ($qualifier eq 'value') {
                   11211: 		return $role;
                   11212:             } elsif ($qualifier eq 'extent') {
                   11213:                 return $where;
                   11214:             }
                   11215: # ----------------------------------------------------------------- user.domain
                   11216:         } elsif ($space eq 'domain') {
1.218     albertel 11217:             return $udom;
1.48      www      11218: # ------------------------------------------------------------------- user.name
                   11219:         } elsif ($space eq 'name') {
1.218     albertel 11220:             return $uname;
1.48      www      11221: # ---------------------------------------------------- Any other user namespace
1.29      www      11222:         } else {
1.359     albertel 11223: 	    my %reply;
                   11224: 	    if (!$publicuser) {
                   11225: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   11226: 	    }
                   11227: 	    return $reply{$qualifierrest};
1.48      www      11228:         }
1.236     www      11229:     } elsif ($realm eq 'query') {
                   11230: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 11231:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   11232: 						[$spacequalifierrest]);
1.620     albertel 11233: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      11234:    } elsif ($realm eq 'request') {
1.48      www      11235: # ------------------------------------------------------------- request.browser
                   11236:         if ($space eq 'browser') {
1.1145    bisitz   11237:             return $env{'browser.'.$qualifier};
1.57      www      11238: # ------------------------------------------------------------ request.filename
                   11239:         } else {
1.620     albertel 11240:             return $env{'request.'.$spacequalifierrest};
1.29      www      11241:         }
1.28      www      11242:     } elsif ($realm eq 'course') {
1.48      www      11243: # ---------------------------------------------------------- course.description
1.620     albertel 11244:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      11245:     } elsif ($realm eq 'resource') {
1.165     www      11246: 
1.620     albertel 11247: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 11248: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   11249: 	}
1.693     albertel 11250: 
1.1172.2.30  raeburn  11251:         if ($qualifier eq '') {
                   11252: 	    if ($space eq 'title') {
                   11253: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   11254: 	        return &gettitle($symbparm);
                   11255: 	    }
1.693     albertel 11256: 	
1.1172.2.30  raeburn  11257: 	    if ($space eq 'map') {
                   11258: 	        my ($map) = &decode_symb($symbparm);
                   11259: 	        return &symbread($map);
                   11260: 	    }
                   11261:             if ($space eq 'maptitle') {
                   11262:                 my ($map) = &decode_symb($symbparm);
                   11263:                 return &gettitle($map);
                   11264:             }
                   11265: 	    if ($space eq 'filename') {
                   11266: 	        if ($symbparm) {
                   11267: 		    return &clutter((&decode_symb($symbparm))[2]);
                   11268: 	        }
                   11269: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 11270: 	    }
1.1172.2.30  raeburn  11271: 
                   11272:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   11273:                 if ($space eq 'visibleparts') {
                   11274:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   11275:                     my $item;
                   11276:                     if (ref($navmap)) {
                   11277:                         my $res = $navmap->getBySymb($symbparm);
                   11278:                         my $parts = $res->parts();
                   11279:                         if (ref($parts) eq 'ARRAY') {
                   11280:                             $item = join(',',@{$parts});
                   11281:                         }
                   11282:                         undef($navmap);
                   11283:                     }
                   11284:                     return $item;
                   11285:                 }
                   11286:             }
                   11287:         }
1.693     albertel 11288: 
                   11289: 	my ($section, $group, @groups);
1.593     albertel 11290: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  11291:         if (($courseid eq '') && ($cid)) {
                   11292:             $courseid = $cid;
                   11293:         }
                   11294: 	if (($symbparm && $courseid) && 
                   11295: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      11296: 
1.218     albertel 11297: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      11298: 
1.60      www      11299: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 11300: 	    my $symbp=$symbparm;
1.735     albertel 11301: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 11302: 
                   11303: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   11304: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   11305: 
1.620     albertel 11306: 	    if (($env{'user.name'} eq $uname) &&
                   11307: 		($env{'user.domain'} eq $udom)) {
                   11308: 		$section=$env{'request.course.sec'};
1.733     raeburn  11309:                 @groups = split(/:/,$env{'request.course.groups'});  
                   11310:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 11311: 	    } else {
1.539     albertel 11312: 		if (! defined($usection)) {
1.551     albertel 11313: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 11314: 		} else {
                   11315: 		    $section = $usection;
                   11316: 		}
1.733     raeburn  11317:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 11318: 	    }
                   11319: 
                   11320: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   11321: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   11322: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   11323: 
1.593     albertel 11324: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 11325: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 11326: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      11327: 
1.60      www      11328: # ----------------------------------------------------------- first, check user
1.624     albertel 11329: 
                   11330: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 11331: 				       ([$courselevelr,'resource'],
                   11332: 					[$courselevelm,'map'     ],
                   11333: 					[$courselevel, 'course'  ]));
1.931     albertel 11334: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      11335: 
1.594     albertel 11336: # ------------------------------------------------ second, check some of course
1.684     raeburn  11337:             my $coursereply;
1.691     raeburn  11338:             if (@groups > 0) {
                   11339:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   11340:                                        $mapparm,$spacequalifierrest);
1.927     albertel 11341:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  11342:             }
1.96      www      11343: 
1.684     raeburn  11344: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 11345: 				  $env{'course.'.$courseid.'.domain'},
                   11346: 				  'course',
                   11347: 				  ([$seclevelr,   'resource'],
                   11348: 				   [$seclevelm,   'map'     ],
                   11349: 				   [$seclevel,    'course'  ],
                   11350: 				   [$courselevelr,'resource']));
                   11351: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      11352: 
1.60      www      11353: # ------------------------------------------------------ third, check map parms
1.218     albertel 11354: 	    my %parmhash=();
                   11355: 	    my $thisparm='';
                   11356: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 11357: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 11358: 		    &GDBM_READER(),0640)) {
1.218     albertel 11359: 		$thisparm=$parmhash{$symbparm};
                   11360: 		untie(%parmhash);
                   11361: 	    }
1.927     albertel 11362: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 11363: 	}
1.594     albertel 11364: # ------------------------------------------ fourth, look in resource metadata
1.71      www      11365: 
1.218     albertel 11366: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 11367: 	my $filename;
                   11368: 	if (!$symbparm) { $symbparm=&symbread(); }
                   11369: 	if ($symbparm) {
1.409     www      11370: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 11371: 	} else {
1.620     albertel 11372: 	    $filename=$env{'request.filename'};
1.282     albertel 11373: 	}
                   11374: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 11375: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 11376: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 11377: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      11378: 
1.927     albertel 11379: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 11380: 	if ($symbparm && defined($courseid) && 
1.620     albertel 11381: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 11382: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   11383: 				     $env{'course.'.$courseid.'.domain'},
                   11384: 				     'course',
1.927     albertel 11385: 				     ([$courselevelm,'map'   ],
                   11386: 				      [$courselevel, 'course']));
                   11387: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 11388: 	}
1.145     www      11389: # ------------------------------------------------------------------ Cascade up
1.218     albertel 11390: 	unless ($space eq '0') {
1.336     albertel 11391: 	    my @parts=split(/_/,$space);
                   11392: 	    my $id=pop(@parts);
                   11393: 	    my $part=join('_',@parts);
                   11394: 	    if ($part eq '') { $part='0'; }
1.927     albertel 11395: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 11396: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  11397: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 11398: 	}
1.395     albertel 11399: 	if ($recurse) { return undef; }
                   11400: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 11401: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      11402: # ---------------------------------------------------- Any other user namespace
                   11403:     } elsif ($realm eq 'environment') {
                   11404: # ----------------------------------------------------------------- environment
1.620     albertel 11405: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   11406: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 11407: 	} else {
1.770     albertel 11408: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   11409: 		return '';
                   11410: 	    }
1.219     albertel 11411: 	    my %returnhash=&userenvironment($udom,$uname,
                   11412: 					    $spacequalifierrest);
                   11413: 	    return $returnhash{$spacequalifierrest};
                   11414: 	}
1.28      www      11415:     } elsif ($realm eq 'system') {
1.48      www      11416: # ----------------------------------------------------------------- system.time
                   11417: 	if ($space eq 'time') {
                   11418: 	    return time;
                   11419:         }
1.696     albertel 11420:     } elsif ($realm eq 'server') {
                   11421: # ----------------------------------------------------------------- system.time
                   11422: 	if ($space eq 'name') {
                   11423: 	    return $ENV{'SERVER_NAME'};
                   11424:         }
1.28      www      11425:     }
1.48      www      11426:     return '';
1.61      www      11427: }
                   11428: 
1.927     albertel 11429: sub get_reply {
                   11430:     my ($reply_value) = @_;
1.940     raeburn  11431:     if (ref($reply_value) eq 'ARRAY') {
                   11432:         if (wantarray) {
                   11433: 	    return @$reply_value;
                   11434:         }
                   11435:         return $reply_value->[0];
                   11436:     } else {
                   11437:         return $reply_value;
1.927     albertel 11438:     }
                   11439: }
                   11440: 
1.691     raeburn  11441: sub check_group_parms {
                   11442:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   11443:     my @groupitems = ();
                   11444:     my $resultitem;
1.927     albertel 11445:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  11446:     foreach my $group (@{$groups}) {
                   11447:         foreach my $level (@levels) {
1.927     albertel 11448:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   11449:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  11450:         }
                   11451:     }
                   11452:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   11453:                             $env{'course.'.$courseid.'.domain'},
                   11454:                                      'course',@groupitems);
                   11455:     return $coursereply;
                   11456: }
                   11457: 
                   11458: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  11459:     my ($courseid,@groups) = @_;
                   11460:     @groups = sort(@groups);
1.691     raeburn  11461:     return @groups;
                   11462: }
                   11463: 
1.395     albertel 11464: sub packages_tab_default {
                   11465:     my ($uri,$varname)=@_;
                   11466:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 11467: 
                   11468:     my (@extension,@specifics,$do_default);
                   11469:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 11470: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 11471: 	if ($pack_type eq 'default') {
                   11472: 	    $do_default=1;
                   11473: 	} elsif ($pack_type eq 'extension') {
                   11474: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 11475: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 11476: 	    # only look at packages defaults for packages that this id is
1.738     albertel 11477: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   11478: 	}
                   11479:     }
                   11480:     # first look for a package that matches the requested part id
                   11481:     foreach my $package (@specifics) {
                   11482: 	my (undef,$pack_type,$pack_part)=@{$package};
                   11483: 	next if ($pack_part ne $part);
                   11484: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11485: 	    return $packagetab{"$pack_type&$name&default"};
                   11486: 	}
                   11487:     }
                   11488:     # look for any possible matching non extension_ package
                   11489:     foreach my $package (@specifics) {
                   11490: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 11491: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11492: 	    return $packagetab{"$pack_type&$name&default"};
                   11493: 	}
1.585     albertel 11494: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 11495: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   11496: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 11497: 	}
                   11498:     }
1.738     albertel 11499:     # look for any posible extension_ match
                   11500:     foreach my $package (@extension) {
                   11501: 	my ($package,$pack_type)=@{$package};
                   11502: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11503: 	    return $packagetab{"$pack_type&$name&default"};
                   11504: 	}
                   11505: 	if (defined($packagetab{$package."&$name&default"})) {
                   11506: 	    return $packagetab{$package."&$name&default"};
                   11507: 	}
                   11508:     }
                   11509:     # look for a global default setting
                   11510:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11511: 	return $packagetab{"default&$name&default"};
                   11512:     }
1.395     albertel 11513:     return undef;
                   11514: }
                   11515: 
1.334     albertel 11516: sub add_prefix_and_part {
                   11517:     my ($prefix,$part)=@_;
                   11518:     my $keyroot;
                   11519:     if (defined($prefix) && $prefix !~ /^__/) {
                   11520: 	# prefix that has a part already
                   11521: 	$keyroot=$prefix;
                   11522:     } elsif (defined($prefix)) {
                   11523: 	# prefix that is missing a part
                   11524: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11525:     } else {
                   11526: 	# no prefix at all
                   11527: 	if (defined($part)) { $keyroot='_'.$part; }
                   11528:     }
                   11529:     return $keyroot;
                   11530: }
                   11531: 
1.71      www      11532: # ---------------------------------------------------------------- Get metadata
                   11533: 
1.599     albertel 11534: my %metaentry;
1.1070    www      11535: my %importedpartids;
1.1172.2.99  raeburn  11536: my %importedrespids;
1.71      www      11537: sub metadata {
1.176     www      11538:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      11539:     $uri=&declutter($uri);
1.288     albertel 11540:     # if it is a non metadata possible uri return quickly
1.529     albertel 11541:     if (($uri eq '') || 
                   11542: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.20  raeburn  11543: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108    raeburn  11544:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11545: 	return undef;
                   11546:     }
1.1172.2.49  raeburn  11547:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11548: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11549: 	return undef;
1.288     albertel 11550:     }
1.73      www      11551:     my $filename=$uri;
                   11552:     $uri=~s/\.meta$//;
1.172     www      11553: #
                   11554: # Is the metadata already cached?
1.177     www      11555: # Look at timestamp of caching
1.172     www      11556: # Everything is cached by the main uri, libraries are never directly cached
                   11557: #
1.428     albertel 11558:     if (!defined($liburi)) {
1.599     albertel 11559: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11560: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11561:     }
                   11562:     {
1.1069    www      11563: # Imported parts would go here
1.1172.2.99  raeburn  11564:         my @origfiletagids=();
1.1069    www      11565:         my $importedparts=0;
1.1172.2.99  raeburn  11566: 
                   11567: # Imported responseids would go here
                   11568:         my $importedresponses=0;
1.172     www      11569: #
                   11570: # Is this a recursive call for a library?
                   11571: #
1.599     albertel 11572: #	if (! exists($metacache{$uri})) {
                   11573: #	    $metacache{$uri}={};
                   11574: #	}
1.924     albertel 11575: 	my $cachetime = 60*60;
1.171     www      11576:         if ($liburi) {
                   11577: 	    $liburi=&declutter($liburi);
                   11578:             $filename=$liburi;
1.401     bowersj2 11579:         } else {
1.599     albertel 11580: 	    &devalidate_cache_new('meta',$uri);
                   11581: 	    undef(%metaentry);
1.401     bowersj2 11582: 	}
1.140     www      11583:         my %metathesekeys=();
1.73      www      11584:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 11585: 	my $metastring;
1.1140    www      11586: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 11587: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 11588: 	    $metastring = 
1.929     albertel 11589: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 11590: 					  ('grade_target' => 'meta'));
                   11591: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  11592: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   11593:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 11594: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 11595: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 11596: 	    $metastring=&getfile($file);
1.489     albertel 11597: 	}
1.208     albertel 11598:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      11599:         my $token;
1.140     www      11600:         undef %metathesekeys;
1.71      www      11601:         while ($token=$parser->get_token) {
1.339     albertel 11602: 	    if ($token->[0] eq 'S') {
                   11603: 		if (defined($token->[2]->{'package'})) {
1.172     www      11604: #
                   11605: # This is a package - get package info
                   11606: #
1.339     albertel 11607: 		    my $package=$token->[2]->{'package'};
                   11608: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11609: 		    if (defined($token->[2]->{'id'})) { 
                   11610: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   11611: 		    }
1.599     albertel 11612: 		    if ($metaentry{':packages'}) {
                   11613: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 11614: 		    } else {
1.599     albertel 11615: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 11616: 		    }
1.736     albertel 11617: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 11618: 			my $part=$keyroot;
                   11619: 			$part=~s/^\_//;
1.736     albertel 11620: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   11621: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   11622: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 11623: 			    # ignore package.tab specified default values
                   11624:                             # here &package_tab_default() will fetch those
                   11625: 			    if ($subp eq 'default') { next; }
1.736     albertel 11626: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 11627: 			    my $unikey;
                   11628: 			    if ($pack =~ /_0$/) {
                   11629: 				$unikey='parameter_0_'.$name;
                   11630: 				$part=0;
                   11631: 			    } else {
                   11632: 				$unikey='parameter'.$keyroot.'_'.$name;
                   11633: 			    }
1.339     albertel 11634: 			    if ($subp eq 'display') {
                   11635: 				$value.=' [Part: '.$part.']';
                   11636: 			    }
1.599     albertel 11637: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 11638: 			    $metathesekeys{$unikey}=1;
1.599     albertel 11639: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11640: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 11641: 			    }
1.599     albertel 11642: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   11643: 				$metaentry{':'.$unikey}=
                   11644: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 11645: 			    }
1.339     albertel 11646: 			}
                   11647: 		    }
                   11648: 		} else {
1.172     www      11649: #
                   11650: # This is not a package - some other kind of start tag
1.339     albertel 11651: #
                   11652: 		    my $entry=$token->[1];
1.1068    www      11653: 		    my $unikey='';
1.175     www      11654: 
1.339     albertel 11655: 		    if ($entry eq 'import') {
1.175     www      11656: #
                   11657: # Importing a library here
1.339     albertel 11658: #
1.1067    www      11659:                         my $location=$parser->get_text('/import');
                   11660:                         my $dir=$filename;
                   11661:                         $dir=~s|[^/]*$||;
                   11662:                         $location=&filelocation($dir,$location);
1.1172.2.99  raeburn  11663: 
                   11664:                         my $importid=$token->[2]->{'id'};
1.1068    www      11665:                         my $importmode=$token->[2]->{'importmode'};
1.1172.2.99  raeburn  11666: #
                   11667: # Check metadata for imported file to
                   11668: # see if it contained response items
                   11669: #
                   11670:                         my %currmetaentry = %metaentry;
                   11671:                         my $libresponseorder = &metadata($location,'responseorder');
                   11672:                         my $origfile;
                   11673:                         if ($libresponseorder ne '') {
                   11674:                             if ($#origfiletagids<0) {
                   11675:                                 undef(%importedrespids);
                   11676:                                 undef(%importedpartids);
                   11677:                             }
                   11678:                             @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
                   11679:                             if (@{$importedrespids{$importid}} > 0) {
                   11680:                                 $importedresponses = 1;
                   11681: # We need to get the original file and the imported file to get the response order correct
                   11682: # Load and inspect original file
                   11683:                                 if ($#origfiletagids<0) {
                   11684:                                     my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11685:                                     $origfile=&getfile($origfilelocation);
                   11686:                                     @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11687:                                 }
                   11688:                             }
                   11689:                         }
                   11690: # Do not overwrite contents of %metaentry hash for resource itself with 
                   11691: # hash populated for imported library file
                   11692:                         %metaentry = %currmetaentry;
                   11693:                         undef(%currmetaentry);
1.1068    www      11694:                         if ($importmode eq 'problem') {
1.1069    www      11695: # Import as problem/response
1.1068    www      11696:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11697:                         } elsif ($importmode eq 'part') {
                   11698: # Import as part(s)
1.1069    www      11699:                            $importedparts=1;
                   11700: # We need to get the original file and the imported file to get the part order correct
                   11701: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.99  raeburn  11702: # Load and inspect original file if we didn't do that already
                   11703:                            if ($#origfiletagids<0) {
                   11704:                                undef(%importedrespids);
                   11705:                                undef(%importedpartids);
                   11706:                                if ($origfile eq '') {
                   11707:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11708:                                    $origfile=&getfile($origfilelocation);
                   11709:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11710:                                }
1.1070    www      11711:                            }
                   11712: 
1.1069    www      11713: # Load and inspect imported file
                   11714:                            my $impfile=&getfile($location);
                   11715:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11716:                            if ($#impfilepartids>=0) {
                   11717: # This problem had parts
1.1070    www      11718:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      11719:                            } else {
                   11720: # Importing by turning a single problem into a problem part
                   11721: # It gets the import-tags ID as part-ID
                   11722:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      11723:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      11724:                            }
1.1068    www      11725:                         } else {
                   11726: # Normal import
                   11727:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11728:                            if (defined($token->[2]->{'id'})) {
                   11729:                               $unikey.='_'.$token->[2]->{'id'};
                   11730:                            }
1.1067    www      11731:                         }
                   11732: 
1.339     albertel 11733: 			if ($depthcount<20) {
1.736     albertel 11734: 			    my $metadata = 
                   11735: 				&metadata($uri,'keys', $location,$unikey,
                   11736: 					  $depthcount+1);
                   11737: 			    foreach my $meta (split(',',$metadata)) {
                   11738: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   11739: 				$metathesekeys{$meta}=1;
1.339     albertel 11740: 			    }
1.1068    www      11741: 			
                   11742:                         }
1.1067    www      11743: 		    } else {
                   11744: #
                   11745: # Not importing, some other kind of non-package, non-library start tag
                   11746: # 
                   11747:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11748:                         if (defined($token->[2]->{'id'})) {
                   11749:                             $unikey.='_'.$token->[2]->{'id'};
                   11750:                         }
1.339     albertel 11751: 			if (defined($token->[2]->{'name'})) { 
                   11752: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   11753: 			}
                   11754: 			$metathesekeys{$unikey}=1;
1.736     albertel 11755: 			foreach my $param (@{$token->[3]}) {
                   11756: 			    $metaentry{':'.$unikey.'.'.$param} =
                   11757: 				$token->[2]->{$param};
1.339     albertel 11758: 			}
                   11759: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 11760: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 11761: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   11762: 		 # only ws inside the tag, and not in default, so use default
                   11763: 		 # as value
1.599     albertel 11764: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 11765: 			} elsif ( $internaltext =~ /\S/ ) {
                   11766: 		  # something interesting inside the tag
                   11767: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 11768: 			} else {
1.908     albertel 11769: 		  # no interesting values, don't set a default
1.339     albertel 11770: 			}
1.172     www      11771: # end of not-a-package not-a-library import
1.339     albertel 11772: 		    }
1.172     www      11773: # end of not-a-package start tag
1.339     albertel 11774: 		}
1.172     www      11775: # the next is the end of "start tag"
1.339     albertel 11776: 	    }
                   11777: 	}
1.483     albertel 11778: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 11779: 	$extension = lc($extension);
                   11780: 	if ($extension eq 'htm') { $extension='html'; }
                   11781: 
1.737     albertel 11782: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 11783: 	    #no specific packages #how's our extension
                   11784: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 11785: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 11786: 					 \%metathesekeys);
                   11787: 	}
1.883     albertel 11788: 
                   11789: 	if (!exists($metaentry{':packages'})
                   11790: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 11791: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 11792: 		#no specific packages well let's get default then
                   11793: 		if ($key!~/^default&/) { next; }
1.488     albertel 11794: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 11795: 					     \%metathesekeys);
                   11796: 	    }
                   11797: 	}
1.338     www      11798: # are there custom rights to evaluate
1.599     albertel 11799: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 11800: 
1.338     www      11801:     #
                   11802:     # Importing a rights file here
1.339     albertel 11803:     #
                   11804: 	    unless ($depthcount) {
1.599     albertel 11805: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 11806: 		my $dir=$filename;
                   11807: 		$dir=~s|[^/]*$||;
                   11808: 		$location=&filelocation($dir,$location);
1.736     albertel 11809: 		my $rights_metadata =
                   11810: 		    &metadata($uri,'keys',$location,'_rights',
                   11811: 			      $depthcount+1);
                   11812: 		foreach my $rights (split(',',$rights_metadata)) {
                   11813: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   11814: 		    $metathesekeys{$rights}=1;
1.339     albertel 11815: 		}
                   11816: 	    }
                   11817: 	}
1.737     albertel 11818: 	# uniqifiy package listing
                   11819: 	my %seen;
                   11820: 	my @uniq_packages =
                   11821: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   11822: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   11823: 
1.1172.2.99  raeburn  11824:         if (($importedresponses) || ($importedparts)) {
                   11825:             if ($importedparts) {
1.1070    www      11826: # We had imported parts and need to rebuild partorder
1.1172.2.99  raeburn  11827:                 $metaentry{':partorder'}='';
                   11828:                 $metathesekeys{'partorder'}=1;
                   11829:             }
                   11830:             if ($importedresponses) {
                   11831: # We had imported responses and need to rebuild responseorder
                   11832:                 $metaentry{':responseorder'}='';
                   11833:                 $metathesekeys{'responseorder'}=1;
                   11834:             }
                   11835:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   11836:                 my $origid = $origfiletagids[$index+1];
                   11837:                 if ($origfiletagids[$index] eq 'part') {
                   11838: # Original part, part of the problem
                   11839:                     if ($importedparts) {
                   11840:                         $metaentry{':partorder'}.=','.$origid;
                   11841:                     }
                   11842:                 } elsif ($origfiletagids[$index] eq 'import') {
                   11843:                     if ($importedparts) {
                   11844: # We have imported parts at this position
                   11845:                         $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   11846:                     }
                   11847:                     if ($importedresponses) {
                   11848: # We have imported responses at this position
                   11849:                         if (ref($importedrespids{$origid}) eq 'ARRAY') {
                   11850:                             $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
                   11851:                         }
                   11852:                     }
                   11853:                 } else {
                   11854: # Original response item, part of the problem
                   11855:                     if ($importedresponses) {
                   11856:                         $metaentry{':responseorder'}.=','.$origid;
                   11857:                     }
                   11858:                 }
                   11859:             }
                   11860:             if ($importedparts) {
                   11861:                 $metaentry{':partorder'}=~s/^\,//;
                   11862:             }
                   11863:             if ($importedresponses) {
                   11864:                 $metaentry{':responseorder'}=~s/^\,//;
                   11865:             }
1.1070    www      11866:         }
                   11867: 
1.737     albertel 11868: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 11869: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58  raeburn  11870: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 11871: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      11872: # this is the end of "was not already recently cached
1.71      www      11873:     }
1.599     albertel 11874:     return $metaentry{':'.$what};
1.261     albertel 11875: }
                   11876: 
1.488     albertel 11877: sub metadata_create_package_def {
1.483     albertel 11878:     my ($uri,$key,$package,$metathesekeys)=@_;
                   11879:     my ($pack,$name,$subp)=split(/\&/,$key);
                   11880:     if ($subp eq 'default') { next; }
                   11881:     
1.599     albertel 11882:     if (defined($metaentry{':packages'})) {
                   11883: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 11884:     } else {
1.599     albertel 11885: 	$metaentry{':packages'}=$package;
1.483     albertel 11886:     }
                   11887:     my $value=$packagetab{$key};
                   11888:     my $unikey;
                   11889:     $unikey='parameter_0_'.$name;
1.599     albertel 11890:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 11891:     $$metathesekeys{$unikey}=1;
1.599     albertel 11892:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11893: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 11894:     }
1.599     albertel 11895:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   11896: 	$metaentry{':'.$unikey}=
                   11897: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 11898:     }
                   11899: }
                   11900: 
1.261     albertel 11901: sub metadata_generate_part0 {
                   11902:     my ($metadata,$metacache,$uri) = @_;
                   11903:     my %allnames;
1.737     albertel 11904:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 11905: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 11906: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   11907: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 11908: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 11909: 	    $allnames{$name}=$part;
                   11910: 	  }
                   11911: 	}
                   11912:     }
                   11913:     foreach my $name (keys(%allnames)) {
                   11914:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 11915:       my $key=":parameter_0_$name";
1.261     albertel 11916:       $$metacache{"$key.part"}='0';
                   11917:       $$metacache{"$key.name"}=$name;
1.428     albertel 11918:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 11919: 					   $allnames{$name}.'_'.$name.
                   11920: 					   '.type'};
1.428     albertel 11921:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 11922: 			     '.display'};
1.644     www      11923:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 11924:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 11925:       $$metacache{"$key.display"}=$olddis;
                   11926:     }
1.71      www      11927: }
                   11928: 
1.764     albertel 11929: # ------------------------------------------------------ Devalidate title cache
                   11930: 
                   11931: sub devalidate_title_cache {
                   11932:     my ($url)=@_;
                   11933:     if (!$env{'request.course.id'}) { return; }
                   11934:     my $symb=&symbread($url);
                   11935:     if (!$symb) { return; }
                   11936:     my $key=$env{'request.course.id'}."\0".$symb;
                   11937:     &devalidate_cache_new('title',$key);
                   11938: }
                   11939: 
1.1014    droeschl 11940: # ------------------------------------------------- Get the title of a course
                   11941: 
                   11942: sub current_course_title {
                   11943:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   11944: }
1.301     www      11945: # ------------------------------------------------- Get the title of a resource
                   11946: 
                   11947: sub gettitle {
                   11948:     my $urlsymb=shift;
                   11949:     my $symb=&symbread($urlsymb);
1.534     albertel 11950:     if ($symb) {
1.620     albertel 11951: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 11952: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 11953: 	if (defined($cached)) { 
                   11954: 	    return $result;
                   11955: 	}
1.534     albertel 11956: 	my ($map,$resid,$url)=&decode_symb($symb);
                   11957: 	my $title='';
1.907     albertel 11958: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   11959: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   11960: 	} else {
                   11961: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11962: 		    &GDBM_READER(),0640)) {
                   11963: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   11964: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   11965: 		untie(%bighash);
                   11966: 	    }
1.534     albertel 11967: 	}
                   11968: 	$title=~s/\&colon\;/\:/gs;
                   11969: 	if ($title) {
1.1159    www      11970: # Remember both $symb and $title for dynamic metadata
                   11971:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      11972:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      11973: # Cache this title and then return it
1.599     albertel 11974: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 11975: 	}
                   11976: 	$urlsymb=$url;
                   11977:     }
                   11978:     my $title=&metadata($urlsymb,'title');
                   11979:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   11980:     return $title;
1.301     www      11981: }
1.613     albertel 11982: 
1.614     albertel 11983: sub get_slot {
                   11984:     my ($which,$cnum,$cdom)=@_;
                   11985:     if (!$cnum || !$cdom) {
1.790     albertel 11986: 	(undef,my $courseid)=&whichuser();
1.620     albertel 11987: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   11988: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 11989:     }
1.703     albertel 11990:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   11991:     my %slotinfo;
                   11992:     if (exists($remembered{$key})) {
                   11993: 	$slotinfo{$which} = $remembered{$key};
                   11994:     } else {
                   11995: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   11996: 	&Apache::lonhomework::showhash(%slotinfo);
                   11997: 	my ($tmp)=keys(%slotinfo);
                   11998: 	if ($tmp=~/^error:/) { return (); }
                   11999: 	$remembered{$key} = $slotinfo{$which};
                   12000:     }
1.616     albertel 12001:     if (ref($slotinfo{$which}) eq 'HASH') {
                   12002: 	return %{$slotinfo{$which}};
                   12003:     }
                   12004:     return $slotinfo{$which};
1.614     albertel 12005: }
1.1150    raeburn  12006: 
                   12007: sub get_reservable_slots {
                   12008:     my ($cnum,$cdom,$uname,$udom) = @_;
                   12009:     my $now = time;
                   12010:     my $reservable_info;
                   12011:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   12012:     if (exists($remembered{$key})) {
                   12013:         $reservable_info = $remembered{$key};
                   12014:     } else {
                   12015:         my %resv;
                   12016:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   12017:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   12018:         $reservable_info = \%resv;
                   12019:         $remembered{$key} = $reservable_info;
                   12020:     }
                   12021:     return $reservable_info;
                   12022: }
                   12023: 
                   12024: sub get_course_slots {
                   12025:     my ($cnum,$cdom) = @_;
                   12026:     my $hashid=$cnum.':'.$cdom;
                   12027:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   12028:     if (defined($cached)) {
                   12029:         if (ref($result) eq 'HASH') {
                   12030:             return %{$result};
                   12031:         }
                   12032:     } else {
                   12033:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   12034:         my ($tmp) = keys(%slots);
                   12035:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  12036:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  12037:             return %slots;
                   12038:         }
                   12039:     }
                   12040:     return;
                   12041: }
                   12042: 
                   12043: sub devalidate_slots_cache {
                   12044:     my ($cnum,$cdom)=@_;
                   12045:     my $hashid=$cnum.':'.$cdom;
                   12046:     &devalidate_cache_new('allslots',$hashid);
                   12047: }
                   12048: 
1.1172.2.8  raeburn  12049: sub get_coursechange {
                   12050:     my ($cdom,$cnum) = @_;
                   12051:     if ($cdom eq '' || $cnum eq '') {
                   12052:         return unless ($env{'request.course.id'});
                   12053:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   12054:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12055:     }
                   12056:     my $hashid=$cdom.'_'.$cnum;
                   12057:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   12058:     if ((defined($cached)) && ($change ne '')) {
                   12059:         return $change;
                   12060:     } else {
                   12061:         my %crshash;
                   12062:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   12063:         if ($crshash{'internal.contentchange'} eq '') {
                   12064:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   12065:             if ($change eq '') {
                   12066:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   12067:                 $change = $crshash{'internal.created'};
                   12068:             }
                   12069:         } else {
                   12070:             $change = $crshash{'internal.contentchange'};
                   12071:         }
                   12072:         my $cachetime = 600;
                   12073:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   12074:     }
                   12075:     return $change;
                   12076: }
                   12077: 
                   12078: sub devalidate_coursechange_cache {
                   12079:     my ($cnum,$cdom)=@_;
                   12080:     my $hashid=$cnum.':'.$cdom;
                   12081:     &devalidate_cache_new('crschange',$hashid);
                   12082: }
                   12083: 
1.31      www      12084: # ------------------------------------------------- Update symbolic store links
                   12085: 
                   12086: sub symblist {
                   12087:     my ($mapname,%newhash)=@_;
1.438     www      12088:     $mapname=&deversion(&declutter($mapname));
1.31      www      12089:     my %hash;
1.620     albertel 12090:     if (($env{'request.course.fn'}) && (%newhash)) {
                   12091:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12092:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  12093: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 12094: 		next if ($url eq 'last_known'
                   12095: 			 && $env{'form.no_update_last_known'});
                   12096: 		$hash{declutter($url)}=&encode_symb($mapname,
                   12097: 						    $newhash{$url}->[1],
                   12098: 						    $newhash{$url}->[0]);
1.191     harris41 12099:             }
1.31      www      12100:             if (untie(%hash)) {
                   12101: 		return 'ok';
                   12102:             }
                   12103:         }
                   12104:     }
                   12105:     return 'error';
1.212     www      12106: }
                   12107: 
                   12108: # --------------------------------------------------------------- Verify a symb
                   12109: 
                   12110: sub symbverify {
1.1172.2.11  raeburn  12111:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      12112:     my $thisfn=$thisurl;
1.439     www      12113:     $thisfn=&declutter($thisfn);
1.215     www      12114: # direct jump to resource in page or to a sequence - will construct own symbs
                   12115:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   12116: # check URL part
1.409     www      12117:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      12118: 
1.431     www      12119:     unless ($url eq $thisfn) { return 0; }
1.213     www      12120: 
1.216     www      12121:     $symb=&symbclean($symb);
1.510     www      12122:     $thisurl=&deversion($thisurl);
1.439     www      12123:     $thisfn=&deversion($thisfn);
1.213     www      12124: 
                   12125:     my %bighash;
                   12126:     my $okay=0;
1.431     www      12127: 
1.620     albertel 12128:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12129:                             &GDBM_READER(),0640)) {
1.1172.2.13  raeburn  12130:         my $noclutter;
1.1032    raeburn  12131:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   12132:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  12133:             if ($map =~ m{^uploaded/.+\.page$}) {
                   12134:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   12135:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   12136:                 $noclutter = 1;
                   12137:             }
                   12138:         }
                   12139:         my $ids;
                   12140:         if ($noclutter) {
                   12141:             $ids=$bighash{'ids_'.$thisurl};
                   12142:         } else {
                   12143:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  12144:         }
1.1102    raeburn  12145:         unless ($ids) {
1.1172.2.13  raeburn  12146:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  12147:             $ids=$bighash{$idkey};
1.216     www      12148:         }
                   12149:         if ($ids) {
                   12150: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  12151:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   12152:                 $symb =~ s/\?.+$//;
                   12153:             }
1.800     albertel 12154: 	    foreach my $id (split(/\,/,$ids)) {
                   12155: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      12156:                if (
                   12157:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  12158:    eq $symb) {
1.1172.2.11  raeburn  12159:                    if (ref($encstate)) {
                   12160:                        $$encstate = $bighash{'encrypted_'.$id};
                   12161:                    }
1.1172.2.13  raeburn  12162:                    if (($env{'request.role.adv'}) ||
                   12163:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  12164:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  12165:                        $okay=1;
                   12166:                        last;
                   12167:                    }
                   12168:                }
                   12169:            }
1.216     www      12170:         }
1.213     www      12171: 	untie(%bighash);
                   12172:     }
                   12173:     return $okay;
1.31      www      12174: }
                   12175: 
1.210     www      12176: # --------------------------------------------------------------- Clean-up symb
                   12177: 
                   12178: sub symbclean {
                   12179:     my $symb=shift;
1.568     albertel 12180:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      12181: # remove version from map
                   12182:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      12183: 
1.210     www      12184: # remove version from URL
                   12185:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      12186: 
1.507     www      12187: # remove wrapper
                   12188: 
1.510     www      12189:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 12190:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      12191:     return $symb;
1.409     www      12192: }
                   12193: 
                   12194: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 12195: 
                   12196: sub encode_symb {
                   12197:     my ($map,$resid,$url)=@_;
                   12198:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   12199: }
1.409     www      12200: 
                   12201: sub decode_symb {
1.568     albertel 12202:     my $symb=shift;
                   12203:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   12204:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      12205:     return (&fixversion($map),$resid,&fixversion($url));
                   12206: }
                   12207: 
                   12208: sub fixversion {
                   12209:     my $fn=shift;
1.609     banghart 12210:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      12211:     my %bighash;
                   12212:     my $uri=&clutter($fn);
1.620     albertel 12213:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      12214: # is this cached?
1.599     albertel 12215:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      12216:     if (defined($cached)) { return $result; }
                   12217: # unfortunately not cached, or expired
1.620     albertel 12218:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      12219: 	    &GDBM_READER(),0640)) {
                   12220:  	if ($bighash{'version_'.$uri}) {
                   12221:  	    my $version=$bighash{'version_'.$uri};
1.444     www      12222:  	    unless (($version eq 'mostrecent') || 
                   12223: 		    ($version==&getversion($uri))) {
1.440     www      12224:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   12225:  	    }
                   12226:  	}
                   12227:  	untie %bighash;
1.413     www      12228:     }
1.599     albertel 12229:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      12230: }
                   12231: 
                   12232: sub deversion {
                   12233:     my $url=shift;
                   12234:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   12235:     return $url;
1.210     www      12236: }
                   12237: 
1.31      www      12238: # ------------------------------------------------------ Return symb list entry
                   12239: 
                   12240: sub symbread {
1.1172.2.66  raeburn  12241:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1172.2.54  raeburn  12242:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.66  raeburn  12243:     if (defined($env{$cache_str})) {
                   12244:         if ($ignorecachednull) {
                   12245:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   12246:         } else {
                   12247:             return $env{$cache_str};
                   12248:         }
                   12249:     }
1.242     www      12250: # no filename provided? try from environment
1.1172.2.54  raeburn  12251:     unless ($thisfn) {
1.620     albertel 12252:         if ($env{'request.symb'}) {
1.1172.2.13  raeburn  12253:             return $env{$cache_str}=&symbclean($env{'request.symb'});
                   12254:         }
                   12255:         $thisfn=$env{'request.filename'};
1.44      www      12256:     }
1.569     albertel 12257:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      12258: # is that filename actually a symb? Verify, clean, and return
                   12259:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 12260: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 12261: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 12262: 	}
1.242     www      12263:     }
1.44      www      12264:     $thisfn=declutter($thisfn);
1.31      www      12265:     my %hash;
1.37      www      12266:     my %bighash;
                   12267:     my $syval='';
1.620     albertel 12268:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  12269:         my $targetfn = $thisfn;
1.609     banghart 12270:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  12271:             $targetfn = 'adm/wrapper/'.$thisfn;
                   12272:         }
1.687     albertel 12273: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   12274: 	    $targetfn=$1;
                   12275: 	}
1.620     albertel 12276:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12277:                       &GDBM_READER(),0640)) {
1.481     raeburn  12278: 	    $syval=$hash{$targetfn};
1.37      www      12279:             untie(%hash);
                   12280:         }
                   12281: # ---------------------------------------------------------- There was an entry
                   12282:         if ($syval) {
1.601     albertel 12283: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 12284: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  12285: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12286: 		    #return $env{$cache_str}='';
1.601     albertel 12287: 		#}    
                   12288: 		#$syval.=$1;
                   12289: 	    #}
1.37      www      12290:         } else {
                   12291: # ------------------------------------------------------- Was not in symb table
1.620     albertel 12292:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12293:                             &GDBM_READER(),0640)) {
1.37      www      12294: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      12295:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      12296:               unless ($ids) { 
                   12297:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      12298:               }
                   12299:               unless ($ids) {
                   12300: # alias?
                   12301: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      12302:               }
1.37      www      12303:               if ($ids) {
                   12304: # ------------------------------------------------------------------- Has ID(s)
                   12305:                  my @possibilities=split(/\,/,$ids);
1.39      www      12306:                  if ($#possibilities==0) {
                   12307: # ----------------------------------------------- There is only one possibility
1.37      www      12308: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 12309: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12310: 						    $resid,$thisfn);
1.1172.2.66  raeburn  12311:                      if (ref($possibles) eq 'HASH') {
                   12312:                          $possibles->{$syval} = 1;
                   12313:                      }
                   12314:                      if ($checkforblock) {
                   12315:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   12316:                          if (@blockers) {
                   12317:                              $syval = '';
                   12318:                              return;
                   12319:                          }
                   12320:                      }
                   12321:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39      www      12322: # ------------------------------------------ There is more than one possibility
                   12323:                      my $realpossible=0;
1.800     albertel 12324:                      foreach my $id (@possibilities) {
                   12325: 			 my $file=$bighash{'src_'.$id};
1.1172.2.66  raeburn  12326:                          my $canaccess;
                   12327:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   12328:                              $canaccess = 1;
                   12329:                          } else {
                   12330:                              $canaccess = &allowed('bre',$file);
                   12331:                          }
                   12332:                          if ($canaccess) {
                   12333:          		     my ($mapid,$resid)=split(/\./,$id);
                   12334:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   12335:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12336:                                                              $resid,$thisfn);
                   12337:                                  if (ref($possibles) eq 'HASH') {
                   12338:                                      $possibles->{$syval} = 1;
                   12339:                                  }
                   12340:                                  if ($checkforblock) {
                   12341:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   12342:                                      unless (@blockers > 0) {
                   12343:                                          $syval = $poss_syval;
                   12344:                                          $realpossible++;
                   12345:                                      }
                   12346:                                  } else {
                   12347:                                      $syval = $poss_syval;
                   12348:                                      $realpossible++;
                   12349:                                  }
                   12350:                              }
1.39      www      12351: 			 }
1.191     harris41 12352:                      }
1.39      www      12353: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      12354:                  } else {
                   12355:                      $syval='';
1.37      www      12356:                  }
                   12357: 	      }
1.1172.2.66  raeburn  12358:               untie(%bighash);
1.481     raeburn  12359:            }
1.31      www      12360:         }
1.62      www      12361:         if ($syval) {
1.620     albertel 12362: 	    return $env{$cache_str}=$syval;
1.62      www      12363:         }
1.31      www      12364:     }
1.949     raeburn  12365:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12366:     return $env{$cache_str}='';
1.31      www      12367: }
                   12368: 
                   12369: # ---------------------------------------------------------- Return random seed
                   12370: 
1.32      www      12371: sub numval {
                   12372:     my $txt=shift;
                   12373:     $txt=~tr/A-J/0-9/;
                   12374:     $txt=~tr/a-j/0-9/;
                   12375:     $txt=~tr/K-T/0-9/;
                   12376:     $txt=~tr/k-t/0-9/;
                   12377:     $txt=~tr/U-Z/0-5/;
                   12378:     $txt=~tr/u-z/0-5/;
                   12379:     $txt=~s/\D//g;
1.564     albertel 12380:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      12381:     return int($txt);
1.368     albertel 12382: }
                   12383: 
1.484     albertel 12384: sub numval2 {
                   12385:     my $txt=shift;
                   12386:     $txt=~tr/A-J/0-9/;
                   12387:     $txt=~tr/a-j/0-9/;
                   12388:     $txt=~tr/K-T/0-9/;
                   12389:     $txt=~tr/k-t/0-9/;
                   12390:     $txt=~tr/U-Z/0-5/;
                   12391:     $txt=~tr/u-z/0-5/;
                   12392:     $txt=~s/\D//g;
                   12393:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12394:     my $total;
                   12395:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 12396:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 12397:     return int($total);
                   12398: }
                   12399: 
1.575     albertel 12400: sub numval3 {
                   12401:     use integer;
                   12402:     my $txt=shift;
                   12403:     $txt=~tr/A-J/0-9/;
                   12404:     $txt=~tr/a-j/0-9/;
                   12405:     $txt=~tr/K-T/0-9/;
                   12406:     $txt=~tr/k-t/0-9/;
                   12407:     $txt=~tr/U-Z/0-5/;
                   12408:     $txt=~tr/u-z/0-5/;
                   12409:     $txt=~s/\D//g;
                   12410:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12411:     my $total;
                   12412:     foreach my $val (@txts) { $total+=$val; }
                   12413:     if ($_64bit) { $total=(($total<<32)>>32); }
                   12414:     return $total;
                   12415: }
                   12416: 
1.675     albertel 12417: sub digest {
                   12418:     my ($data)=@_;
                   12419:     my $digest=&Digest::MD5::md5($data);
                   12420:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   12421:     my ($e,$f);
                   12422:     {
                   12423:         use integer;
                   12424:         $e=($a+$b);
                   12425:         $f=($c+$d);
                   12426:         if ($_64bit) {
                   12427:             $e=(($e<<32)>>32);
                   12428:             $f=(($f<<32)>>32);
                   12429:         }
                   12430:     }
                   12431:     if (wantarray) {
                   12432: 	return ($e,$f);
                   12433:     } else {
                   12434: 	my $g;
                   12435: 	{
                   12436: 	    use integer;
                   12437: 	    $g=($e+$f);
                   12438: 	    if ($_64bit) {
                   12439: 		$g=(($g<<32)>>32);
                   12440: 	    }
                   12441: 	}
                   12442: 	return $g;
                   12443:     }
                   12444: }
                   12445: 
1.368     albertel 12446: sub latest_rnd_algorithm_id {
1.675     albertel 12447:     return '64bit5';
1.366     albertel 12448: }
1.32      www      12449: 
1.503     albertel 12450: sub get_rand_alg {
                   12451:     my ($courseid)=@_;
1.790     albertel 12452:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 12453:     if ($courseid) {
1.620     albertel 12454: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 12455:     }
                   12456:     return &latest_rnd_algorithm_id();
                   12457: }
                   12458: 
1.562     albertel 12459: sub validCODE {
                   12460:     my ($CODE)=@_;
                   12461:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   12462:     return 0;
                   12463: }
                   12464: 
1.491     albertel 12465: sub getCODE {
1.620     albertel 12466:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 12467:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   12468: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   12469: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 12470: 	return $Apache::lonhomework::history{'resource.CODE'};
                   12471:     }
                   12472:     return undef;
                   12473: }
1.1133    foxr     12474: #
                   12475: #  Determines the random seed for a specific context:
                   12476: #
                   12477: # parameters:
                   12478: #   symb      - in course context the symb for the seed.
                   12479: #   course_id - The course id of the form domain_coursenum.
                   12480: #   domain    - Domain for the user.
                   12481: #   course    - Course for the user.
                   12482: #   cenv      - environment of the course.
                   12483: #
                   12484: # NOTE:
                   12485: #   All parameters are picked out of the environment if missing
                   12486: #   or not defined.
                   12487: #   If a symb cannot be determined the current time is used instead.
                   12488: #
                   12489: #  For a given well defined symb, courside, domain, username,
                   12490: #  and course environment, the seed is reproducible.
                   12491: #
1.31      www      12492: sub rndseed {
1.1133    foxr     12493:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 12494:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 12495:     if (!defined($symb)) {
1.366     albertel 12496: 	unless ($symb=$wsymb) { return time; }
                   12497:     }
1.1146    foxr     12498:     if (!defined $courseid) { 
                   12499: 	$courseid=$wcourseid; 
                   12500:     }
                   12501:     if (!defined $domain) { $domain=$wdomain; }
                   12502:     if (!defined $username) { $username=$wusername }
1.1133    foxr     12503: 
                   12504:     my $which;
                   12505:     if (defined($cenv->{'rndseed'})) {
                   12506: 	$which = $cenv->{'rndseed'};
                   12507:     } else {
                   12508: 	$which =&get_rand_alg($courseid);
                   12509:     }
1.491     albertel 12510:     if (defined(&getCODE())) {
1.675     albertel 12511: 	if ($which eq '64bit5') {
                   12512: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   12513: 	} elsif ($which eq '64bit4') {
1.575     albertel 12514: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   12515: 	} else {
                   12516: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   12517: 	}
1.675     albertel 12518:     } elsif ($which eq '64bit5') {
                   12519: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 12520:     } elsif ($which eq '64bit4') {
                   12521: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 12522:     } elsif ($which eq '64bit3') {
                   12523: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 12524:     } elsif ($which eq '64bit2') {
                   12525: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 12526:     } elsif ($which eq '64bit') {
                   12527: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   12528:     }
                   12529:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   12530: }
                   12531: 
                   12532: sub rndseed_32bit {
                   12533:     my ($symb,$courseid,$domain,$username)=@_;
                   12534:     {
                   12535: 	use integer;
                   12536: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   12537: 	my $symbseed=numval($symb) << 22;
                   12538: 	my $namechck=unpack("%32C*",$username) << 17;
                   12539: 	my $nameseed=numval($username) << 12;
                   12540: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   12541: 	my $courseseed=unpack("%32C*",$courseid);
                   12542: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 12543: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12544: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12545: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 12546: 	return $num;
                   12547:     }
                   12548: }
                   12549: 
                   12550: sub rndseed_64bit {
                   12551:     my ($symb,$courseid,$domain,$username)=@_;
                   12552:     {
                   12553: 	use integer;
                   12554: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   12555: 	my $symbseed=numval($symb) << 10;
                   12556: 	my $namechck=unpack("%32S*",$username);
                   12557: 	
                   12558: 	my $nameseed=numval($username) << 21;
                   12559: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   12560: 	my $courseseed=unpack("%32S*",$courseid);
                   12561: 	
                   12562: 	my $num1=$symbchck+$symbseed+$namechck;
                   12563: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12564: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12565: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12566: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 12567: 	return "$num1,$num2";
1.155     albertel 12568:     }
1.366     albertel 12569: }
                   12570: 
1.443     albertel 12571: sub rndseed_64bit2 {
                   12572:     my ($symb,$courseid,$domain,$username)=@_;
                   12573:     {
                   12574: 	use integer;
                   12575: 	# strings need to be an even # of cahracters long, it it is odd the
                   12576:         # last characters gets thrown away
                   12577: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12578: 	my $symbseed=numval($symb) << 10;
                   12579: 	my $namechck=unpack("%32S*",$username.' ');
                   12580: 	
                   12581: 	my $nameseed=numval($username) << 21;
1.501     albertel 12582: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12583: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12584: 	
                   12585: 	my $num1=$symbchck+$symbseed+$namechck;
                   12586: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12587: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12588: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 12589: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 12590: 	return "$num1,$num2";
                   12591:     }
                   12592: }
                   12593: 
                   12594: sub rndseed_64bit3 {
                   12595:     my ($symb,$courseid,$domain,$username)=@_;
                   12596:     {
                   12597: 	use integer;
                   12598: 	# strings need to be an even # of cahracters long, it it is odd the
                   12599:         # last characters gets thrown away
                   12600: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12601: 	my $symbseed=numval2($symb) << 10;
                   12602: 	my $namechck=unpack("%32S*",$username.' ');
                   12603: 	
                   12604: 	my $nameseed=numval2($username) << 21;
1.443     albertel 12605: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12606: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12607: 	
                   12608: 	my $num1=$symbchck+$symbseed+$namechck;
                   12609: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12610: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12611: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 12612: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12613: 	
1.503     albertel 12614: 	return "$num1:$num2";
1.443     albertel 12615:     }
                   12616: }
                   12617: 
1.575     albertel 12618: sub rndseed_64bit4 {
                   12619:     my ($symb,$courseid,$domain,$username)=@_;
                   12620:     {
                   12621: 	use integer;
                   12622: 	# strings need to be an even # of cahracters long, it it is odd the
                   12623:         # last characters gets thrown away
                   12624: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12625: 	my $symbseed=numval3($symb) << 10;
                   12626: 	my $namechck=unpack("%32S*",$username.' ');
                   12627: 	
                   12628: 	my $nameseed=numval3($username) << 21;
                   12629: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12630: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12631: 	
                   12632: 	my $num1=$symbchck+$symbseed+$namechck;
                   12633: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12634: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12635: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 12636: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12637: 	
1.575     albertel 12638: 	return "$num1:$num2";
                   12639:     }
                   12640: }
                   12641: 
1.675     albertel 12642: sub rndseed_64bit5 {
                   12643:     my ($symb,$courseid,$domain,$username)=@_;
                   12644:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   12645:     return "$num1:$num2";
                   12646: }
                   12647: 
1.366     albertel 12648: sub rndseed_CODE_64bit {
                   12649:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 12650:     {
1.366     albertel 12651: 	use integer;
1.443     albertel 12652: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 12653: 	my $symbseed=numval2($symb);
1.491     albertel 12654: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12655: 	my $CODEseed=numval(&getCODE());
1.443     albertel 12656: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 12657: 	my $num1=$symbseed+$CODEchck;
                   12658: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12659: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12660: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 12661: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12662: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 12663: 	return "$num1:$num2";
1.366     albertel 12664:     }
                   12665: }
                   12666: 
1.575     albertel 12667: sub rndseed_CODE_64bit4 {
                   12668:     my ($symb,$courseid,$domain,$username)=@_;
                   12669:     {
                   12670: 	use integer;
                   12671: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   12672: 	my $symbseed=numval3($symb);
                   12673: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12674: 	my $CODEseed=numval3(&getCODE());
                   12675: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12676: 	my $num1=$symbseed+$CODEchck;
                   12677: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12678: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12679: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 12680: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12681: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   12682: 	return "$num1:$num2";
                   12683:     }
                   12684: }
                   12685: 
1.675     albertel 12686: sub rndseed_CODE_64bit5 {
                   12687:     my ($symb,$courseid,$domain,$username)=@_;
                   12688:     my $code = &getCODE();
                   12689:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   12690:     return "$num1:$num2";
                   12691: }
                   12692: 
1.366     albertel 12693: sub setup_random_from_rndseed {
                   12694:     my ($rndseed)=@_;
1.503     albertel 12695:     if ($rndseed =~/([,:])/) {
1.1172.2.51  raeburn  12696: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   12697:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   12698:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   12699:         } else {
                   12700:             &Math::Random::random_set_seed($num1,$num2);
                   12701:         }
1.366     albertel 12702:     } else {
                   12703: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 12704:     }
1.36      albertel 12705: }
                   12706: 
1.474     albertel 12707: sub latest_receipt_algorithm_id {
1.835     albertel 12708:     return 'receipt3';
1.474     albertel 12709: }
                   12710: 
1.480     www      12711: sub recunique {
                   12712:     my $fucourseid=shift;
                   12713:     my $unique;
1.835     albertel 12714:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   12715: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12716: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      12717:     } else {
                   12718: 	$unique=$perlvar{'lonReceipt'};
                   12719:     }
                   12720:     return unpack("%32C*",$unique);
                   12721: }
                   12722: 
                   12723: sub recprefix {
                   12724:     my $fucourseid=shift;
                   12725:     my $prefix;
1.835     albertel 12726:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   12727: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12728: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      12729:     } else {
                   12730: 	$prefix=$perlvar{'lonHostID'};
                   12731:     }
                   12732:     return unpack("%32C*",$prefix);
                   12733: }
                   12734: 
1.76      www      12735: sub ireceipt {
1.474     albertel 12736:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 12737: 
                   12738:     my $return =&recprefix($fucourseid).'-';
                   12739: 
                   12740:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   12741: 	$env{'request.state'} eq 'construct') {
                   12742: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   12743: 	return $return;
                   12744:     }
                   12745: 
1.76      www      12746:     my $cuname=unpack("%32C*",$funame);
                   12747:     my $cudom=unpack("%32C*",$fudom);
                   12748:     my $cucourseid=unpack("%32C*",$fucourseid);
                   12749:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      12750:     my $cunique=&recunique($fucourseid);
1.474     albertel 12751:     my $cpart=unpack("%32S*",$part);
1.835     albertel 12752:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   12753: 
1.790     albertel 12754: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 12755: 			       
                   12756: 	$return.= ($cunique%$cuname+
                   12757: 		   $cunique%$cudom+
                   12758: 		   $cusymb%$cuname+
                   12759: 		   $cusymb%$cudom+
                   12760: 		   $cucourseid%$cuname+
                   12761: 		   $cucourseid%$cudom+
                   12762: 		   $cpart%$cuname+
                   12763: 		   $cpart%$cudom);
                   12764:     } else {
                   12765: 	$return.= ($cunique%$cuname+
                   12766: 		   $cunique%$cudom+
                   12767: 		   $cusymb%$cuname+
                   12768: 		   $cusymb%$cudom+
                   12769: 		   $cucourseid%$cuname+
                   12770: 		   $cucourseid%$cudom);
                   12771:     }
                   12772:     return $return;
1.76      www      12773: }
                   12774: 
                   12775: sub receipt {
1.474     albertel 12776:     my ($part)=@_;
1.790     albertel 12777:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 12778:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      12779: }
1.260     ng       12780: 
1.790     albertel 12781: sub whichuser {
                   12782:     my ($passedsymb)=@_;
                   12783:     my ($symb,$courseid,$domain,$name,$publicuser);
                   12784:     if (defined($env{'form.grade_symb'})) {
                   12785: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   12786: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   12787: 	if (!$allowed &&
                   12788: 	    exists($env{'request.course.sec'}) &&
                   12789: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   12790: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   12791: 			      '/'.$env{'request.course.sec'});
                   12792: 	}
                   12793: 	if ($allowed) {
                   12794: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   12795: 	    $courseid=$tmp_courseid;
                   12796: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   12797: 	    ($name)=&get_env_multiple('form.grade_username');
                   12798: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   12799: 	}
                   12800:     }
                   12801:     if (!$passedsymb) {
                   12802: 	$symb=&symbread();
                   12803:     } else {
                   12804: 	$symb=$passedsymb;
                   12805:     }
                   12806:     $courseid=$env{'request.course.id'};
                   12807:     $domain=$env{'user.domain'};
                   12808:     $name=$env{'user.name'};
                   12809:     if ($name eq 'public' && $domain eq 'public') {
                   12810: 	if (!defined($env{'form.username'})) {
                   12811: 	    $env{'form.username'}.=time.rand(10000000);
                   12812: 	}
                   12813: 	$name.=$env{'form.username'};
                   12814:     }
                   12815:     return ($symb,$courseid,$domain,$name,$publicuser);
                   12816: 
                   12817: }
                   12818: 
1.36      albertel 12819: # ------------------------------------------------------------ Serves up a file
1.472     albertel 12820: # returns either the contents of the file or 
                   12821: # -1 if the file doesn't exist
1.481     raeburn  12822: #
                   12823: # if the target is a file that was uploaded via DOCS, 
                   12824: # a check will be made to see if a current copy exists on the local server,
                   12825: # if it does this will be served, otherwise a copy will be retrieved from
                   12826: # the home server for the course and stored in /home/httpd/html/userfiles on
                   12827: # the local server.   
1.472     albertel 12828: 
1.36      albertel 12829: sub getfile {
1.538     albertel 12830:     my ($file) = @_;
1.609     banghart 12831:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 12832:     &repcopy($file);
                   12833:     return &readfile($file);
                   12834: }
                   12835: 
                   12836: sub repcopy_userfile {
                   12837:     my ($file)=@_;
1.1142    raeburn  12838:     my $londocroot = $perlvar{'lonDocRoot'};
                   12839:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  12840:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 12841:     my ($cdom,$cnum,$filename) = 
1.811     albertel 12842: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 12843:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   12844:     if (-e "$file") {
1.828     www      12845: # we already have a local copy, check it out
1.538     albertel 12846: 	my @fileinfo = stat($file);
1.828     www      12847: 	my $rtncode;
                   12848: 	my $info;
1.538     albertel 12849: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 12850: 	if ($lwpresp ne 'ok') {
1.828     www      12851: # there is no such file anymore, even though we had a local copy
1.482     albertel 12852: 	    if ($rtncode eq '404') {
1.538     albertel 12853: 		unlink($file);
1.482     albertel 12854: 	    }
                   12855: 	    return -1;
                   12856: 	}
                   12857: 	if ($info < $fileinfo[9]) {
1.828     www      12858: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  12859: 	    return 'ok';
1.828     www      12860: 	} else {
                   12861: # the file is outdated, get rid of it
                   12862: 	    unlink($file);
1.482     albertel 12863: 	}
1.828     www      12864:     }
                   12865: # one way or the other, at this point, we don't have the file
                   12866: # construct the correct path for the file
                   12867:     my @parts = ($cdom,$cnum); 
                   12868:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   12869: 	push @parts, split(/\//,$1);
                   12870:     }
                   12871:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   12872:     foreach my $part (@parts) {
                   12873: 	$path .= '/'.$part;
                   12874: 	if (!-e $path) {
                   12875: 	    mkdir($path,0770);
1.482     albertel 12876: 	}
                   12877:     }
1.828     www      12878: # now the path exists for sure
                   12879: # get a user agent
                   12880:     my $ua=new LWP::UserAgent;
                   12881:     my $transferfile=$file.'.in.transfer';
                   12882: # FIXME: this should flock
                   12883:     if (-e $transferfile) { return 'ok'; }
                   12884:     my $request;
                   12885:     $uri=~s/^\///;
1.980     raeburn  12886:     my $homeserver = &homeserver($cnum,$cdom);
                   12887:     my $protocol = $protocol{$homeserver};
                   12888:     $protocol = 'http' if ($protocol ne 'https');
                   12889:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      12890:     my $response=$ua->request($request,$transferfile);
                   12891: # did it work?
                   12892:     if ($response->is_error()) {
                   12893: 	unlink($transferfile);
                   12894: 	&logthis("Userfile repcopy failed for $uri");
                   12895: 	return -1;
                   12896:     }
                   12897: # worked, rename the transfer file
                   12898:     rename($transferfile,$file);
1.607     raeburn  12899:     return 'ok';
1.481     raeburn  12900: }
                   12901: 
1.517     albertel 12902: sub tokenwrapper {
                   12903:     my $uri=shift;
1.980     raeburn  12904:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 12905:     $uri=~s|^/||;
1.620     albertel 12906:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 12907:     my $token=$1;
1.552     albertel 12908:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   12909:     if ($udom && $uname && $file) {
                   12910: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  12911:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  12912:         my $homeserver = &homeserver($uname,$udom);
                   12913:         my $protocol = $protocol{$homeserver};
                   12914:         $protocol = 'http' if ($protocol ne 'https');
                   12915:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 12916:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   12917:                                '&tokenissued='.$perlvar{'lonHostID'};
                   12918:     } else {
                   12919:         return '/adm/notfound.html';
                   12920:     }
                   12921: }
                   12922: 
1.828     www      12923: # call with reqtype HEAD: get last modification time
                   12924: # call with reqtype GET: get the file contents
                   12925: # Do not call this with reqtype GET for large files! It loads everything into memory
                   12926: #
1.481     raeburn  12927: sub getuploaded {
                   12928:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   12929:     $uri=~s/^\///;
1.980     raeburn  12930:     my $homeserver = &homeserver($cnum,$cdom);
                   12931:     my $protocol = $protocol{$homeserver};
                   12932:     $protocol = 'http' if ($protocol ne 'https');
                   12933:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  12934:     my $ua=new LWP::UserAgent;
                   12935:     my $request=new HTTP::Request($reqtype,$uri);
                   12936:     my $response=$ua->request($request);
                   12937:     $$rtncode = $response->code;
1.482     albertel 12938:     if (! $response->is_success()) {
                   12939: 	return 'failed';
                   12940:     }      
                   12941:     if ($reqtype eq 'HEAD') {
1.486     www      12942: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 12943:     } elsif ($reqtype eq 'GET') {
                   12944: 	$$info = $response->content;
1.472     albertel 12945:     }
1.482     albertel 12946:     return 'ok';
1.36      albertel 12947: }
                   12948: 
1.481     raeburn  12949: sub readfile {
                   12950:     my $file = shift;
                   12951:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   12952:     my $fh;
1.1172.2.96  raeburn  12953:     open($fh,"<",$file);
1.481     raeburn  12954:     my $a='';
1.800     albertel 12955:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  12956:     return $a;
                   12957: }
                   12958: 
1.36      albertel 12959: sub filelocation {
1.590     banghart 12960:     my ($dir,$file) = @_;
                   12961:     my $location;
                   12962:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 12963: 
                   12964:     if ($file =~ m-^/adm/-) {
                   12965: 	$file=~s-^/adm/wrapper/-/-;
                   12966: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   12967:     }
1.882     albertel 12968: 
1.1139    www      12969:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  12970:         $location = $file;
1.609     banghart 12971:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 12972:         my ($udom,$uname,$filename)=
1.811     albertel 12973:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 12974:         my $home=&homeserver($uname,$udom);
                   12975:         my $is_me=0;
                   12976:         my @ids=&current_machine_ids();
                   12977:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   12978:         if ($is_me) {
1.1117    foxr     12979:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 12980:         } else {
                   12981:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   12982:   	      $udom.'/'.$uname.'/'.$filename;
                   12983:         }
1.882     albertel 12984:     } elsif ($file =~ m-^/adm/-) {
                   12985: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 12986:     } else {
                   12987:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      12988:         $file=~s:^/(res|priv)/:/:;
                   12989:         my $space=$1;
1.590     banghart 12990:         if ( !( $file =~ m:^/:) ) {
                   12991:             $location = $dir. '/'.$file;
                   12992:         } else {
1.1142    raeburn  12993:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 12994:         }
1.59      albertel 12995:     }
1.590     banghart 12996:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 12997:     while ($location=~m{/\.\./}) {
                   12998: 	if ($location =~ m{/[^/]+/\.\./}) {
                   12999: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   13000: 	} else {
                   13001: 	    $location=~ s{/\.\./}{/}g;
                   13002: 	}
                   13003:     } #remove dir/..
1.590     banghart 13004:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   13005:     return $location;
1.46      www      13006: }
1.36      albertel 13007: 
1.46      www      13008: sub hreflocation {
                   13009:     my ($dir,$file)=@_;
1.980     raeburn  13010:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 13011: 	$file=filelocation($dir,$file);
1.700     albertel 13012:     } elsif ($file=~m-^/adm/-) {
                   13013: 	$file=~s-^/adm/wrapper/-/-;
                   13014: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 13015:     }
                   13016:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   13017: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   13018:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  13019: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   13020: 	        {/uploaded/$1/$2/}x;
1.46      www      13021:     }
1.913     albertel 13022:     if ($file=~ m{^/userfiles/}) {
                   13023: 	$file =~ s{^/userfiles/}{/uploaded/};
                   13024:     }
1.462     albertel 13025:     return $file;
1.465     albertel 13026: }
                   13027: 
1.1139    www      13028: 
                   13029: 
                   13030: 
                   13031: 
1.465     albertel 13032: sub current_machine_domains {
1.853     albertel 13033:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   13034: }
                   13035: 
                   13036: sub machine_domains {
                   13037:     my ($hostname) = @_;
1.465     albertel 13038:     my @domains;
1.838     albertel 13039:     my %hostname = &all_hostnames();
1.465     albertel 13040:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  13041: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 13042: 	if ($hostname eq $name) {
1.844     albertel 13043: 	    push(@domains,&host_domain($id));
1.465     albertel 13044: 	}
                   13045:     }
                   13046:     return @domains;
                   13047: }
                   13048: 
                   13049: sub current_machine_ids {
1.853     albertel 13050:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   13051: }
                   13052: 
                   13053: sub machine_ids {
                   13054:     my ($hostname) = @_;
                   13055:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 13056:     my @ids;
1.888     albertel 13057:     my %name_to_host = &all_names();
1.889     albertel 13058:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   13059: 	return @{ $name_to_host{$hostname} };
                   13060:     }
                   13061:     return;
1.31      www      13062: }
                   13063: 
1.824     raeburn  13064: sub additional_machine_domains {
                   13065:     my @domains;
1.1172.2.96  raeburn  13066:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824     raeburn  13067:     while( my $line = <$fh>) {
                   13068:         $line =~ s/\s//g;
                   13069:         push(@domains,$line);
                   13070:     }
                   13071:     return @domains;
                   13072: }
                   13073: 
                   13074: sub default_login_domain {
                   13075:     my $domain = $perlvar{'lonDefDomain'};
                   13076:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   13077:     foreach my $posdom (&current_machine_domains(),
                   13078:                         &additional_machine_domains()) {
                   13079:         if (lc($posdom) eq lc($testdomain)) {
                   13080:             $domain=$posdom;
                   13081:             last;
                   13082:         }
                   13083:     }
                   13084:     return $domain;
                   13085: }
                   13086: 
1.1172.2.106  raeburn  13087: sub shared_institution {
                   13088:     my ($dom) = @_;
                   13089:     my $same_intdom;
                   13090:     my $hostintdom = &internet_dom($perlvar{'lonHostID'});
                   13091:     if ($hostintdom ne '') {
                   13092:         my %iphost = &get_iphost();
                   13093:         my $primary_id = &domain($dom,'primary');
                   13094:         my $primary_ip = &get_host_ip($primary_id);
                   13095:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
                   13096:             foreach my $id (@{$iphost{$primary_ip}}) {
                   13097:                 my $intdom = &internet_dom($id);
                   13098:                 if ($intdom eq $hostintdom) {
                   13099:                     $same_intdom = 1;
                   13100:                     last;
                   13101:                 }
                   13102:             }
                   13103:         }
                   13104:     }
                   13105:     return $same_intdom;
                   13106: }
                   13107: 
1.31      www      13108: # ------------------------------------------------------------- Declutters URLs
                   13109: 
                   13110: sub declutter {
                   13111:     my $thisfn=shift;
1.569     albertel 13112:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49  raeburn  13113:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   13114:         $thisfn=~s{^/home/httpd/html}{};
                   13115:     }
1.31      www      13116:     $thisfn=~s/^\///;
1.697     albertel 13117:     $thisfn=~s|^adm/wrapper/||;
                   13118:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      13119:     $thisfn=~s/^res\///;
1.1172    bisitz   13120:     $thisfn=~s/^priv\///;
1.1032    raeburn  13121:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   13122:         $thisfn=~s/\?.+$//;
                   13123:     }
1.268     www      13124:     return $thisfn;
                   13125: }
                   13126: 
                   13127: # ------------------------------------------------------------- Clutter up URLs
                   13128: 
                   13129: sub clutter {
                   13130:     my $thisfn='/'.&declutter(shift);
1.887     albertel 13131:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 13132: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      13133:        $thisfn='/res'.$thisfn; 
                   13134:     }
1.1031    raeburn  13135:     if ($thisfn !~m|^/adm|) {
                   13136: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 13137: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 13138: 	} else {
                   13139: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   13140: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 13141: 	    if ($embstyle eq 'ssi'
                   13142: 		|| ($embstyle eq 'hdn')
                   13143: 		|| ($embstyle eq 'rat')
                   13144: 		|| ($embstyle eq 'prv')
                   13145: 		|| ($embstyle eq 'ign')) {
                   13146: 		#do nothing with these
                   13147: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 13148: 		|| ($embstyle eq 'emb')
                   13149: 		|| ($embstyle eq 'wrp')) {
                   13150: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 13151: 	    } elsif ($embstyle eq 'unk'
                   13152: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 13153: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 13154: 	    } else {
1.718     www      13155: #		&logthis("Got a blank emb style");
1.695     albertel 13156: 	    }
1.694     albertel 13157: 	}
                   13158:     }
1.31      www      13159:     return $thisfn;
1.12      www      13160: }
                   13161: 
1.787     albertel 13162: sub clutter_with_no_wrapper {
                   13163:     my $uri = &clutter(shift);
                   13164:     if ($uri =~ m-^/adm/-) {
                   13165: 	$uri =~ s-^/adm/wrapper/-/-;
                   13166: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   13167:     }
                   13168:     return $uri;
                   13169: }
                   13170: 
1.557     albertel 13171: sub freeze_escape {
                   13172:     my ($value)=@_;
                   13173:     if (ref($value)) {
                   13174: 	$value=&nfreeze($value);
                   13175: 	return '__FROZEN__'.&escape($value);
                   13176:     }
                   13177:     return &escape($value);
                   13178: }
                   13179: 
1.11      www      13180: 
1.557     albertel 13181: sub thaw_unescape {
                   13182:     my ($value)=@_;
                   13183:     if ($value =~ /^__FROZEN__/) {
                   13184: 	substr($value,0,10,undef);
                   13185: 	$value=&unescape($value);
                   13186: 	return &thaw($value);
                   13187:     }
                   13188:     return &unescape($value);
                   13189: }
                   13190: 
1.436     albertel 13191: sub correct_line_ends {
                   13192:     my ($result)=@_;
                   13193:     $$result =~s/\r\n/\n/mg;
                   13194:     $$result =~s/\r/\n/mg;
1.415     albertel 13195: }
1.1       albertel 13196: # ================================================================ Main Program
                   13197: 
1.184     www      13198: sub goodbye {
1.204     albertel 13199:    &logthis("Starting Shut down");
1.443     albertel 13200: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 13201:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 13202: #converted
1.599     albertel 13203: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 13204:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   13205: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   13206: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 13207: #1.1 only
1.870     albertel 13208: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   13209: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   13210: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   13211: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   13212:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 13213:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   13214:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      13215:    &flushcourselogs();
                   13216:    &logthis("Shutting down");
                   13217: }
                   13218: 
1.852     albertel 13219: sub get_dns {
1.1172.2.17  raeburn  13220:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 13221:     if (!$ignore_cache) {
                   13222: 	my ($content,$cached)=
                   13223: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   13224: 	if ($cached) {
1.1172.2.17  raeburn  13225: 	    &$func($content,$hashref);
1.869     albertel 13226: 	    return;
                   13227: 	}
                   13228:     }
                   13229: 
                   13230:     my %alldns;
1.1172.2.96  raeburn  13231:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   13232:         foreach my $dns (<$config>) {
                   13233: 	    next if ($dns !~ /^\^(\S*)/x);
                   13234:             my $line = $1;
                   13235:             my ($host,$protocol) = split(/:/,$line);
                   13236:             if ($protocol ne 'https') {
                   13237:                 $protocol = 'http';
                   13238:             }
                   13239: 	    $alldns{$host} = $protocol;
1.979     raeburn  13240:         }
1.1172.2.96  raeburn  13241:         close($config);
1.869     albertel 13242:     }
                   13243:     while (%alldns) {
1.1172.2.52  raeburn  13244: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 13245: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  13246:         $ua->timeout(30);
1.979     raeburn  13247: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 13248: 	my $response=$ua->request($request);
1.979     raeburn  13249:         delete($alldns{$dns});
1.852     albertel 13250: 	next if ($response->is_error());
                   13251: 	my @content = split("\n",$response->content);
1.1172.2.17  raeburn  13252:         unless ($nocache) {
1.1172.2.23  raeburn  13253: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  13254:         }
                   13255: 	&$func(\@content,$hashref);
1.869     albertel 13256: 	return;
1.852     albertel 13257:     }
1.871     albertel 13258:     my $which = (split('/',$url))[3];
                   13259:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.105  raeburn  13260:     if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   13261:         my @content = <$config>;
                   13262:         &$func(\@content,$hashref);
                   13263:     }
1.1172.2.17  raeburn  13264:     return;
                   13265: }
                   13266: 
                   13267: # ------------------------------------------------------Get DNS checksums file
                   13268: sub parse_dns_checksums_tab {
                   13269:     my ($lines,$hashref) = @_;
1.1172.2.53  raeburn  13270:     my $lonhost = $perlvar{'lonHostID'};
                   13271:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17  raeburn  13272:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53  raeburn  13273:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   13274:     my $webconfdir = '/etc/httpd/conf';
                   13275:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   13276:         $webconfdir = '/etc/apache2';
                   13277:     } elsif ($distro =~ /^sles(\d+)$/) {
                   13278:         if ($1 >= 10) {
                   13279:             $webconfdir = '/etc/apache2';
                   13280:         }
                   13281:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   13282:         if ($1 >= 10.0) {
                   13283:             $webconfdir = '/etc/apache2';
                   13284:         }
                   13285:     }
1.1172.2.17  raeburn  13286:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13287:     my (%chksum,%revnum);
                   13288:     if (ref($lines) eq 'ARRAY') {
                   13289:         chomp(@{$lines});
1.1172.2.34  raeburn  13290:         my $version = shift(@{$lines});
                   13291:         if ($version eq $release) {
1.1172.2.17  raeburn  13292:             foreach my $line (@{$lines}) {
1.1172.2.34  raeburn  13293:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53  raeburn  13294:                 if ($file =~ m{^/etc/httpd/conf}) {
                   13295:                     if ($webconfdir eq '/etc/apache2') {
                   13296:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   13297:                     }
                   13298:                 }
1.1172.2.34  raeburn  13299:                 $chksum{$file} = $shasum;
                   13300:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  13301:             }
                   13302:             if (ref($hashref) eq 'HASH') {
                   13303:                 %{$hashref} = (
                   13304:                                 sums     => \%chksum,
                   13305:                                 versions => \%revnum,
                   13306:                               );
                   13307:             }
                   13308:         }
                   13309:     }
1.869     albertel 13310:     return;
1.852     albertel 13311: }
1.1172.2.17  raeburn  13312: 
                   13313: sub fetch_dns_checksums {
                   13314:     my %checksums;
1.1172.2.34  raeburn  13315:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48  raeburn  13316:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34  raeburn  13317:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13318:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  13319:              \%checksums);
                   13320:     return \%checksums;
                   13321: }
                   13322: 
1.327     albertel 13323: # ------------------------------------------------------------ Read domain file
                   13324: {
1.852     albertel 13325:     my $loaded;
1.846     albertel 13326:     my %domain;
                   13327: 
1.852     albertel 13328:     sub parse_domain_tab {
                   13329: 	my ($lines) = @_;
                   13330: 	foreach my $line (@$lines) {
                   13331: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      13332: 
1.846     albertel 13333: 	    chomp($line);
1.852     albertel 13334: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 13335: 	    my %this_domain;
                   13336: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   13337: 			       'lang_def', 'city', 'longi', 'lati',
                   13338: 			       'primary') {
                   13339: 		$this_domain{$field} = shift(@elements);
                   13340: 	    }
                   13341: 	    $domain{$name} = \%this_domain;
1.852     albertel 13342: 	}
                   13343:     }
1.864     albertel 13344: 
                   13345:     sub reset_domain_info {
                   13346: 	undef($loaded);
                   13347: 	undef(%domain);
                   13348:     }
                   13349: 
1.852     albertel 13350:     sub load_domain_tab {
1.1172.2.70  raeburn  13351: 	my ($ignore_cache,$nocache) = @_;
                   13352: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 13353: 	my $fh;
1.1172.2.96  raeburn  13354: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 13355: 	    my @lines = <$fh>;
                   13356: 	    &parse_domain_tab(\@lines);
1.448     albertel 13357: 	}
1.852     albertel 13358: 	close($fh);
                   13359: 	$loaded = 1;
1.327     albertel 13360:     }
1.846     albertel 13361: 
                   13362:     sub domain {
1.852     albertel 13363: 	&load_domain_tab() if (!$loaded);
                   13364: 
1.846     albertel 13365: 	my ($name,$what) = @_;
                   13366: 	return if ( !exists($domain{$name}) );
                   13367: 
                   13368: 	if (!$what) {
                   13369: 	    return $domain{$name}{'description'};
                   13370: 	}
                   13371: 	return $domain{$name}{$what};
                   13372:     }
1.974     raeburn  13373: 
                   13374:     sub domain_info {
                   13375:         &load_domain_tab() if (!$loaded);
                   13376:         return %domain;
                   13377:     }
                   13378: 
1.327     albertel 13379: }
                   13380: 
                   13381: 
1.1       albertel 13382: # ------------------------------------------------------------- Read hosts file
                   13383: {
1.838     albertel 13384:     my %hostname;
1.844     albertel 13385:     my %hostdom;
1.845     albertel 13386:     my %libserv;
1.852     albertel 13387:     my $loaded;
1.888     albertel 13388:     my %name_to_host;
1.1074    raeburn  13389:     my %internetdom;
1.1107    raeburn  13390:     my %LC_dns_serv;
1.852     albertel 13391: 
                   13392:     sub parse_hosts_tab {
                   13393: 	my ($file) = @_;
                   13394: 	foreach my $configline (@$file) {
                   13395: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  13396:             chomp($configline);
                   13397: 	    if ($configline =~ /^\^/) {
                   13398:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   13399:                     $LC_dns_serv{$1} = 1;
                   13400:                 }
                   13401:                 next;
                   13402:             }
1.1074    raeburn  13403: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 13404: 	    $name=~s/\s//g;
                   13405: 	    if ($id && $domain && $role && $name) {
1.1172.2.96  raeburn  13406:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   13407:                     my $curr = $hostname{$id};
                   13408:                     my $skip;
                   13409:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   13410:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   13411:                             $skip = 1;
                   13412:                         } else {
                   13413:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   13414:                         }
                   13415:                     }
                   13416:                     unless ($skip) {
                   13417:                         push(@{$name_to_host{$name}},$id);
                   13418:                     }
                   13419:                 } else {
                   13420:                     push(@{$name_to_host{$name}},$id);
                   13421:                 }
1.852     albertel 13422: 		$hostname{$id}=$name;
                   13423: 		$hostdom{$id}=$domain;
                   13424: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  13425:                 if (defined($protocol)) {
                   13426:                     if ($protocol eq 'https') {
                   13427:                         $protocol{$id} = $protocol;
                   13428:                     } else {
                   13429:                         $protocol{$id} = 'http'; 
                   13430:                     }
1.968     raeburn  13431:                 } else {
1.969     raeburn  13432:                     $protocol{$id} = 'http';
1.968     raeburn  13433:                 }
1.1074    raeburn  13434:                 if (defined($intdom)) {
                   13435:                     $internetdom{$id} = $intdom;
                   13436:                 }
1.852     albertel 13437: 	    }
                   13438: 	}
                   13439:     }
1.864     albertel 13440:     
                   13441:     sub reset_hosts_info {
1.897     albertel 13442: 	&purge_remembered();
1.864     albertel 13443: 	&reset_domain_info();
                   13444: 	&reset_hosts_ip_info();
1.892     albertel 13445: 	undef(%name_to_host);
1.864     albertel 13446: 	undef(%hostname);
                   13447: 	undef(%hostdom);
                   13448: 	undef(%libserv);
                   13449: 	undef($loaded);
                   13450:     }
1.1       albertel 13451: 
1.852     albertel 13452:     sub load_hosts_tab {
1.1172.2.70  raeburn  13453: 	my ($ignore_cache,$nocache) = @_;
                   13454: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96  raeburn  13455: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 13456: 	my @config = <$config>;
                   13457: 	&parse_hosts_tab(\@config);
                   13458: 	close($config);
                   13459: 	$loaded=1;
1.1       albertel 13460:     }
1.852     albertel 13461: 
1.838     albertel 13462:     sub hostname {
1.852     albertel 13463: 	&load_hosts_tab() if (!$loaded);
                   13464: 
1.838     albertel 13465: 	my ($lonid) = @_;
                   13466: 	return $hostname{$lonid};
                   13467:     }
1.845     albertel 13468: 
1.838     albertel 13469:     sub all_hostnames {
1.852     albertel 13470: 	&load_hosts_tab() if (!$loaded);
                   13471: 
1.838     albertel 13472: 	return %hostname;
                   13473:     }
1.845     albertel 13474: 
1.888     albertel 13475:     sub all_names {
1.1172.2.70  raeburn  13476:         my ($ignore_cache,$nocache) = @_;
                   13477: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 13478: 
                   13479: 	return %name_to_host;
                   13480:     }
                   13481: 
1.974     raeburn  13482:     sub all_host_domain {
                   13483:         &load_hosts_tab() if (!$loaded);
                   13484:         return %hostdom;
                   13485:     }
                   13486: 
1.845     albertel 13487:     sub is_library {
1.852     albertel 13488: 	&load_hosts_tab() if (!$loaded);
                   13489: 
1.845     albertel 13490: 	return exists($libserv{$_[0]});
                   13491:     }
                   13492: 
                   13493:     sub all_library {
1.852     albertel 13494: 	&load_hosts_tab() if (!$loaded);
                   13495: 
1.845     albertel 13496: 	return %libserv;
                   13497:     }
                   13498: 
1.1062    droeschl 13499:     sub unique_library {
                   13500: 	#2x reverse removes all hostnames that appear more than once
                   13501:         my %unique = reverse &all_library();
                   13502:         return reverse %unique;
                   13503:     }
                   13504: 
1.841     albertel 13505:     sub get_servers {
1.852     albertel 13506: 	&load_hosts_tab() if (!$loaded);
                   13507: 
1.841     albertel 13508: 	my ($domain,$type) = @_;
                   13509: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   13510: 	                                          : %hostname;
                   13511: 	my %result;
1.842     albertel 13512: 	if (ref($domain) eq 'ARRAY') {
                   13513: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 13514: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 13515: 		    $result{$host} = $hostname;
                   13516: 		}
                   13517: 	    }
                   13518: 	} else {
                   13519: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   13520: 		if ($hostdom{$host} eq $domain) {
                   13521: 		    $result{$host} = $hostname;
                   13522: 		}
1.841     albertel 13523: 	    }
                   13524: 	}
                   13525: 	return %result;
                   13526:     }
1.845     albertel 13527: 
1.1062    droeschl 13528:     sub get_unique_servers {
                   13529:         my %unique = reverse &get_servers(@_);
                   13530: 	return reverse %unique;
                   13531:     }
                   13532: 
1.844     albertel 13533:     sub host_domain {
1.852     albertel 13534: 	&load_hosts_tab() if (!$loaded);
                   13535: 
1.844     albertel 13536: 	my ($lonid) = @_;
                   13537: 	return $hostdom{$lonid};
                   13538:     }
                   13539: 
1.841     albertel 13540:     sub all_domains {
1.852     albertel 13541: 	&load_hosts_tab() if (!$loaded);
                   13542: 
1.841     albertel 13543: 	my %seen;
                   13544: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   13545: 	return @uniq;
                   13546:     }
1.1074    raeburn  13547: 
                   13548:     sub internet_dom {
                   13549:         &load_hosts_tab() if (!$loaded);
                   13550: 
                   13551:         my ($lonid) = @_;
                   13552:         return $internetdom{$lonid};
                   13553:     }
1.1107    raeburn  13554: 
                   13555:     sub is_LC_dns {
                   13556:         &load_hosts_tab() if (!$loaded);
                   13557: 
                   13558:         my ($hostname) = @_;
                   13559:         return exists($LC_dns_serv{$hostname});
                   13560:     }
                   13561: 
1.1       albertel 13562: }
                   13563: 
1.847     albertel 13564: { 
                   13565:     my %iphost;
1.856     albertel 13566:     my %name_to_ip;
                   13567:     my %lonid_to_ip;
1.869     albertel 13568: 
1.847     albertel 13569:     sub get_hosts_from_ip {
                   13570: 	my ($ip) = @_;
                   13571: 	my %iphosts = &get_iphost();
                   13572: 	if (ref($iphosts{$ip})) {
                   13573: 	    return @{$iphosts{$ip}};
                   13574: 	}
                   13575: 	return;
1.839     albertel 13576:     }
1.864     albertel 13577:     
                   13578:     sub reset_hosts_ip_info {
                   13579: 	undef(%iphost);
                   13580: 	undef(%name_to_ip);
                   13581: 	undef(%lonid_to_ip);
                   13582:     }
1.856     albertel 13583: 
                   13584:     sub get_host_ip {
                   13585: 	my ($lonid) = @_;
                   13586: 	if (exists($lonid_to_ip{$lonid})) {
                   13587: 	    return $lonid_to_ip{$lonid};
                   13588: 	}
                   13589: 	my $name=&hostname($lonid);
                   13590:    	my $ip = gethostbyname($name);
                   13591: 	return if (!$ip || length($ip) ne 4);
                   13592: 	$ip=inet_ntoa($ip);
                   13593: 	$name_to_ip{$name}   = $ip;
                   13594: 	$lonid_to_ip{$lonid} = $ip;
                   13595: 	return $ip;
                   13596:     }
1.847     albertel 13597:     
                   13598:     sub get_iphost {
1.1172.2.70  raeburn  13599: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 13600: 
1.869     albertel 13601: 	if (!$ignore_cache) {
                   13602: 	    if (%iphost) {
                   13603: 		return %iphost;
                   13604: 	    }
                   13605: 	    my ($ip_info,$cached)=
                   13606: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   13607: 	    if ($cached) {
                   13608: 		%iphost      = %{$ip_info->[0]};
                   13609: 		%name_to_ip  = %{$ip_info->[1]};
                   13610: 		%lonid_to_ip = %{$ip_info->[2]};
                   13611: 		return %iphost;
                   13612: 	    }
                   13613: 	}
1.894     albertel 13614: 
                   13615: 	# get yesterday's info for fallback
                   13616: 	my %old_name_to_ip;
                   13617: 	my ($ip_info,$cached)=
                   13618: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   13619: 	if ($cached) {
                   13620: 	    %old_name_to_ip = %{$ip_info->[1]};
                   13621: 	}
                   13622: 
1.1172.2.70  raeburn  13623: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 13624: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 13625: 	    my $ip;
                   13626: 	    if (!exists($name_to_ip{$name})) {
                   13627: 		$ip = gethostbyname($name);
                   13628: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 13629: 		    if (defined($old_name_to_ip{$name})) {
                   13630: 			$ip = $old_name_to_ip{$name};
                   13631: 			&logthis("Can't find $name defaulting to old $ip");
                   13632: 		    } else {
                   13633: 			&logthis("Name $name no IP found");
                   13634: 			next;
                   13635: 		    }
                   13636: 		} else {
                   13637: 		    $ip=inet_ntoa($ip);
1.847     albertel 13638: 		}
                   13639: 		$name_to_ip{$name} = $ip;
                   13640: 	    } else {
                   13641: 		$ip = $name_to_ip{$name};
1.653     albertel 13642: 	    }
1.888     albertel 13643: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   13644: 		$lonid_to_ip{$id} = $ip;
                   13645: 	    }
                   13646: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 13647: 	}
1.1172.2.70  raeburn  13648:         unless ($nocache) {
                   13649: 	    &do_cache_new('iphost','iphost',
                   13650: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   13651: 		          48*60*60);
                   13652:         }
1.869     albertel 13653: 
1.847     albertel 13654: 	return %iphost;
1.598     albertel 13655:     }
                   13656: 
1.992     raeburn  13657:     #
                   13658:     #  Given a DNS returns the loncapa host name for that DNS 
                   13659:     # 
                   13660:     sub host_from_dns {
                   13661:         my ($dns) = @_;
                   13662:         my @hosts;
                   13663:         my $ip;
                   13664: 
1.993     raeburn  13665:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  13666:             $ip = $name_to_ip{$dns};
                   13667:         }
                   13668:         if (!$ip) {
                   13669:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   13670:             if (length($ip) == 4) { 
                   13671: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   13672:             }
                   13673:         }
                   13674:         if ($ip) {
                   13675: 	    @hosts = get_hosts_from_ip($ip);
                   13676: 	    return $hosts[0];
                   13677:         }
                   13678:         return undef;
1.986     foxr     13679:     }
1.992     raeburn  13680: 
1.1074    raeburn  13681:     sub get_internet_names {
                   13682:         my ($lonid) = @_;
                   13683:         return if ($lonid eq '');
                   13684:         my ($idnref,$cached)=
                   13685:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   13686:         if ($cached) {
                   13687:             return $idnref;
                   13688:         }
                   13689:         my $ip = &get_host_ip($lonid);
                   13690:         my @hosts = &get_hosts_from_ip($ip);
                   13691:         my %iphost = &get_iphost();
                   13692:         my (@idns,%seen);
                   13693:         foreach my $id (@hosts) {
                   13694:             my $dom = &host_domain($id);
                   13695:             my $prim_id = &domain($dom,'primary');
                   13696:             my $prim_ip = &get_host_ip($prim_id);
                   13697:             next if ($seen{$prim_ip});
                   13698:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   13699:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   13700:                     my $intdom = &internet_dom($id);
                   13701:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   13702:                         push(@idns,$intdom);
                   13703:                     }
                   13704:                 }
                   13705:             }
                   13706:             $seen{$prim_ip} = 1;
                   13707:         }
1.1172.2.23  raeburn  13708:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  13709:     }
                   13710: 
1.986     foxr     13711: }
                   13712: 
1.1079    raeburn  13713: sub all_loncaparevs {
1.1172.2.39  raeburn  13714:     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  13715: }
                   13716: 
1.1172.2.27  raeburn  13717: # ------------------------------------------------------- Read loncaparev table
                   13718: {
                   13719:     sub load_loncaparevs {
                   13720:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96  raeburn  13721:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27  raeburn  13722:                 while (my $configline=<$config>) {
                   13723:                     chomp($configline);
                   13724:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   13725:                     $loncaparevs{$hostid}=$loncaparev;
                   13726:                 }
                   13727:                 close($config);
                   13728:             }
                   13729:         }
                   13730:     }
                   13731: }
                   13732: 
                   13733: # ----------------------------------------------------- Read serverhostID table
                   13734: {
                   13735:     sub load_serverhomeIDs {
                   13736:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96  raeburn  13737:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27  raeburn  13738:                 while (my $configline=<$config>) {
                   13739:                     chomp($configline);
                   13740:                     my ($name,$id)=split(/:/,$configline);
                   13741:                     $serverhomeIDs{$name}=$id;
                   13742:                 }
                   13743:                 close($config);
                   13744:             }
                   13745:         }
                   13746:     }
                   13747: }
                   13748: 
                   13749: 
1.862     albertel 13750: BEGIN {
                   13751: 
                   13752: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   13753:     unless ($readit) {
                   13754: {
                   13755:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   13756:     %perlvar = (%perlvar,%{$configvars});
                   13757: }
                   13758: 
                   13759: 
1.1       albertel 13760: # ------------------------------------------------------ Read spare server file
                   13761: {
1.1172.2.96  raeburn  13762:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 13763: 
                   13764:     while (my $configline=<$config>) {
                   13765:        chomp($configline);
1.284     matthew  13766:        if ($configline) {
1.784     albertel 13767: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 13768: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 13769: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 13770:        }
                   13771:     }
1.448     albertel 13772:     close($config);
1.1       albertel 13773: }
1.11      www      13774: # ------------------------------------------------------------ Read permissions
                   13775: {
1.1172.2.96  raeburn  13776:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      13777: 
                   13778:     while (my $configline=<$config>) {
1.448     albertel 13779: 	chomp($configline);
                   13780: 	if ($configline) {
                   13781: 	    my ($role,$perm)=split(/ /,$configline);
                   13782: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   13783: 	}
1.11      www      13784:     }
1.448     albertel 13785:     close($config);
1.11      www      13786: }
                   13787: 
                   13788: # -------------------------------------------- Read plain texts for permissions
                   13789: {
1.1172.2.96  raeburn  13790:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      13791: 
                   13792:     while (my $configline=<$config>) {
1.448     albertel 13793: 	chomp($configline);
                   13794: 	if ($configline) {
1.742     raeburn  13795: 	    my ($short,@plain)=split(/:/,$configline);
                   13796:             %{$prp{$short}} = ();
                   13797: 	    if (@plain > 0) {
                   13798:                 $prp{$short}{'std'} = $plain[0];
                   13799:                 for (my $i=1; $i<@plain; $i++) {
                   13800:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   13801:                 }
                   13802:             }
1.448     albertel 13803: 	}
1.135     www      13804:     }
1.448     albertel 13805:     close($config);
1.135     www      13806: }
                   13807: 
                   13808: # ---------------------------------------------------------- Read package table
                   13809: {
1.1172.2.96  raeburn  13810:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      13811: 
                   13812:     while (my $configline=<$config>) {
1.483     albertel 13813: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 13814: 	chomp($configline);
                   13815: 	my ($short,$plain)=split(/:/,$configline);
                   13816: 	my ($pack,$name)=split(/\&/,$short);
                   13817: 	if ($plain ne '') {
                   13818: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   13819: 	    $packagetab{$short}=$plain; 
                   13820: 	}
1.11      www      13821:     }
1.448     albertel 13822:     close($config);
1.329     matthew  13823: }
                   13824: 
1.1172.2.27  raeburn  13825: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  13826: 
1.1172.2.27  raeburn  13827: &load_loncaparevs();
                   13828: 
                   13829: # ------------------------------------------------------- Read serverhostID table
                   13830: 
                   13831: &load_serverhomeIDs();
1.1074    raeburn  13832: 
1.1172.2.27  raeburn  13833: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  13834: {
                   13835:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   13836:     if (-e $file) {
                   13837:         my $parser = HTML::LCParser->new($file);
                   13838:         while (my $token = $parser->get_token()) {
                   13839:             if ($token->[0] eq 'S') {
                   13840:                 my $item = $token->[1];
                   13841:                 my $name = $token->[2]{'name'};
                   13842:                 my $value = $token->[2]{'value'};
                   13843:                 if ($item ne '' && $name ne '' && $value ne '') {
                   13844:                     my $release = $parser->get_text();
                   13845:                     $release =~ s/(^\s*|\s*$ )//gx;
                   13846:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   13847:                 }
                   13848:             }
                   13849:         }
                   13850:     }
1.1073    raeburn  13851: }
                   13852: 
1.1138    raeburn  13853: # ---------------------------------------------------------- Read managers table
                   13854: {
                   13855:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96  raeburn  13856:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  13857:             while (my $configline=<$config>) {
                   13858:                 chomp($configline);
                   13859:                 next if ($configline =~ /^\#/);
                   13860:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   13861:                     $managerstab{$configline} = 1;
                   13862:                 }
                   13863:             }
                   13864:             close($config);
                   13865:         }
                   13866:     }
                   13867: }
                   13868: 
1.329     matthew  13869: # ------------- set up temporary directory
                   13870: {
1.1117    foxr     13871:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  13872: 
1.11      www      13873: }
                   13874: 
1.1172.2.104  raeburn  13875: # ------------- set default texengine (domain default overrides this)
                   13876: {
                   13877:     $deftex = LONCAPA::texengine();
                   13878: }
                   13879: 
1.794     albertel 13880: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   13881: 				'compress_threshold'=> 20_000,
                   13882:  			        });
1.185     www      13883: 
1.281     www      13884: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      13885: $dumpcount=0;
1.958     www      13886: $locknum=0;
1.22      www      13887: 
1.163     harris41 13888: &logtouch();
1.672     albertel 13889: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      13890: $readit=1;
1.564     albertel 13891:     {
                   13892: 	use integer;
                   13893: 	my $test=(2**32)+1;
1.568     albertel 13894: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 13895: 	&logthis(" Detected 64bit platform ($_64bit)");
                   13896:     }
1.195     www      13897: }
1.1       albertel 13898: }
1.179     www      13899: 
1.1       albertel 13900: 1;
1.191     harris41 13901: __END__
                   13902: 
1.243     albertel 13903: =pod
                   13904: 
1.191     harris41 13905: =head1 NAME
                   13906: 
1.243     albertel 13907: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 13908: 
                   13909: =head1 SYNOPSIS
                   13910: 
1.243     albertel 13911: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 13912: 
                   13913:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   13914: 
1.243     albertel 13915: Common parameters:
                   13916: 
                   13917: =over 4
                   13918: 
                   13919: =item *
                   13920: 
                   13921: $uname : an internal username (if $cname expecting a course Id specifically)
                   13922: 
                   13923: =item *
                   13924: 
                   13925: $udom : a domain (if $cdom expecting a course's domain specifically)
                   13926: 
                   13927: =item *
                   13928: 
                   13929: $symb : a resource instance identifier
                   13930: 
                   13931: =item *
                   13932: 
                   13933: $namespace : the name of a .db file that contains the data needed or
                   13934: being set.
                   13935: 
                   13936: =back
                   13937: 
1.394     bowersj2 13938: =head1 OVERVIEW
1.191     harris41 13939: 
1.394     bowersj2 13940: lonnet provides subroutines which interact with the
                   13941: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   13942: about classes, users, and resources.
1.243     albertel 13943: 
                   13944: For many of these objects you can also use this to store data about
                   13945: them or modify them in various ways.
1.191     harris41 13946: 
1.394     bowersj2 13947: =head2 Symbs
1.191     harris41 13948: 
1.394     bowersj2 13949: To identify a specific instance of a resource, LON-CAPA uses symbols
                   13950: or "symbs"X<symb>. These identifiers are built from the URL of the
                   13951: map, the resource number of the resource in the map, and the URL of
                   13952: the resource itself. The latter is somewhat redundant, but might help
                   13953: if maps change.
                   13954: 
                   13955: An example is
                   13956: 
                   13957:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   13958: 
                   13959: The respective map entry is
                   13960: 
                   13961:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   13962:   title="Problem 2">
                   13963:  </resource>
                   13964: 
                   13965: Symbs are used by the random number generator, as well as to store and
                   13966: restore data specific to a certain instance of for example a problem.
                   13967: 
                   13968: =head2 Storing And Retrieving Data
                   13969: 
                   13970: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   13971: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   13972: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   13973: is is the non-critical message twin of cstore. These functions are for
                   13974: handlers to store a perl hash to a user's permanent data space in an
                   13975: easy manner, and to retrieve it again on another call. It is expected
                   13976: that a handler would use this once at the beginning to retrieve data,
                   13977: and then again once at the end to send only the new data back.
                   13978: 
                   13979: The data is stored in the user's data directory on the user's
                   13980: homeserver under the ID of the course.
                   13981: 
                   13982: The hash that is returned by restore will have all of the previous
                   13983: value for all of the elements of the hash.
                   13984: 
                   13985: Example:
                   13986: 
                   13987:  #creating a hash
                   13988:  my %hash;
                   13989:  $hash{'foo'}='bar';
                   13990: 
                   13991:  #storing it
                   13992:  &Apache::lonnet::cstore(\%hash);
                   13993: 
                   13994:  #changing a value
                   13995:  $hash{'foo'}='notbar';
                   13996: 
                   13997:  #adding a new value
                   13998:  $hash{'bar'}='foo';
                   13999:  &Apache::lonnet::cstore(\%hash);
                   14000: 
                   14001:  #retrieving the hash
                   14002:  my %history=&Apache::lonnet::restore();
                   14003: 
                   14004:  #print the hash
                   14005:  foreach my $key (sort(keys(%history))) {
                   14006:    print("\%history{$key} = $history{$key}");
                   14007:  }
                   14008: 
                   14009: Will print out:
1.191     harris41 14010: 
1.394     bowersj2 14011:  %history{1:foo} = bar
                   14012:  %history{1:keys} = foo:timestamp
                   14013:  %history{1:timestamp} = 990455579
                   14014:  %history{2:bar} = foo
                   14015:  %history{2:foo} = notbar
                   14016:  %history{2:keys} = foo:bar:timestamp
                   14017:  %history{2:timestamp} = 990455580
                   14018:  %history{bar} = foo
                   14019:  %history{foo} = notbar
                   14020:  %history{timestamp} = 990455580
                   14021:  %history{version} = 2
                   14022: 
                   14023: Note that the special hash entries C<keys>, C<version> and
                   14024: C<timestamp> were added to the hash. C<version> will be equal to the
                   14025: total number of versions of the data that have been stored. The
                   14026: C<timestamp> attribute will be the UNIX time the hash was
                   14027: stored. C<keys> is available in every historical section to list which
                   14028: keys were added or changed at a specific historical revision of a
                   14029: hash.
                   14030: 
                   14031: B<Warning>: do not store the hash that restore returns directly. This
                   14032: will cause a mess since it will restore the historical keys as if the
                   14033: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 14034: 
1.394     bowersj2 14035: Calling convention:
1.191     harris41 14036: 
1.1172.2.27  raeburn  14037:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64  raeburn  14038:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 14039: 
1.394     bowersj2 14040: For more detailed information, see lonnet specific documentation.
1.191     harris41 14041: 
1.394     bowersj2 14042: =head1 RETURN MESSAGES
1.191     harris41 14043: 
1.394     bowersj2 14044: =over 4
1.191     harris41 14045: 
1.394     bowersj2 14046: =item * B<con_lost>: unable to contact remote host
1.191     harris41 14047: 
1.394     bowersj2 14048: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   14049: when the connection is brought back up
1.191     harris41 14050: 
1.394     bowersj2 14051: =item * B<con_failed>: unable to contact remote host and unable to save message
                   14052: for later delivery
1.191     harris41 14053: 
1.967     bisitz   14054: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 14055: 
1.394     bowersj2 14056: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 14057: that was requested
1.191     harris41 14058: 
1.243     albertel 14059: =back
1.191     harris41 14060: 
1.243     albertel 14061: =head1 PUBLIC SUBROUTINES
1.191     harris41 14062: 
1.243     albertel 14063: =head2 Session Environment Functions
1.191     harris41 14064: 
1.243     albertel 14065: =over 4
1.191     harris41 14066: 
1.394     bowersj2 14067: =item * 
                   14068: X<appenv()>
1.949     raeburn  14069: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 14070: the user envirnoment file, and will be restored for each access this
1.620     albertel 14071: user makes during this session, also modifies the %env for the current
1.949     raeburn  14072: process. Optional rolesarrayref - if defined contains a reference to an array
                   14073: of roles which are exempt from the restriction on modifying user.role entries 
                   14074: in the user's environment.db and in %env.    
1.191     harris41 14075: 
                   14076: =item *
1.394     bowersj2 14077: X<delenv()>
1.987     raeburn  14078: B<delenv($delthis,$regexp)>: removes all items from the session
                   14079: environment file that begin with $delthis. If the 
                   14080: optional second arg - $regexp - is true, $delthis is treated as a 
                   14081: regular expression, otherwise \Q$delthis\E is used. 
                   14082: The values are also deleted from the current processes %env.
1.191     harris41 14083: 
1.795     albertel 14084: =item * get_env_multiple($name) 
                   14085: 
                   14086: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   14087: values may be defined and end up as an array ref.
                   14088: 
                   14089: returns an array of values
                   14090: 
1.243     albertel 14091: =back
                   14092: 
                   14093: =head2 User Information
1.191     harris41 14094: 
1.243     albertel 14095: =over 4
1.191     harris41 14096: 
                   14097: =item *
1.394     bowersj2 14098: X<queryauthenticate()>
                   14099: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 14100: authentication scheme
                   14101: 
                   14102: =item *
1.394     bowersj2 14103: X<authenticate()>
1.1073    raeburn  14104: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 14105: authenticate user from domain's lib servers (first use the current
                   14106: one). C<$upass> should be the users password.
1.1073    raeburn  14107: $checkdefauth is optional (value is 1 if a check should be made to
                   14108:    authenticate user using default authentication method, and allow
                   14109:    account creation if username does not have account in the domain).
                   14110: $clientcancheckhost is optional (value is 1 if checking whether the
                   14111:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 14112: 
                   14113: =item *
1.394     bowersj2 14114: X<homeserver()>
                   14115: B<homeserver($uname,$udom)>: find the server which has
                   14116: the user's directory and files (there must be only one), this caches
                   14117: the answer, and also caches if there is a borken connection.
1.191     harris41 14118: 
                   14119: =item *
1.394     bowersj2 14120: X<idget()>
                   14121: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   14122: (IDs are a unique resource in a domain, there must be only 1 ID per
                   14123: username, and only 1 username per ID in a specific domain) (returns
                   14124: hash: id=>name,id=>name)
1.191     harris41 14125: 
                   14126: =item *
1.394     bowersj2 14127: X<idrget()>
                   14128: B<idrget($udom,@unames)>: find the IDs behind a list of
                   14129: usernames (returns hash: name=>id,name=>id)
1.191     harris41 14130: 
                   14131: =item *
1.394     bowersj2 14132: X<idput()>
                   14133: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 14134: 
                   14135: =item *
1.394     bowersj2 14136: X<rolesinit()>
1.1169    droeschl 14137: B<rolesinit($udom,$username)>: get user privileges.
                   14138: returns user role, first access and timer interval hashes
1.243     albertel 14139: 
                   14140: =item *
1.1171    droeschl 14141: X<privileged()>
                   14142: B<privileged($username,$domain)>: returns a true if user has a
                   14143: privileged and active role (i.e. su or dc), false otherwise.
                   14144: 
                   14145: =item *
1.551     albertel 14146: X<getsection()>
                   14147: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 14148: course $cname, return section name/number or '' for "not in course"
                   14149: and '-1' for "no section"
                   14150: 
                   14151: =item *
1.394     bowersj2 14152: X<userenvironment()>
                   14153: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 14154: passed in @what from the requested user's environment, returns a hash
                   14155: 
1.858     raeburn  14156: =item * 
                   14157: X<userlog_query()>
1.859     albertel 14158: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   14159: activity.log file. %filters defines filters applied when parsing the
                   14160: log file. These can be start or end timestamps, or the type of action
                   14161: - log to look for Login or Logout events, check for Checkin or
                   14162: Checkout, role for role selection. The response is in the form
                   14163: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   14164: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  14165: 
1.243     albertel 14166: =back
                   14167: 
                   14168: =head2 User Roles
                   14169: 
                   14170: =over 4
                   14171: 
                   14172: =item *
                   14173: 
1.1172.2.65  raeburn  14174: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   14175: returns codes for allowed actions.
                   14176: 
                   14177: The first argument is required, all others are optional.
                   14178: 
                   14179: $priv is the privilege being checked.
                   14180: $uri contains additional information about what is being checked for access (e.g.,
                   14181: URL, course ID etc.).
                   14182: $symb is the unique resource instance identifier in a course; if needed,
                   14183: but not provided, it will be retrieved via a call to &symbread().
                   14184: $role is the role for which a priv is being checked (only used if priv is evb).
                   14185: $clientip is the user's IP address (only used when checking for access to portfolio
                   14186: files).
                   14187: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
                   14188: prevents recursive calls to &allowed.
                   14189: 
1.243     albertel 14190:  F: full access
                   14191:  U,I,K: authentication modes (cxx only)
                   14192:  '': forbidden
                   14193:  1: user needs to choose course
                   14194:  2: browse allowed
1.766     albertel 14195:  A: passphrase authentication needed
1.1172.2.65  raeburn  14196:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 14197: 
                   14198: =item *
                   14199: 
1.1172.2.13  raeburn  14200: constructaccess($url,$setpriv) : check for access to construction space URL
                   14201: 
                   14202: See if the owner domain and name in the URL match those in the
                   14203: expected environment.  If so, return three element list
                   14204: ($ownername,$ownerdomain,$ownerhome).
                   14205: 
                   14206: Otherwise return the null string.
                   14207: 
                   14208: If second argument 'setpriv' is true, it assigns the privileges,
                   14209: and returns the same three element list, unless the owner has
                   14210: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   14211: in which case the null string is returned.
                   14212: 
                   14213: =item *
                   14214: 
1.1172.2.84  raeburn  14215: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   14216: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   14217: for system, domain, and course level. $uname and $udom are optional (current
                   14218: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 14219: 
                   14220: =item *
                   14221: 
1.988     raeburn  14222: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   14223: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  14224: $type is Course (default) or Community.
1.988     raeburn  14225: If $forcedefault evaluates to true, text returned will be default 
                   14226: text for $type. Otherwise, if this is a course, the text returned 
                   14227: will be a custom name for the role (if defined in the course's 
                   14228: environment).  If no custom name is defined the default is returned.
                   14229:    
1.832     raeburn  14230: =item *
                   14231: 
1.1172.2.23  raeburn  14232: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  14233: All arguments are optional. Returns a hash of a roles, either for
                   14234: co-author/assistant author roles for a user's Construction Space
1.906     albertel 14235: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  14236: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   14237: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   14238: For each key, value is set to colon-separated start and end times for
                   14239: the role.  If no username and domain are specified, will default to
1.934     raeburn  14240: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  14241: of role statuses (active, future or previous), roles 
                   14242: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   14243: to restrict the list of roles reported. If no array ref is 
                   14244: provided for types, will default to return only active roles.
1.834     albertel 14245: 
1.1172.2.13  raeburn  14246: =item *
                   14247: 
                   14248: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   14249: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   14250: 
                   14251: Additional optional arguments are: $type (if role checking is to be restricted
                   14252: to certain user status types -- previous (expired roles), active (currently
                   14253: available roles) or future (roles available in the future), and
                   14254: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  14255: have active Domain Coordinator role in course's domain or in additional
                   14256: domains (specified in 'Domains to check for privileged users' in course
                   14257: environment -- set via:  Course Settings -> Classlists and staff listing).
                   14258: 
                   14259: =item *
                   14260: 
                   14261: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   14262: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   14263: $possdomains and $possroles are optional array refs -- to domains to check and
                   14264: roles to check.  If $possdomains is not specified, a dump will be done of the
                   14265: users' roles.db to check for a dc or su role in any domain. This can be
                   14266: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   14267: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   14268: this then allows &privileged_by_domain() to be used, which caches the identity
                   14269: of privileged users, eliminating the need for repeated calls to &dump().
                   14270: 
                   14271: =item *
                   14272: 
                   14273: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   14274: where the outer hash keys are domains specified in the $possdomains array ref,
                   14275: next inner hash keys are privileged roles specified in the $roles array ref,
                   14276: and the innermost hash contains key = value pairs for username:domain = end:start
                   14277: for active or future "privileged" users with that role in that domain. To avoid
                   14278: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   14279: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  14280: 
1.243     albertel 14281: =back
                   14282: 
                   14283: =head2 User Modification
                   14284: 
                   14285: =over 4
                   14286: 
                   14287: =item *
                   14288: 
1.957     raeburn  14289: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 14290: user for the level given by URL.  Optional start and end dates (leave empty
                   14291: string or zero for "no date")
1.191     harris41 14292: 
                   14293: =item *
                   14294: 
1.243     albertel 14295: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   14296: change a users, password, possible return values are: ok,
                   14297: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   14298: refused
1.191     harris41 14299: 
                   14300: =item *
                   14301: 
1.243     albertel 14302: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 14303: 
                   14304: =item *
                   14305: 
1.1058    raeburn  14306: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   14307:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   14308: 
                   14309: will update user information (firstname,middlename,lastname,generation,
                   14310: permanentemail), and if forceid is true, student/employee ID also.
                   14311: A user's institutional affiliation(s) can also be updated.
                   14312: User information fields will not be overwritten with empty entries 
                   14313: unless the field is included in the $candelete array reference.
                   14314: This array is included when a single user is modified via "Manage Users",
                   14315: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 14316: 
                   14317: =item *
                   14318: 
1.286     matthew  14319: modifystudent
                   14320: 
1.957     raeburn  14321: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  14322: The course id is resolved based on the current user's environment.  
                   14323: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  14324: associated with a course.
                   14325: 
1.297     matthew  14326: This call is essentially a wrapper for lonnet::modifyuser and
                   14327: lonnet::modify_student_enrollment
1.286     matthew  14328: 
                   14329: Inputs: 
                   14330: 
                   14331: =over 4
                   14332: 
1.957     raeburn  14333: =item B<$udom> Student's loncapa domain
1.286     matthew  14334: 
1.957     raeburn  14335: =item B<$uname> Student's loncapa login name
1.286     matthew  14336: 
1.964     bisitz   14337: =item B<$uid> Student/Employee ID
1.286     matthew  14338: 
1.957     raeburn  14339: =item B<$umode> Student's authentication mode
1.286     matthew  14340: 
1.957     raeburn  14341: =item B<$upass> Student's password
1.286     matthew  14342: 
1.957     raeburn  14343: =item B<$first> Student's first name
1.286     matthew  14344: 
1.957     raeburn  14345: =item B<$middle> Student's middle name
1.286     matthew  14346: 
1.957     raeburn  14347: =item B<$last> Student's last name
1.286     matthew  14348: 
1.957     raeburn  14349: =item B<$gene> Student's generation
1.286     matthew  14350: 
1.957     raeburn  14351: =item B<$usec> Student's section in course
1.286     matthew  14352: 
                   14353: =item B<$end> Unix time of the roles expiration
                   14354: 
                   14355: =item B<$start> Unix time of the roles start date
                   14356: 
                   14357: =item B<$forceid> If defined, allow $uid to be changed
                   14358: 
                   14359: =item B<$desiredhome> server to use as home server for student
                   14360: 
1.957     raeburn  14361: =item B<$email> Student's permanent e-mail address
                   14362: 
                   14363: =item B<$type> Type of enrollment (auto or manual)
                   14364: 
1.963     raeburn  14365: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   14366: 
                   14367: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  14368: 
1.963     raeburn  14369: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  14370: 
1.963     raeburn  14371: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  14372: 
1.1172.2.19  raeburn  14373: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   14374: 
                   14375: =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  14376: 
1.286     matthew  14377: =back
1.297     matthew  14378: 
                   14379: =item *
                   14380: 
                   14381: modify_student_enrollment
                   14382: 
1.1172.2.31  raeburn  14383: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  14384: 'role.request.course' must be defined for this function to proceed.
                   14385: 
                   14386: Inputs:
                   14387: 
                   14388: =over 4
                   14389: 
1.1172.2.31  raeburn  14390: =item $udom, student's domain
1.297     matthew  14391: 
1.1172.2.31  raeburn  14392: =item $uname, student's name
1.297     matthew  14393: 
1.1172.2.31  raeburn  14394: =item $uid, student's user id
1.297     matthew  14395: 
1.1172.2.31  raeburn  14396: =item $first, student's first name
1.297     matthew  14397: 
                   14398: =item $middle
                   14399: 
                   14400: =item $last
                   14401: 
                   14402: =item $gene
                   14403: 
                   14404: =item $usec
                   14405: 
                   14406: =item $end
                   14407: 
                   14408: =item $start
                   14409: 
1.957     raeburn  14410: =item $type
                   14411: 
                   14412: =item $locktype
                   14413: 
                   14414: =item $cid
                   14415: 
                   14416: =item $selfenroll
                   14417: 
                   14418: =item $context
                   14419: 
1.1172.2.19  raeburn  14420: =item $credits, number of credits student will earn from this class
                   14421: 
1.1172.2.76  raeburn  14422: =item $instsec, institutional course section code for student
                   14423: 
1.297     matthew  14424: =back
                   14425: 
1.191     harris41 14426: 
                   14427: =item *
                   14428: 
1.243     albertel 14429: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   14430: custom role; give a custom role to a user for the level given by URL.  Specify
                   14431: name and domain of role author, and role name
1.191     harris41 14432: 
                   14433: =item *
                   14434: 
1.243     albertel 14435: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 14436: 
                   14437: =item *
                   14438: 
1.243     albertel 14439: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   14440: 
                   14441: =back
                   14442: 
                   14443: =head2 Course Infomation
                   14444: 
                   14445: =over 4
1.191     harris41 14446: 
                   14447: =item *
                   14448: 
1.1118    foxr     14449: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 14450: specified course id, including all environment settings for the
                   14451: course, the description of the course will be in the hash under the
                   14452: key 'description'
1.191     harris41 14453: 
1.1118    foxr     14454: $options is an optional parameter that if supplied is a hash reference that controls
                   14455: what how this function works.  It has the following key/values:
                   14456: 
                   14457: =over 4
                   14458: 
                   14459: =item freshen_cache
                   14460: 
                   14461: If defined, and the environment cache for the course is valid, it is 
                   14462: returned in the returned hash.
                   14463: 
                   14464: =item one_time
                   14465: 
                   14466: If defined, the last cache time is set to _now_
                   14467: 
                   14468: =item user
                   14469: 
                   14470: If defined, the supplied username is used instead of the current user.
                   14471: 
                   14472: 
                   14473: =back
                   14474: 
1.191     harris41 14475: =item *
                   14476: 
1.624     albertel 14477: resdata($name,$domain,$type,@which) : request for current parameter
                   14478: setting for a specific $type, where $type is either 'course' or 'user',
                   14479: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  14480: answers for 10 minutes.
1.243     albertel 14481: 
1.877     foxr     14482: =item *
                   14483: 
                   14484: get_courseresdata($courseid, $domain) : dump the entire course resource
                   14485: data base, returning a hash that is keyed by the resource name and has
                   14486: values that are the resource value.  I believe that the timestamps and
                   14487: versions are also returned.
                   14488: 
1.1172.2.31  raeburn  14489: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   14490: supplemental content area. This routine caches the number of files for
                   14491: 10 minutes.
                   14492: 
1.243     albertel 14493: =back
                   14494: 
                   14495: =head2 Course Modification
                   14496: 
                   14497: =over 4
1.191     harris41 14498: 
                   14499: =item *
                   14500: 
1.243     albertel 14501: writecoursepref($courseid,%prefs) : write preferences (environment
                   14502: database) for a course
1.191     harris41 14503: 
                   14504: =item *
                   14505: 
1.1011    raeburn  14506: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   14507: 
                   14508: =item *
                   14509: 
1.1038    raeburn  14510: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 14511: 
1.1167    droeschl 14512: =item *
                   14513: 
                   14514: is_course($courseid), is_course($cdom, $cnum)
                   14515: 
                   14516: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   14517: two component version $cdom, $cnum. It checks if the specified course exists.
                   14518: 
                   14519: Returns:
                   14520:     undef if the course doesn't exist, otherwise
                   14521:     in scalar context the combined courseid.
                   14522:     in list context the two components of the course identifier, domain and 
                   14523:     courseid.    
                   14524: 
1.243     albertel 14525: =back
                   14526: 
1.1172.2.109! raeburn  14527: =head2 Bubblesheet Configuration
        !          14528: 
        !          14529: =over 4
        !          14530: 
        !          14531: =item *
        !          14532: 
        !          14533: get_scantron_config($which)
        !          14534: 
        !          14535: $which - the name of the configuration to parse from the file.
        !          14536: 
        !          14537: Parses and returns the bubblesheet configuration line selected as a
        !          14538: hash of configuration file fields.
        !          14539: 
        !          14540: 
        !          14541: Returns:
        !          14542:     If the named configuration is not in the file, an empty
        !          14543:     hash is returned.
        !          14544: 
        !          14545:     a hash with the fields
        !          14546:       name         - internal name for the this configuration setup
        !          14547:       description  - text to display to operator that describes this config
        !          14548:       CODElocation - if 0 or the string 'none'
        !          14549:                           - no CODE exists for this config
        !          14550:                      if -1 || the string 'letter'
        !          14551:                           - a CODE exists for this config and is
        !          14552:                             a string of letters
        !          14553:                      Unsupported value (but planned for future support)
        !          14554:                           if a positive integer
        !          14555:                                - The CODE exists as the first n items from
        !          14556:                                  the question section of the form
        !          14557:                           if the string 'number'
        !          14558:                                - The CODE exists for this config and is
        !          14559:                                  a string of numbers
        !          14560:       CODEstart   - (only matter if a CODE exists) column in the line where
        !          14561:                      the CODE starts
        !          14562:       CODElength  - length of the CODE
        !          14563:       IDstart     - column where the student/employee ID starts
        !          14564:       IDlength    - length of the student/employee ID info
        !          14565:       Qstart      - column where the information from the bubbled
        !          14566:                     'questions' start
        !          14567:       Qlength     - number of columns comprising a single bubble line from
        !          14568:                     the sheet. (usually either 1 or 10)
        !          14569:       Qon         - either a single character representing the character used
        !          14570:                     to signal a bubble was chosen in the positional setup, or
        !          14571:                     the string 'letter' if the letter of the chosen bubble is
        !          14572:                     in the final, or 'number' if a number representing the
        !          14573:                     chosen bubble is in the file (1->A 0->J)
        !          14574:       Qoff        - the character used to represent that a bubble was
        !          14575:                     left blank
        !          14576:       PaperID     - if the scanning process generates a unique number for each
        !          14577:                     sheet scanned the column that this ID number starts in
        !          14578:       PaperIDlength - number of columns that comprise the unique ID number
        !          14579:                       for the sheet of paper
        !          14580:       FirstName   - column that the first name starts in
        !          14581:       FirstNameLength - number of columns that the first name spans
        !          14582:       LastName    - column that the last name starts in
        !          14583:       LastNameLength - number of columns that the last name spans
        !          14584:       BubblesPerRow - number of bubbles available in each row used to
        !          14585:                       bubble an answer. (If not specified, 10 assumed).
        !          14586: 
        !          14587: 
        !          14588: =item *
        !          14589: 
        !          14590: get_scantronformat_file($cdom)
        !          14591: 
        !          14592: $cdom - the course's domain (optional); if not supplied, uses
        !          14593: domain for current $env{'request.course.id'}.
        !          14594: 
        !          14595: Returns an array containing lines from the scantron format file for
        !          14596: the domain of the course.
        !          14597: 
        !          14598: If a url for a custom.tab file is listed in domain's configuration.db,
        !          14599: lines are from this file.
        !          14600: 
        !          14601: Otherwise, if a default.tab has been published in RES space by the
        !          14602: domainconfig user, lines are from this file.
        !          14603: 
        !          14604: Otherwise, fall back to getting lines from the legacy file on the
        !          14605: local server:  /home/httpd/lonTabs/default_scantronformat.tab
        !          14606: 
        !          14607: =back
        !          14608: 
1.243     albertel 14609: =head2 Resource Subroutines
                   14610: 
                   14611: =over 4
1.191     harris41 14612: 
                   14613: =item *
                   14614: 
1.243     albertel 14615: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 14616: 
                   14617: =item *
                   14618: 
1.243     albertel 14619: repcopy($filename) : subscribes to the requested file, and attempts to
                   14620: replicate from the owning library server, Might return
1.607     raeburn  14621: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   14622: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 14623: resource. Expects the local filesystem pathname
                   14624: (/home/httpd/html/res/....)
                   14625: 
                   14626: =back
                   14627: 
                   14628: =head2 Resource Information
                   14629: 
                   14630: =over 4
1.191     harris41 14631: 
                   14632: =item *
                   14633: 
1.1172.2.28  raeburn  14634: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   14635: and returns the value of a variety of different possible values,
                   14636: $varname should be a request string, and the other parameters can be
                   14637: used to specify who and what one is asking about. Ordinarily, $cid 
                   14638: does not need to be specified, as it is retrived from 
                   14639: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   14640: within lonuserstate::loadmap() when initializing a course, before
                   14641: $env{'request.course.id'} has been set, so it needs to be provided
                   14642: in that one case.
1.243     albertel 14643: 
                   14644: Possible values for $varname are environment.lastname (or other item
                   14645: from the envirnment hash), user.name (or someother aspect about the
                   14646: user), resource.0.maxtries (or some other part and parameter of a
                   14647: resource)
1.204     albertel 14648: 
                   14649: =item *
                   14650: 
1.243     albertel 14651: directcondval($number) : get current value of a condition; reads from a state
                   14652: string
1.204     albertel 14653: 
                   14654: =item *
                   14655: 
1.243     albertel 14656: condval($condidx) : value of condition index based on state
1.204     albertel 14657: 
                   14658: =item *
                   14659: 
1.243     albertel 14660: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   14661: resource's metadata, $what should be either a specific key, or either
                   14662: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   14663: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   14664: 
                   14665: this function automatically caches all requests
1.191     harris41 14666: 
                   14667: =item *
                   14668: 
1.243     albertel 14669: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   14670: network of library servers; returns file handle of where SQL and regex results
                   14671: will be stored for query
1.191     harris41 14672: 
                   14673: =item *
                   14674: 
1.1172.2.66  raeburn  14675: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
                   14676: return symbolic list entry (all arguments optional).
                   14677: 
                   14678: Args: filename is the filename (including path) for the file for which a symb
                   14679: is required; donotrecurse, if true will prevent calls to allowed() being made
                   14680: to check access status if more than one resource was found in the bighash
                   14681: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
                   14682: a randompick); ignorecachednull, if true will prevent a symb of '' being
                   14683: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   14684: cause possible symbs to be checked to determine if they are subject to content
                   14685: blocking, if so they will not be included as possible symbs; possibles is a
                   14686: ref to a hash, which, as a side effect, will be populated with all possible
                   14687: symbs (content blocking not tested).
                   14688: 
1.243     albertel 14689: returns the data handle
1.191     harris41 14690: 
                   14691: =item *
                   14692: 
1.1172.2.17  raeburn  14693: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  14694: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 14695: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  14696: on failure, user must be in a course, as it assumes the existence of
                   14697: the course initial hash, and uses $env('request.course.id'}.  The third
                   14698: arg is an optional reference to a scalar.  If this arg is passed in the
                   14699: call to symbverify, it will be set to 1 if the symb has been set to be 
                   14700: encrypted; otherwise it will be null.
1.243     albertel 14701: 
1.191     harris41 14702: =item *
                   14703: 
1.243     albertel 14704: symbclean($symb) : removes versions numbers from a symb, returns the
                   14705: cleaned symb
1.191     harris41 14706: 
                   14707: =item *
                   14708: 
1.243     albertel 14709: is_on_map($uri) : checks if the $uri is somewhere on the current
                   14710: course map, user must be in a course for it to work.
1.191     harris41 14711: 
                   14712: =item *
                   14713: 
1.243     albertel 14714: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 14715: 
                   14716: =item *
                   14717: 
1.243     albertel 14718: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   14719: a random seed, all arguments are optional, if they aren't sent it uses the
                   14720: environment to derive them. Note: if symb isn't sent and it can't get one
                   14721: from &symbread it will use the current time as its return value
1.191     harris41 14722: 
                   14723: =item *
                   14724: 
1.243     albertel 14725: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   14726: unfakeable, receipt
1.191     harris41 14727: 
                   14728: =item *
                   14729: 
1.620     albertel 14730: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 14731: 
                   14732: =item *
                   14733: 
1.243     albertel 14734: countacc($url) : count the number of accesses to a given URL
1.191     harris41 14735: 
                   14736: =item *
                   14737: 
1.243     albertel 14738: 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 14739: 
                   14740: =item *
                   14741: 
1.243     albertel 14742: 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 14743: 
                   14744: =item *
                   14745: 
1.243     albertel 14746: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 14747: 
                   14748: =item *
                   14749: 
1.243     albertel 14750: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   14751: forcing spreadsheet to reevaluate the resource scores next time.
                   14752: 
1.1172.2.13  raeburn  14753: =item *
                   14754: 
                   14755: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   14756: when viewing in course context.
                   14757: 
                   14758:  input: six args -- filename (decluttered), course number, course domain,
                   14759:                     url, symb (if registered) and group (if this is a
                   14760:                     group item -- e.g., bulletin board, group page etc.).
                   14761: 
                   14762:  output: array of five scalars --
                   14763:          $cfile -- url for file editing if editable on current server
                   14764:          $home -- homeserver of resource (i.e., for author if published,
                   14765:                                           or course if uploaded.).
                   14766:          $switchserver --  1 if server switch will be needed.
                   14767:          $forceedit -- 1 if icon/link should be to go to edit mode
                   14768:          $forceview -- 1 if icon/link should be to go to view mode
                   14769: 
                   14770: =item *
                   14771: 
                   14772: is_course_upload($file,$cnum,$cdom)
                   14773: 
                   14774: Used in course context to determine if current file was uploaded to
                   14775: the course (i.e., would be found in /userfiles/docs on the course's
                   14776: homeserver.
                   14777: 
                   14778:   input: 3 args -- filename (decluttered), course number and course domain.
                   14779:   output: boolean -- 1 if file was uploaded.
                   14780: 
1.243     albertel 14781: =back
                   14782: 
                   14783: =head2 Storing/Retreiving Data
                   14784: 
                   14785: =over 4
1.191     harris41 14786: 
                   14787: =item *
                   14788: 
1.1172.2.64  raeburn  14789: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
                   14790: permanently for this url; hashref needs to be given and should be a \%hashname;
                   14791: the remaining args aren't required and if they aren't passed or are '' they will
                   14792: be derived from the env (with the exception of $laststore, which is an
                   14793: optional arg used when a user's submission is stored in grading).
                   14794: $laststore is $version=$timestamp, where $version is the most recent version
                   14795: number retrieved for the corresponding $symb in the $namespace db file, and
                   14796: $timestamp is the timestamp for that transaction (UNIX time).
                   14797: $laststore is currently only passed when cstore() is called by
                   14798: structuretags::finalize_storage().
1.191     harris41 14799: 
                   14800: =item *
                   14801: 
1.1172.2.64  raeburn  14802: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
                   14803: but uses critical subroutine
1.191     harris41 14804: 
                   14805: =item *
                   14806: 
1.243     albertel 14807: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   14808: all args are optional
1.191     harris41 14809: 
                   14810: =item *
                   14811: 
1.717     albertel 14812: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   14813: dumps the complete (or key matching regexp) namespace into a hash
                   14814: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   14815: normally &store()ed into
                   14816: 
                   14817: $range should be either an integer '100' (give me the first 100
                   14818:                                            matching records)
                   14819:               or be  two integers sperated by a - with no spaces
                   14820:                  '30-50' (give me the 30th through the 50th matching
                   14821:                           records)
                   14822: 
                   14823: 
                   14824: =item *
                   14825: 
1.1172.2.59  raeburn  14826: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 14827: replaces a &store() version of data with a replacement set of data
                   14828: for a particular resource in a namespace passed in the $storehash hash 
1.1172.2.59  raeburn  14829: reference. If $tolog is true, the transaction is logged in the courselog
                   14830: with an action=PUTSTORE.
1.717     albertel 14831: 
                   14832: =item *
                   14833: 
1.243     albertel 14834: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   14835: works very similar to store/cstore, but all data is stored in a
                   14836: temporary location and can be reset using tmpreset, $storehash should
                   14837: be a hash reference, returns nothing on success
1.191     harris41 14838: 
                   14839: =item *
                   14840: 
1.243     albertel 14841: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   14842: similar to restore, but all data is stored in a temporary location and
                   14843: can be reset using tmpreset. Returns a hash of values on success,
                   14844: error string otherwise.
1.191     harris41 14845: 
                   14846: =item *
                   14847: 
1.243     albertel 14848: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   14849: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 14850: 
                   14851: =item *
                   14852: 
1.243     albertel 14853: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14854: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 14855: 
                   14856: =item *
                   14857: 
1.243     albertel 14858: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   14859: namesp ($udom and $uname are optional)
1.191     harris41 14860: 
                   14861: =item *
                   14862: 
1.702     albertel 14863: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 14864: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 14865: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  14866: 
1.702     albertel 14867: $range should be either an integer '100' (give me the first 100
                   14868:                                            matching records)
                   14869:               or be  two integers sperated by a - with no spaces
                   14870:                  '30-50' (give me the 30th through the 50th matching
                   14871:                           records)
1.449     matthew  14872: =item *
                   14873: 
                   14874: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   14875: $store can be a scalar, an array reference, or if the amount to be 
                   14876: incremented is > 1, a hash reference.
                   14877: 
                   14878: ($udom and $uname are optional)
1.191     harris41 14879: 
                   14880: =item *
                   14881: 
1.243     albertel 14882: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   14883: ($udom and $uname are optional)
1.191     harris41 14884: 
                   14885: =item *
                   14886: 
1.243     albertel 14887: cput($namespace,$storehash,$udom,$uname) : critical put
                   14888: ($udom and $uname are optional)
1.191     harris41 14889: 
                   14890: =item *
                   14891: 
1.748     albertel 14892: newput($namespace,$storehash,$udom,$uname) :
                   14893: 
                   14894: Attempts to store the items in the $storehash, but only if they don't
                   14895: currently exist, if this succeeds you can be certain that you have 
                   14896: successfully created a new key value pair in the $namespace db.
                   14897: 
                   14898: 
                   14899: Args:
                   14900:  $namespace: name of database to store values to
                   14901:  $storehash: hashref to store to the db
                   14902:  $udom: (optional) domain of user containing the db
                   14903:  $uname: (optional) name of user caontaining the db
                   14904: 
                   14905: Returns:
                   14906:  'ok' -> succeeded in storing all keys of $storehash
                   14907:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   14908:                         least <key> already existed in the db (other
                   14909:                         requested keys may also already exist)
1.967     bisitz   14910:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 14911:  'con_lost' -> unable to contact request server
                   14912:  'refused' -> action was not allowed by remote machine
                   14913: 
                   14914: 
                   14915: =item *
                   14916: 
1.243     albertel 14917: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14918: reference filled in from namesp (encrypts the return communication)
                   14919: ($udom and $uname are optional)
1.191     harris41 14920: 
                   14921: =item *
                   14922: 
1.243     albertel 14923: log($udom,$name,$home,$message) : write to permanent log for user; use
                   14924: critical subroutine
                   14925: 
1.806     raeburn  14926: =item *
                   14927: 
1.860     raeburn  14928: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   14929: array reference filled in from namespace found in domain level on either
                   14930: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  14931: 
                   14932: =item *
                   14933: 
1.860     raeburn  14934: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   14935: domain level either on specified domain server ($uhome) or primary domain 
                   14936: server ($udom and $uhome are optional)
1.806     raeburn  14937: 
1.943     raeburn  14938: =item * 
                   14939: 
1.1172.2.35  raeburn  14940: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
                   14941: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   14942: the target domain.
                   14943: 
                   14944: May also include additional key => value pairs for the following groups:
                   14945: 
                   14946: =over
                   14947: 
                   14948: =item
                   14949: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   14950: 
                   14951: =over
                   14952: 
                   14953: =item defaultquota, authorquota
                   14954: 
                   14955: =back
                   14956: 
                   14957: =item
                   14958: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   14959: portfolio for users).
                   14960: 
                   14961: =over
                   14962: 
                   14963: =item
                   14964: aboutme, blog, webdav, portfolio
                   14965: 
                   14966: =back
                   14967: 
                   14968: =item
                   14969: requestcourses: ability to request courses, and how requests are processed.
                   14970: 
                   14971: =over
                   14972: 
                   14973: =item
1.1172.2.37  raeburn  14974: official, unofficial, community, textbook
1.1172.2.35  raeburn  14975: 
                   14976: =back
                   14977: 
                   14978: =item
                   14979: inststatus: types of institutional affiliation, and order in which they are displayed.
                   14980: 
                   14981: =over
                   14982: 
                   14983: =item
1.1172.2.44  raeburn  14984: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35  raeburn  14985: 
                   14986: =back
                   14987: 
                   14988: =item
                   14989: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   14990: for course's uploaded content.
                   14991: 
                   14992: =over
                   14993: 
                   14994: =item
1.1172.2.68  raeburn  14995: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
                   14996: communityquota, textbookquota
1.1172.2.35  raeburn  14997: 
                   14998: =back
                   14999: 
                   15000: =item
                   15001: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   15002: on your servers.
                   15003: 
                   15004: =over
                   15005: 
                   15006: =item
                   15007: remotesessions, hostedsessions
                   15008: 
                   15009: =back
                   15010: 
                   15011: =back
                   15012: 
                   15013: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   15014: utility to create a configuration.db file on a domain's primary library server
                   15015: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   15016: -- corresponding values are authentication type (internal, krb4, krb5,
                   15017: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
                   15018: will be available. Values are retrieved from cache (if current), unless the
                   15019: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   15020: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   15021: 
                   15022: Typical usage:
1.943     raeburn  15023: 
1.1172.2.35  raeburn  15024: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  15025: 
1.243     albertel 15026: =back
                   15027: 
                   15028: =head2 Network Status Functions
                   15029: 
                   15030: =over 4
1.191     harris41 15031: 
                   15032: =item *
                   15033: 
1.1137    raeburn  15034: dirlist() : return directory list based on URI (first arg).
                   15035: 
                   15036: Inputs: 1 required, 5 optional.
                   15037: 
                   15038: =over
                   15039: 
                   15040: =item 
                   15041: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   15042: 
                   15043: =item
                   15044: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   15045: 
                   15046: =item
                   15047: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   15048: 
                   15049: =item
                   15050: $getpropath - boolean: 1 if prepend path using &propath(). 
                   15051: 
                   15052: =item
                   15053: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   15054: 
                   15055: =item 
                   15056: $alternateRoot - path to prepend in place of path from $uri.
                   15057: 
                   15058: =back
                   15059: 
                   15060: Returns: Array of up to two items.
                   15061: 
                   15062: =over
                   15063: 
                   15064: a reference to an array of files/subdirectories
                   15065: 
                   15066: =over
                   15067: 
                   15068: Each element in the array of files/subdirectories is a & separated list of
                   15069: item name and the result of running stat on the item.  If dirlist was requested
                   15070: for a file instead of a directory, the item name will be ''. For a directory 
                   15071: listing, if the item is a metadata file, the element will end &N&M 
                   15072: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   15073: default copyright set (1).  
                   15074: 
                   15075: =back
                   15076: 
                   15077: a scalar containing error condition (if encountered).
                   15078: 
                   15079: =over
                   15080: 
                   15081: =item 
                   15082: no_host (no homeserver identified for $username:$domain).
                   15083: 
                   15084: =item 
                   15085: no_such_host (server contacted for listing not identified as valid host).
                   15086: 
                   15087: =item 
                   15088: con_lost (connection to remote server failed).
                   15089: 
                   15090: =item 
                   15091: refused (invalid $username:$domain received on lond side).
                   15092: 
                   15093: =item 
                   15094: no_such_dir (directory at specified path on lond side does not exist). 
                   15095: 
                   15096: =item 
                   15097: empty (directory at specified path on lond side is empty).
                   15098: 
                   15099: =over
                   15100: 
                   15101: This is currently not encountered because the &ls3, &ls2, 
                   15102: &ls (_handler) routines on the lond side do not filter out
                   15103: . and .. from a directory listing. 
                   15104: 
                   15105: =back
                   15106: 
                   15107: =back
                   15108: 
                   15109: =back
1.191     harris41 15110: 
                   15111: =item *
                   15112: 
1.243     albertel 15113: spareserver() : find server with least workload from spare.tab
                   15114: 
1.986     foxr     15115: 
                   15116: =item *
                   15117: 
                   15118: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   15119: if there is no corresponding loncapa host.
                   15120: 
1.243     albertel 15121: =back
                   15122: 
1.986     foxr     15123: 
1.243     albertel 15124: =head2 Apache Request
                   15125: 
                   15126: =over 4
1.191     harris41 15127: 
                   15128: =item *
                   15129: 
1.243     albertel 15130: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   15131: localhost, posts hash
                   15132: 
                   15133: =back
                   15134: 
                   15135: =head2 Data to String to Data
                   15136: 
                   15137: =over 4
1.191     harris41 15138: 
                   15139: =item *
                   15140: 
1.243     albertel 15141: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   15142: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 15143: 
                   15144: =item *
                   15145: 
1.243     albertel 15146: hashref2str($hashref) : convert a hashref into a string complete with
                   15147: escaping and '=' and '&' separators, supports elements that are
                   15148: arrayrefs and hashrefs
1.191     harris41 15149: 
                   15150: =item *
                   15151: 
1.243     albertel 15152: arrayref2str($arrayref) : convert an arrayref into a string complete
                   15153: with escaping and '&' separators, supports elements that are arrayrefs
                   15154: and hashrefs
1.191     harris41 15155: 
                   15156: =item *
                   15157: 
1.243     albertel 15158: str2hash($string) : convert string to hash using unescaping and
                   15159: splitting on '=' and '&', supports elements that are arrayrefs and
                   15160: hashrefs
1.191     harris41 15161: 
                   15162: =item *
                   15163: 
1.243     albertel 15164: str2array($string) : convert string to hash using unescaping and
                   15165: splitting on '&', supports elements that are arrayrefs and hashrefs
                   15166: 
                   15167: =back
                   15168: 
                   15169: =head2 Logging Routines
                   15170: 
                   15171: 
                   15172: These routines allow one to make log messages in the lonnet.log and
                   15173: lonnet.perm logfiles.
1.191     harris41 15174: 
1.1119    foxr     15175: =over 4
                   15176: 
1.191     harris41 15177: =item *
                   15178: 
1.243     albertel 15179: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 15180: 
                   15181: =item *
                   15182: 
1.243     albertel 15183: logthis() : append message to the normal lonnet.log file, it gets
                   15184: preiodically rolled over and deleted.
1.191     harris41 15185: 
                   15186: =item *
                   15187: 
1.243     albertel 15188: logperm() : append a permanent message to lonnet.perm.log, this log
                   15189: file never gets deleted by any automated portion of the system, only
                   15190: messages of critical importance should go in here.
                   15191: 
1.1119    foxr     15192: 
1.243     albertel 15193: =back
                   15194: 
                   15195: =head2 General File Helper Routines
                   15196: 
                   15197: =over 4
1.191     harris41 15198: 
                   15199: =item *
                   15200: 
1.481     raeburn  15201: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   15202: (a) files in /uploaded
                   15203:   (i) If a local copy of the file exists - 
                   15204:       compares modification date of local copy with last-modified date for 
                   15205:       definitive version stored on home server for course. If local copy is 
                   15206:       stale, requests a new version from the home server and stores it. 
                   15207:       If the original has been removed from the home server, then local copy 
                   15208:       is unlinked.
                   15209:   (ii) If local copy does not exist -
                   15210:       requests the file from the home server and stores it. 
                   15211:   
                   15212:   If $caller is 'uploadrep':  
                   15213:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   15214:     for request for files originally uploaded via DOCS. 
                   15215:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   15216:   
                   15217:   Otherwise:
                   15218:      This indicates a call from the content generation phase of the request.
                   15219:      -  returns the entire contents of the file or -1.
                   15220:      
                   15221: (b) files in /res
                   15222:    - returns the entire contents of a file or -1; 
                   15223:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 15224: 
1.712     albertel 15225: 
                   15226: =item *
                   15227: 
                   15228: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   15229:                   reference
                   15230: 
                   15231: returns either a stat() list of data about the file or an empty list
                   15232: if the file doesn't exist or couldn't find out about it (connection
                   15233: problems or user unknown)
                   15234: 
1.191     harris41 15235: =item *
                   15236: 
1.243     albertel 15237: filelocation($dir,$file) : returns file system location of a file
                   15238: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   15239: directory that relative $file lookups are to looked in ($dir of /a/dir
                   15240: and a file of ../bob will become /a/bob)
1.191     harris41 15241: 
                   15242: =item *
                   15243: 
                   15244: hreflocation($dir,$file) : returns file system location or a URL; same as
                   15245: filelocation except for hrefs
                   15246: 
                   15247: =item *
                   15248: 
1.1172.2.49  raeburn  15249: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   15250: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 15251: 
1.243     albertel 15252: =back
                   15253: 
1.608     albertel 15254: =head2 Usererfile file routines (/uploaded*)
                   15255: 
                   15256: =over 4
                   15257: 
                   15258: =item *
                   15259: 
                   15260: userfileupload(): main rotine for putting a file in a user or course's
                   15261:                   filespace, arguments are,
                   15262: 
1.620     albertel 15263:  formname - required - this is the name of the element in $env where the
1.608     albertel 15264:            filename, and the contents of the file to create/modifed exist
1.620     albertel 15265:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   15266:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  15267:  context - if coursedoc, store the file in the course of the active role
                   15268:              of the current user; 
                   15269:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   15270:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 15271:  subdir - required - subdirectory to put the file in under ../userfiles/
                   15272:          if undefined, it will be placed in "unknown"
                   15273: 
                   15274:  (This routine calls clean_filename() to remove any dangerous
                   15275:  characters from the filename, and then calls finuserfileupload() to
                   15276:  complete the transaction)
                   15277: 
                   15278:  returns either the url of the uploaded file (/uploaded/....) if successful
                   15279:  and /adm/notfound.html if unsuccessful
                   15280: 
                   15281: =item *
                   15282: 
                   15283: clean_filename(): routine for cleaing a filename up for storage in
                   15284:                  userfile space, argument is:
                   15285: 
                   15286:  filename - proposed filename
                   15287: 
                   15288: returns: the new clean filename
                   15289: 
                   15290: =item *
                   15291: 
1.1090    raeburn  15292: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 15293: userspace, probably shouldn't be called directly
                   15294: 
                   15295:   docuname: username or courseid of destination for the file
                   15296:   docudom: domain of user/course of destination for the file
                   15297:   formname: same as for userfileupload()
1.1090    raeburn  15298:   fname: filename (including subdirectories) for the file
                   15299:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1172.2.109! raeburn  15300:           if hashref, and context is scantron, will convert csv format to standard format
1.1090    raeburn  15301:   allfiles: reference to hash used to store objects found by parser
                   15302:   codebase: reference to hash used for codebases of java objects found by parser
                   15303:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   15304:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   15305:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   15306:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   15307:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   15308:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  15309:   mimetype: reference to scalar to accommodate mime type determined
                   15310:             from File::MMagic if $parser = parse.
1.608     albertel 15311: 
                   15312:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  15313:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   15314:  was 'overwrite').
                   15315:  
1.608     albertel 15316: 
                   15317: =item *
                   15318: 
                   15319: renameuserfile(): renames an existing userfile to a new name
                   15320: 
                   15321:   Args:
                   15322:    docuname: username or courseid of destination for the file
                   15323:    docudom: domain of user/course of destination for the file
                   15324:    old: current file name (including any subdirs under userfiles)
                   15325:    new: desired file name (including any subdirs under userfiles)
                   15326: 
                   15327: =item *
                   15328: 
                   15329: mkdiruserfile(): creates a directory is a userfiles dir
                   15330: 
                   15331:   Args:
                   15332:    docuname: username or courseid of destination for the file
                   15333:    docudom: domain of user/course of destination for the file
                   15334:    dir: dir to create (including any subdirs under userfiles)
                   15335: 
                   15336: =item *
                   15337: 
                   15338: removeuserfile(): removes a file that exists in userfiles
                   15339: 
                   15340:   Args:
                   15341:    docuname: username or courseid of destination for the file
                   15342:    docudom: domain of user/course of destination for the file
                   15343:    fname: filname to delete (including any subdirs under userfiles)
                   15344: 
                   15345: =item *
                   15346: 
                   15347: removeuploadedurl(): convience function for removeuserfile()
                   15348: 
                   15349:   Args:
                   15350:    url:  a full /uploaded/... url to delete
                   15351: 
1.747     albertel 15352: =item * 
                   15353: 
                   15354: get_portfile_permissions():
                   15355:   Args:
                   15356:     domain: domain of user or course contain the portfolio files
                   15357:     user: name of user or num of course contain the portfolio files
                   15358:   Returns:
                   15359:     hashref of a dump of the proper file_permissions.db
                   15360:    
                   15361: 
                   15362: =item * 
                   15363: 
                   15364: get_access_controls():
                   15365: 
                   15366: Args:
                   15367:   current_permissions: the hash ref returned from get_portfile_permissions()
                   15368:   group: (optional) the group you want the files associated with
                   15369:   file: (optional) the file you want access info on
                   15370: 
                   15371: Returns:
1.749     raeburn  15372:     a hash (keys are file names) of hashes containing
                   15373:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   15374:         values are XML containing access control settings (see below) 
1.747     albertel 15375: 
                   15376: Internal notes:
                   15377: 
1.749     raeburn  15378:  access controls are stored in file_permissions.db as key=value pairs.
                   15379:     key -> path to file/file_name\0uniqueID:scope_end_start
                   15380:         where scope -> public,guest,course,group,domains or users.
                   15381:               end -> UNIX time for end of access (0 -> no end date)
                   15382:               start -> UNIX time for start of access
                   15383: 
                   15384:     value -> XML description of access control
                   15385:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   15386:             <start></start>
                   15387:             <end></end>
                   15388: 
                   15389:             <password></password>  for scope type = guest
                   15390: 
                   15391:             <domain></domain>     for scope type = course or group
                   15392:             <number></number>
                   15393:             <roles id="">
                   15394:              <role></role>
                   15395:              <access></access>
                   15396:              <section></section>
                   15397:              <group></group>
                   15398:             </roles>
                   15399: 
                   15400:             <dom></dom>         for scope type = domains
                   15401: 
                   15402:             <users>             for scope type = users
                   15403:              <user>
                   15404:               <uname></uname>
                   15405:               <udom></udom>
                   15406:              </user>
                   15407:             </users>
                   15408:            </scope> 
                   15409:               
                   15410:  Access data is also aggregated for each file in an additional key=value pair:
                   15411:  key -> path to file/file_name\0accesscontrol 
                   15412:  value -> reference to hash
                   15413:           hash contains key = value pairs
                   15414:           where key = uniqueID:scope_end_start
                   15415:                 value = UNIX time record was last updated
                   15416: 
                   15417:           Used to improve speed of look-ups of access controls for each file.  
                   15418:  
                   15419:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   15420: 
1.1172.2.13  raeburn  15421: =item *
                   15422: 
1.749     raeburn  15423: modify_access_controls():
                   15424: 
                   15425: Modifies access controls for a portfolio file
                   15426: Args
                   15427: 1. file name
                   15428: 2. reference to hash of required changes,
                   15429: 3. domain
                   15430: 4. username
                   15431:   where domain,username are the domain of the portfolio owner 
                   15432:   (either a user or a course) 
                   15433: 
                   15434: Returns:
                   15435: 1. result of additions or updates ('ok' or 'error', with error message). 
                   15436: 2. result of deletions ('ok' or 'error', with error message).
                   15437: 3. reference to hash of any new or updated access controls.
                   15438: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   15439:    key = integer (inbound ID)
1.1172.2.13  raeburn  15440:    value = uniqueID
                   15441: 
                   15442: =item *
                   15443: 
                   15444: get_timebased_id():
                   15445: 
                   15446: Attempts to get a unique timestamp-based suffix for use with items added to a
                   15447: course via the Course Editor (e.g., folders, composite pages,
                   15448: group bulletin boards).
                   15449: 
                   15450: Args: (first three required; six others optional)
                   15451: 
                   15452: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   15453:    docssequence, or name of group
                   15454: 
                   15455: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   15456:    e.g., num, boardids
                   15457: 
                   15458: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   15459:    file will be named nohist_namespace.db
                   15460: 
                   15461: 4. cdom: domain of course; default is current course domain from %env
                   15462: 
                   15463: 5. cnum: course number; default is current course number from %env
                   15464: 
                   15465: 6. idtype: set to concat if an additional digit is to be appended to the
                   15466:    unix timestamp to form the suffix, if the plain timestamp is already
                   15467:    in use.  Default is to not do this, but simply increment the unix
                   15468:    timestamp by 1 until a unique key is obtained.
                   15469: 
                   15470: 7. who: holder of locking key; defaults to user:domain for user.
                   15471: 
                   15472: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   15473:    retrying); default is 3.
                   15474: 
                   15475: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   15476: 
                   15477: Returns:
                   15478: 
                   15479: 1. suffix obtained (numeric)
                   15480: 
                   15481: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   15482: 
                   15483: 3. error: contains (localized) error message if an error occurred.
                   15484: 
1.747     albertel 15485: 
1.608     albertel 15486: =back
                   15487: 
1.243     albertel 15488: =head2 HTTP Helper Routines
                   15489: 
                   15490: =over 4
                   15491: 
1.191     harris41 15492: =item *
                   15493: 
                   15494: escape() : unpack non-word characters into CGI-compatible hex codes
                   15495: 
                   15496: =item *
                   15497: 
                   15498: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   15499: 
1.243     albertel 15500: =back
                   15501: 
                   15502: =head1 PRIVATE SUBROUTINES
                   15503: 
                   15504: =head2 Underlying communication routines (Shouldn't call)
                   15505: 
                   15506: =over 4
                   15507: 
                   15508: =item *
                   15509: 
                   15510: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   15511: 
                   15512: =item *
                   15513: 
                   15514: reply() : uses subreply to send a message to remote machine, logs all failures
                   15515: 
                   15516: =item *
                   15517: 
                   15518: critical() : passes a critical message to another server; if cannot
                   15519: get through then place message in connection buffer directory and
                   15520: returns con_delayed, if incapable of saving message, returns
                   15521: con_failed
                   15522: 
                   15523: =item *
                   15524: 
                   15525: reconlonc() : tries to reconnect lonc client processes.
                   15526: 
                   15527: =back
                   15528: 
                   15529: =head2 Resource Access Logging
                   15530: 
                   15531: =over 4
                   15532: 
                   15533: =item *
                   15534: 
                   15535: flushcourselogs() : flush (save) buffer logs and access logs
                   15536: 
                   15537: =item *
                   15538: 
                   15539: courselog($what) : save message for course in hash
                   15540: 
                   15541: =item *
                   15542: 
                   15543: courseacclog($what) : save message for course using &courselog().  Perform
                   15544: special processing for specific resource types (problems, exams, quizzes, etc).
                   15545: 
1.191     harris41 15546: =item *
                   15547: 
                   15548: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   15549: as a PerlChildExitHandler
1.243     albertel 15550: 
                   15551: =back
                   15552: 
                   15553: =head2 Other
                   15554: 
                   15555: =over 4
                   15556: 
                   15557: =item *
                   15558: 
                   15559: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 15560: 
                   15561: =back
                   15562: 
                   15563: =cut
1.877     foxr     15564: 

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