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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.107! raeburn     4: # $Id: lonnet.pm,v 1.1172.2.106 2019/07/26 19:09:16 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.1155    raeburn   607:     if ($name eq '') {
                    608:         $name = 'lonID';
                    609:     }
                    610:     my $lonid=$cookies{$name};
1.916     albertel  611:     return undef if (!$lonid);
                    612: 
                    613:     my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155    raeburn   614:     my $lonidsdir;
                    615:     if ($name eq 'lonDAV') {
                    616:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    617:     } else {
                    618:         $lonidsdir=$r->dir_config('lonIDsDir');
                    619:     }
1.1172.2.96  raeburn   620:     if (!-e "$lonidsdir/$handle.id") {
                    621:         if ((ref($domref)) && ($name eq 'lonID') &&
                    622:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    623:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    624:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    625:                 $$domref = $possudom;
                    626:             }
                    627:         }
                    628:         return undef;
                    629:     }
1.916     albertel  630: 
1.917     albertel  631:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    632:     return undef if (!$opened);
1.916     albertel  633: 
                    634:     flock($idf,LOCK_SH);
                    635:     my %disk_env;
                    636:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    637: 	    &GDBM_READER(),0640)) {
                    638: 	return undef;	
                    639:     }
                    640: 
                    641:     if (!defined($disk_env{'user.name'})
                    642: 	|| !defined($disk_env{'user.domain'})) {
1.1172.2.107! raeburn   643:         untie(%disk_env);
1.916     albertel  644: 	return undef;
                    645:     }
1.1172.2.18  raeburn   646: 
1.1172.2.36  raeburn   647:     if (ref($userhashref) eq 'HASH') {
                    648:         $userhashref->{'name'} = $disk_env{'user.name'};
                    649:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1172.2.18  raeburn   650:     }
1.1172.2.107! raeburn   651:     untie(%disk_env);
1.1172.2.18  raeburn   652: 
1.916     albertel  653:     return $handle;
                    654: }
                    655: 
1.830     albertel  656: sub timed_flock {
                    657:     my ($file,$lock_type) = @_;
                    658:     my $failed=0;
                    659:     eval {
                    660: 	local $SIG{__DIE__}='DEFAULT';
                    661: 	local $SIG{ALRM}=sub {
                    662: 	    $failed=1;
                    663: 	    die("failed lock");
                    664: 	};
                    665: 	alarm(13);
                    666: 	flock($file,$lock_type);
                    667: 	alarm(0);
                    668:     };
                    669:     if ($failed) {
                    670: 	return undef;
                    671:     } else {
                    672: 	return 1;
                    673:     }
                    674: }
                    675: 
1.1172.2.107! raeburn   676: sub get_sessionfile_vars {
        !           677:     my ($handle,$lonidsdir,$storearr) = @_;
        !           678:     my %returnhash;
        !           679:     unless (ref($storearr) eq 'ARRAY') {
        !           680:         return %returnhash;
        !           681:     }
        !           682:     if (-l "$lonidsdir/$handle.id") {
        !           683:         my $link = readlink("$lonidsdir/$handle.id");
        !           684:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
        !           685:             $handle = $1;
        !           686:         }
        !           687:     }
        !           688:     if ((-e "$lonidsdir/$handle.id") &&
        !           689:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
        !           690:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
        !           691:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
        !           692:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
        !           693:                 flock($idf,LOCK_SH);
        !           694:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
        !           695:                         &GDBM_READER(),0640)) {
        !           696:                     foreach my $item (@{$storearr}) {
        !           697:                         $returnhash{$item} = $disk_env{$item};
        !           698:                     }
        !           699:                     untie(%disk_env);
        !           700:                 }
        !           701:             }
        !           702:         }
        !           703:     }
        !           704:     return %returnhash;
        !           705: }
        !           706: 
1.5       www       707: # ---------------------------------------------------------- Append Environment
                    708: 
                    709: sub appenv {
1.949     raeburn   710:     my ($newenv,$roles) = @_;
                    711:     if (ref($newenv) eq 'HASH') {
                    712:         foreach my $key (keys(%{$newenv})) {
                    713:             my $refused = 0;
                    714: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    715:                 $refused = 1;
                    716:                 if (ref($roles) eq 'ARRAY') {
1.1172.2.40  raeburn   717:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   718:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    719:                         $refused = 0;
                    720:                     }
                    721:                 }
                    722:             }
                    723:             if ($refused) {
                    724:                 &logthis("<font color=\"blue\">WARNING: ".
                    725:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    726:                          .'</font>');
                    727: 	        delete($newenv->{$key});
                    728:             } else {
                    729:                 $env{$key}=$newenv->{$key};
                    730:             }
                    731:         }
1.1172.2.96  raeburn   732:         my $lonids = $perlvar{'lonIDsDir'};
                    733:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
                    734:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    735:             if ($opened
                    736: 	        && &timed_flock($env_file,LOCK_EX)
                    737: 	        &&
                    738: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    739: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    740: 	        while (my ($key,$value) = each(%{$newenv})) {
                    741: 	            $disk_env{$key} = $value;
                    742: 	        }
                    743: 	        untie(%disk_env);
                    744:             }
1.35      www       745:         }
1.191     harris41  746:     }
1.56      www       747:     return 'ok';
                    748: }
                    749: # ----------------------------------------------------- Delete from Environment
                    750: 
                    751: sub delenv {
1.1104    raeburn   752:     my ($delthis,$regexp,$roles) = @_;
                    753:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    754:         my $refused = 1;
                    755:         if (ref($roles) eq 'ARRAY') {
                    756:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    757:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    758:                 $refused = 0;
                    759:             }
                    760:         }
                    761:         if ($refused) {
                    762:             &logthis("<font color=\"blue\">WARNING: ".
                    763:                      "Attempt to delete from environment ".$delthis);
                    764:             return 'error';
                    765:         }
1.56      www       766:     }
1.917     albertel  767:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    768:     if ($opened
1.915     albertel  769: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  770: 	&&
                    771: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    772: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  773: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   774: 	    if ($regexp) {
                    775:                 if ($key=~/^$delthis/) {
                    776:                     delete($env{$key});
                    777:                     delete($disk_env{$key});
                    778:                 } 
                    779:             } else {
                    780:                 if ($key=~/^\Q$delthis\E/) {
                    781: 		    delete($env{$key});
                    782: 		    delete($disk_env{$key});
                    783: 	        }
                    784:             }
1.448     albertel  785: 	}
1.783     albertel  786: 	untie(%disk_env);
1.5       www       787:     }
                    788:     return 'ok';
1.369     albertel  789: }
                    790: 
1.790     albertel  791: sub get_env_multiple {
                    792:     my ($name) = @_;
                    793:     my @values;
                    794:     if (defined($env{$name})) {
                    795:         # exists is it an array
                    796:         if (ref($env{$name})) {
                    797:             @values=@{ $env{$name} };
                    798:         } else {
                    799:             $values[0]=$env{$name};
                    800:         }
                    801:     }
                    802:     return(@values);
                    803: }
                    804: 
1.958     www       805: # ------------------------------------------------------------------- Locking
                    806: 
                    807: sub set_lock {
                    808:     my ($text)=@_;
                    809:     $locknum++;
                    810:     my $id=$$.'-'.$locknum;
                    811:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    812:              'session.lock.'.$id => $text});
                    813:     return $id;
                    814: }
                    815: 
                    816: sub get_locks {
                    817:     my $num=0;
                    818:     my %texts=();
                    819:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    820:        if ($lock=~/\w/) {
                    821:           $num++;
                    822:           $texts{$lock}=$env{'session.lock.'.$lock};
                    823:        }
                    824:    }
                    825:    return ($num,%texts);
                    826: }
                    827: 
                    828: sub remove_lock {
                    829:     my ($id)=@_;
                    830:     my $newlocks='';
                    831:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    832:        if (($lock=~/\w/) && ($lock ne $id)) {
                    833:           $newlocks.=','.$lock;
                    834:        }
                    835:     }
                    836:     &appenv({'session.locks' => $newlocks});
                    837:     &delenv('session.lock.'.$id);
                    838: }
                    839: 
                    840: sub remove_all_locks {
                    841:     my $activelocks=$env{'session.locks'};
                    842:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    843:        if ($lock=~/\w/) {
                    844:           &remove_lock($lock);
                    845:        }
                    846:     }
                    847: }
                    848: 
                    849: 
1.369     albertel  850: # ------------------------------------------ Find out current server userload
                    851: sub userload {
                    852:     my $numusers=0;
                    853:     {
                    854: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    855: 	my $filename;
                    856: 	my $curtime=time;
                    857: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  858: 	    next if ($filename eq '.' || $filename eq '..');
                    859: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  860: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  861: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  862: 	}
                    863: 	closedir(LONIDS);
                    864:     }
                    865:     my $userloadpercent=0;
                    866:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    867:     if ($maxuserload) {
1.371     albertel  868: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  869:     }
1.372     albertel  870:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  871:     return $userloadpercent;
1.283     www       872: }
                    873: 
1.1       albertel  874: # ------------------------------ Find server with least workload from spare.tab
1.11      www       875: 
1.1       albertel  876: sub spareserver {
1.1083    raeburn   877:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  878:     my $spare_server;
1.370     albertel  879:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  880:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    881:                                                      :  $userloadpercent;
1.1083    raeburn   882:     my ($uint_dom,$remotesessions);
                    883:     if (($udom ne '') && (&domain($udom) ne '')) {
                    884:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    885:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    886:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    887:         $remotesessions = $udomdefaults{'remotesessions'};
                    888:     }
1.1123    raeburn   889:     my $spareshash = &this_host_spares($udom);
                    890:     if (ref($spareshash) eq 'HASH') {
                    891:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    892:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1172.2.62  raeburn   893:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    894:                                              $try_server));
1.1123    raeburn   895: 	        ($spare_server, $lowest_load) =
                    896: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    897:             }
1.1083    raeburn   898:         }
1.784     albertel  899: 
1.1123    raeburn   900:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    901: 
                    902:         if (!$found_server) {
                    903:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    904: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1172.2.62  raeburn   905:                     next unless (&spare_can_host($udom,$uint_dom,
                    906:                                                  $remotesessions,$try_server));
1.1123    raeburn   907: 	            ($spare_server, $lowest_load) =
                    908: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    909:                 }
                    910: 	    }
                    911:         }
1.784     albertel  912:     }
                    913: 
                    914:     if (!$want_server_name) {
1.968     raeburn   915:         my $protocol = 'http';
                    916:         if ($protocol{$spare_server} eq 'https') {
                    917:             $protocol = $protocol{$spare_server};
                    918:         }
1.1001    raeburn   919:         if (defined($spare_server)) {
                    920:             my $hostname = &hostname($spare_server);
1.1083    raeburn   921:             if (defined($hostname)) {
1.1001    raeburn   922: 	        $spare_server = $protocol.'://'.$hostname;
                    923:             }
                    924:         }
1.784     albertel  925:     }
                    926:     return $spare_server;
                    927: }
                    928: 
                    929: sub compare_server_load {
1.1172.2.41  raeburn   930:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                    931: 
                    932:     if ($required) {
                    933:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                    934:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                    935:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                    936:         if (($major eq '' && $minor eq '') ||
                    937:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                    938:             return ($spare_server,$lowest_load);
                    939:         }
                    940:     }
1.784     albertel  941: 
                    942:     my $loadans     = &reply('load',    $try_server);
                    943:     my $userloadans = &reply('userload',$try_server);
                    944: 
                    945:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   946: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  947:     }
                    948: 
                    949:     my $load;
                    950:     if ($loadans =~ /\d/) {
                    951: 	if ($userloadans =~ /\d/) {
                    952: 	    #both are numbers, pick the bigger one
                    953: 	    $load = ($loadans > $userloadans) ? $loadans 
                    954: 		                              : $userloadans;
1.411     albertel  955: 	} else {
1.784     albertel  956: 	    $load = $loadans;
1.411     albertel  957: 	}
1.784     albertel  958:     } else {
                    959: 	$load = $userloadans;
                    960:     }
                    961: 
                    962:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    963: 	$spare_server = $try_server;
                    964: 	$lowest_load  = $load;
1.370     albertel  965:     }
1.784     albertel  966:     return ($spare_server,$lowest_load);
1.202     matthew   967: }
1.914     albertel  968: 
                    969: # --------------------------- ask offload servers if user already has a session
                    970: sub find_existing_session {
                    971:     my ($udom,$uname) = @_;
1.1123    raeburn   972:     my $spareshash = &this_host_spares($udom);
                    973:     if (ref($spareshash) eq 'HASH') {
                    974:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    975:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    976:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    977:             }
                    978:         }
                    979:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                    980:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                    981:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    982:             }
                    983:         }
1.914     albertel  984:     }
                    985:     return;
                    986: }
                    987: 
1.1172.2.107! raeburn   988: # check if user's browser sent load balancer cookie and server still has session
        !           989: # and is not overloaded.
        !           990: sub check_for_balancer_cookie {
        !           991:     my ($r,$update_mtime) = @_;
        !           992:     my ($otherserver,$cookie);
        !           993:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
        !           994:     if (exists($cookies{'balanceID'})) {
        !           995:         my $balid = $cookies{'balanceID'};
        !           996:         $cookie=&LONCAPA::clean_handle($balid->value);
        !           997:         my $balancedir=$r->dir_config('lonBalanceDir');
        !           998:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
        !           999:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
        !          1000:                 my ($possudom,$possuname) = ($1,$2);
        !          1001:                 my $has_session = 0;
        !          1002:                 if ((&domain($possudom) ne '') &&
        !          1003:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
        !          1004:                     my $try_server;
        !          1005:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
        !          1006:                     if ($opened) {
        !          1007:                         flock($idf,LOCK_SH);
        !          1008:                         while (my $line = <$idf>) {
        !          1009:                             chomp($line);
        !          1010:                             if (&hostname($line) ne '') {
        !          1011:                                 $try_server = $line;
        !          1012:                                 last;
        !          1013:                             }
        !          1014:                         }
        !          1015:                         close($idf);
        !          1016:                         if (($try_server) &&
        !          1017:                             (&has_user_session($try_server,$possudom,$possuname))) {
        !          1018:                             my $lowest_load = 30000;
        !          1019:                             ($otherserver,$lowest_load) =
        !          1020:                                 &compare_server_load($try_server,undef,$lowest_load);
        !          1021:                             if ($otherserver ne '' && $lowest_load < 100) {
        !          1022:                                 $has_session = 1;
        !          1023:                             } else {
        !          1024:                                 undef($otherserver);
        !          1025:                             }
        !          1026:                         }
        !          1027:                     }
        !          1028:                 }
        !          1029:                 if ($has_session) {
        !          1030:                     if ($update_mtime) {
        !          1031:                         my $atime = my $mtime = time;
        !          1032:                         utime($atime,$mtime,"$balancedir/$cookie.id");
        !          1033:                     }
        !          1034:                 } else {
        !          1035:                     unlink("$balancedir/$cookie.id");
        !          1036:                 }
        !          1037:             }
        !          1038:         }
        !          1039:     }
        !          1040:     return ($otherserver,$cookie);
        !          1041: }
        !          1042: 
        !          1043: sub delbalcookie {
        !          1044:     my ($cookie,$balancer) =@_;
        !          1045:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
        !          1046:         my ($udom,$uname) = ($1,$2);
        !          1047:         my $uprimary_id = &domain($udom,'primary');
        !          1048:         my $uintdom = &internet_dom($uprimary_id);
        !          1049:         my $intdom = &internet_dom($balancer);
        !          1050:         my $serverhomedom = &host_domain($balancer);
        !          1051:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
        !          1052:             return &reply("delbalcookie:$cookie",$balancer);
        !          1053:         }
        !          1054:     }
        !          1055: }
        !          1056: 
1.914     albertel 1057: # -------------------------------- ask if server already has a session for user
                   1058: sub has_user_session {
                   1059:     my ($lonid,$udom,$uname) = @_;
                   1060:     my $result = &reply(join(':','userhassession',
                   1061: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                   1062:     return 1 if ($result eq 'ok');
                   1063: 
                   1064:     return 0;
                   1065: }
                   1066: 
1.1076    raeburn  1067: # --------- determine least loaded server in a user's domain which allows login
                   1068: 
                   1069: sub choose_server {
1.1172.2.47  raeburn  1070:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn  1071:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn  1072:     my %servers = &get_servers($udom);
1.1076    raeburn  1073:     my $lowest_load = 30000;
1.1172.2.47  raeburn  1074:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                   1075:     if ($skiploadbal) {
                   1076:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                   1077:         unless (defined($cached)) {
                   1078:             my $cachetime = 60*60*24;
                   1079:             my %domconfig =
                   1080:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1081:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1082:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                   1083:                                            $cachetime);
                   1084:             }
                   1085:         }
                   1086:     }
1.1076    raeburn  1087:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn  1088:         my $loginvia;
1.1172.2.47  raeburn  1089:         if ($skiploadbal) {
                   1090:             if (ref($balancers) eq 'HASH') {
                   1091:                 next if (exists($balancers->{$lonhost}));
                   1092:             }
                   1093:         }
1.1115    raeburn  1094:         if ($checkloginvia) {
                   1095:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn  1096:             if ($loginvia) {
                   1097:                 my ($server,$path) = split(/:/,$loginvia);
                   1098:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1099:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn  1100:                 if ($login_host eq $server) {
                   1101:                     $portal_path = $path;
1.1151    raeburn  1102:                     $isredirect = 1;
1.1116    raeburn  1103:                 }
                   1104:             } else {
                   1105:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1106:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn  1107:                 if ($login_host eq $lonhost) {
                   1108:                     $portal_path = '';
1.1151    raeburn  1109:                     $isredirect = ''; 
1.1116    raeburn  1110:                 }
                   1111:             }
                   1112:         } else {
1.1076    raeburn  1113:             ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1114:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1115:         }
                   1116:     }
                   1117:     if ($login_host ne '') {
1.1116    raeburn  1118:         $hostname = &hostname($login_host);
1.1076    raeburn  1119:     }
1.1172.2.88  raeburn  1120:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076    raeburn  1121: }
                   1122: 
1.202     matthew  1123: # --------------------------------------------- Try to change a user's password
                   1124: 
                   1125: sub changepass {
1.799     raeburn  1126:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1127:     $currentpass = &escape($currentpass);
                   1128:     $newpass     = &escape($newpass);
1.1030    raeburn  1129:     my $lonhost = $perlvar{'lonHostID'};
                   1130:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1131: 		       $server);
                   1132:     if (! $answer) {
                   1133: 	&logthis("No reply on password change request to $server ".
                   1134: 		 "by $uname in domain $udom.");
                   1135:     } elsif ($answer =~ "^ok") {
                   1136:         &logthis("$uname in $udom successfully changed their password ".
                   1137: 		 "on $server.");
                   1138:     } elsif ($answer =~ "^pwchange_failure") {
                   1139: 	&logthis("$uname in $udom was unable to change their password ".
                   1140: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1141: 		 "or pwchange");
                   1142:     } elsif ($answer =~ "^non_authorized") {
                   1143:         &logthis("$uname in $udom did not get their password correct when ".
                   1144: 		 "attempting to change it on $server.");
                   1145:     } elsif ($answer =~ "^auth_mode_error") {
                   1146:         &logthis("$uname in $udom attempted to change their password despite ".
                   1147: 		 "not being locally or internally authenticated on $server.");
                   1148:     } elsif ($answer =~ "^unknown_user") {
                   1149:         &logthis("$uname in $udom attempted to change their password ".
                   1150: 		 "on $server but were unable to because $server is not ".
                   1151: 		 "their home server.");
                   1152:     } elsif ($answer =~ "^refused") {
                   1153: 	&logthis("$server refused to change $uname in $udom password because ".
                   1154: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1155:     } elsif ($answer =~ "invalid_client") {
                   1156:         &logthis("$server refused to change $uname in $udom password because ".
                   1157:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1158:     }
                   1159:     return $answer;
1.1       albertel 1160: }
                   1161: 
1.169     harris41 1162: # ----------------------- Try to determine user's current authentication scheme
                   1163: 
                   1164: sub queryauthenticate {
                   1165:     my ($uname,$udom)=@_;
1.456     albertel 1166:     my $uhome=&homeserver($uname,$udom);
                   1167:     if (!$uhome) {
                   1168: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1169: 	return 'no_host';
                   1170:     }
                   1171:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1172:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1173: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1174:     }
1.456     albertel 1175:     return $answer;
1.169     harris41 1176: }
                   1177: 
1.1       albertel 1178: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1179: 
1.1       albertel 1180: sub authenticate {
1.1073    raeburn  1181:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1182:     $upass=&escape($upass);
                   1183:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1184:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1185:     my $newhome;
1.836     www      1186:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1187: # Maybe the machine was offline and only re-appeared again recently?
                   1188:         &reconlonc();
                   1189: # One more
1.952     raeburn  1190: 	$uhome=&homeserver($uname,$udom,1);
                   1191:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1192:             if (defined(&domain($udom,'primary'))) {
                   1193:                 $newhome=&domain($udom,'primary');
                   1194:             }
                   1195:             if ($newhome ne '') {
                   1196:                 $uhome = $newhome;
                   1197:             }
                   1198:         }
1.836     www      1199: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1200: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1201: 	    return 'no_host';
                   1202:         }
1.1       albertel 1203:     }
1.1073    raeburn  1204:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1205:     if ($answer eq 'authorized') {
1.952     raeburn  1206:         if ($newhome) {
                   1207:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1208:             return 'no_account_on_host'; 
                   1209:         } else {
                   1210:             &logthis("User $uname at $udom authorized by $uhome");
                   1211:             return $uhome;
                   1212:         }
1.471     albertel 1213:     }
                   1214:     if ($answer eq 'non_authorized') {
                   1215: 	&logthis("User $uname at $udom rejected by $uhome");
                   1216: 	return 'no_host'; 
1.9       www      1217:     }
1.471     albertel 1218:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1219:     return 'no_host';
                   1220: }
                   1221: 
1.1073    raeburn  1222: sub can_host_session {
1.1074    raeburn  1223:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1224:     my $canhost = 1;
1.1074    raeburn  1225:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1226:     if (ref($remotesessions) eq 'HASH') {
                   1227:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1228:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1229:                 $canhost = 0;
                   1230:             } else {
                   1231:                 $canhost = 1;
                   1232:             }
                   1233:         }
                   1234:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1235:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1236:                 $canhost = 1;
                   1237:             } else {
                   1238:                 $canhost = 0;
                   1239:             }
                   1240:         }
                   1241:         if ($canhost) {
                   1242:             if ($remotesessions->{'version'} ne '') {
                   1243:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1244:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1245:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1246:                         my $major = $1;
                   1247:                         my $minor = $2;
                   1248:                         if (($major < $reqmajor ) ||
                   1249:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1250:                             $canhost = 0;
                   1251:                         }
                   1252:                     } else {
                   1253:                         $canhost = 0;
                   1254:                     }
                   1255:                 }
                   1256:             }
                   1257:         }
                   1258:     }
                   1259:     if ($canhost) {
                   1260:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1261:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1262:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1263:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1264:                 if (($uint_dom ne '') && 
                   1265:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1266:                     $canhost = 0;
                   1267:                 } else {
                   1268:                     $canhost = 1;
                   1269:                 }
                   1270:             }
                   1271:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1272:                 if (($uint_dom ne '') && 
                   1273:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1274:                     $canhost = 1;
                   1275:                 } else {
                   1276:                     $canhost = 0;
                   1277:                 }
                   1278:             }
                   1279:         }
                   1280:     }
                   1281:     return $canhost;
                   1282: }
                   1283: 
1.1083    raeburn  1284: sub spare_can_host {
                   1285:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1286:     my $canhost=1;
1.1172.2.62  raeburn  1287:     my $try_server_hostname = &hostname($try_server);
                   1288:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1289:     my $serverhomedom = &host_domain($serverhomeID);
                   1290:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1291:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1292:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1293:             $canhost = 0;
                   1294:         }
                   1295:     }
                   1296:     if (($canhost) && ($uint_dom)) {
                   1297:         my @intdoms;
                   1298:         my $internet_names = &get_internet_names($try_server);
                   1299:         if (ref($internet_names) eq 'ARRAY') {
                   1300:             @intdoms = @{$internet_names};
                   1301:         }
                   1302:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1303:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1304:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1305:                                          $remotesessions,
                   1306:                                          $defdomdefaults{'hostedsessions'});
                   1307:         }
1.1083    raeburn  1308:     }
                   1309:     return $canhost;
                   1310: }
                   1311: 
1.1123    raeburn  1312: sub this_host_spares {
                   1313:     my ($dom) = @_;
1.1126    raeburn  1314:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1315:     my @hosts = &current_machine_ids();
                   1316:     foreach my $lonhost (@hosts) {
                   1317:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1318:             $dom_in_use = $dom;
                   1319:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1320:             last;
                   1321:         }
                   1322:     }
1.1126    raeburn  1323:     if ($dom_in_use ne '') {
                   1324:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1325:     }
                   1326:     if (ref($result) ne 'HASH') {
                   1327:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1328:         $dom_in_use = &host_domain($lonhost_in_use);
                   1329:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1330:         if (ref($result) ne 'HASH') {
                   1331:             $result = \%spareid;
                   1332:         }
                   1333:     }
                   1334:     return $result;
                   1335: }
                   1336: 
                   1337: sub spares_for_offload  {
                   1338:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1339:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1340:     if (defined($cached)) {
                   1341:         return $result;
                   1342:     } else {
1.1126    raeburn  1343:         my $cachetime = 60*60*24;
                   1344:         my %domconfig =
                   1345:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1346:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1347:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1348:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1349:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1350:                 }
                   1351:             }
                   1352:         }
                   1353:     }
1.1126    raeburn  1354:     return;
1.1123    raeburn  1355: }
                   1356: 
1.1129    raeburn  1357: sub get_lonbalancer_config {
                   1358:     my ($servers) = @_;
                   1359:     my ($currbalancer,$currtargets);
                   1360:     if (ref($servers) eq 'HASH') {
                   1361:         foreach my $server (keys(%{$servers})) {
                   1362:             my %what = (
                   1363:                          spareid => 1,
                   1364:                          perlvar => 1,
                   1365:                        );
                   1366:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1367:             if ($result eq 'ok') {
                   1368:                 if (ref($returnhash) eq 'HASH') {
                   1369:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1370:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1371:                             $currbalancer = $server;
                   1372:                             $currtargets = {};
                   1373:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1374:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1375:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1376:                                 }
                   1377:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1378:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1379:                                 }
                   1380:                             }
                   1381:                             last;
                   1382:                         }
                   1383:                     }
                   1384:                 }
                   1385:             }
                   1386:         }
                   1387:     }
                   1388:     return ($currbalancer,$currtargets);
                   1389: }
                   1390: 
                   1391: sub check_loadbalancing {
1.1172.2.88  raeburn  1392:     my ($uname,$udom,$caller) = @_;
1.1172.2.12  raeburn  1393:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1172.2.107! raeburn  1394:         $rule_in_effect,$offloadto,$otherserver,$setcookie);
1.1129    raeburn  1395:     my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4  raeburn  1396:     my @hosts = &current_machine_ids();
1.1129    raeburn  1397:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1398:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1399:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1400:     my $serverhomedom = &host_domain($lonhost);
1.1172.2.75  raeburn  1401:     my $domneedscache; 
1.1129    raeburn  1402:     my $cachetime = 60*60*24;
                   1403: 
                   1404:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1405:         $dom_in_use = $udom;
                   1406:         $homeintdom = 1;
                   1407:     } else {
                   1408:         $dom_in_use = $serverhomedom;
                   1409:     }
                   1410:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1411:     unless (defined($cached)) {
                   1412:         my %domconfig =
                   1413:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1414:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1415:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1172.2.75  raeburn  1416:         } else {
                   1417:             $domneedscache = $dom_in_use;
1.1129    raeburn  1418:         }
                   1419:     }
                   1420:     if (ref($result) eq 'HASH') {
1.1172.2.107! raeburn  1421:         ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12  raeburn  1422:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1423:         if ($is_balancer) {
                   1424:             if (ref($currrules) eq 'HASH') {
                   1425:                 if ($homeintdom) {
                   1426:                     if ($uname ne '') {
                   1427:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1428:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1429:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1430:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1431:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1432:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1433:                             }
                   1434:                         }
                   1435:                         if ($rule_in_effect eq '') {
                   1436:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1437:                             if ($userenv{'inststatus'} ne '') {
                   1438:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1439:                                 my ($othertitle,$usertypes,$types) =
                   1440:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1441:                                 if (ref($types) eq 'ARRAY') {
                   1442:                                     foreach my $type (@{$types}) {
                   1443:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1444:                                             if (exists($currrules->{$type})) {
                   1445:                                                 $rule_in_effect = $currrules->{$type};
                   1446:                                             }
                   1447:                                         }
                   1448:                                     }
                   1449:                                 }
                   1450:                             } else {
                   1451:                                 if (exists($currrules->{'default'})) {
                   1452:                                     $rule_in_effect = $currrules->{'default'};
                   1453:                                 }
                   1454:                             }
                   1455:                         }
                   1456:                     } else {
                   1457:                         if (exists($currrules->{'default'})) {
                   1458:                             $rule_in_effect = $currrules->{'default'};
                   1459:                         }
                   1460:                     }
                   1461:                 } else {
                   1462:                     if ($currrules->{'_LC_external'} ne '') {
                   1463:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1464:                     }
                   1465:                 }
                   1466:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1467:                                                        $uname,$udom);
                   1468:             }
                   1469:         }
                   1470:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35  raeburn  1471:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1472:         unless (defined($cached)) {
                   1473:             my %domconfig =
                   1474:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1475:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1172.2.75  raeburn  1476:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1477:             } else {
                   1478:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1479:             }
                   1480:         }
                   1481:         if (ref($result) eq 'HASH') {
1.1172.2.107! raeburn  1482:             ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12  raeburn  1483:                 &check_balancer_result($result,@hosts);
                   1484:             if ($is_balancer) {
1.1129    raeburn  1485:                 if (ref($currrules) eq 'HASH') {
                   1486:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1487:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1488:                     }
                   1489:                 }
                   1490:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1491:                                                        $uname,$udom);
                   1492:             }
                   1493:         } else {
                   1494:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1495:                 $is_balancer = 1;
                   1496:                 $offloadto = &this_host_spares($dom_in_use);
                   1497:             }
1.1172.2.75  raeburn  1498:             unless (defined($cached)) {
                   1499:                 $domneedscache = $serverhomedom;
                   1500:             }
1.1129    raeburn  1501:         }
                   1502:     } else {
                   1503:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1504:             $is_balancer = 1;
                   1505:             $offloadto = &this_host_spares($dom_in_use);
                   1506:         }
1.1172.2.75  raeburn  1507:         unless (defined($cached)) {
                   1508:             $domneedscache = $serverhomedom;
                   1509:         }
                   1510:     }
                   1511:     if ($domneedscache) {
                   1512:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1513:     }
1.1172.2.5  raeburn  1514:     if ($is_balancer) {
                   1515:         my $lowest_load = 30000;
                   1516:         if (ref($offloadto) eq 'HASH') {
                   1517:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1518:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1519:                     ($otherserver,$lowest_load) =
                   1520:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1521:                 }
1.1129    raeburn  1522:             }
1.1172.2.5  raeburn  1523:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1524: 
1.1172.2.5  raeburn  1525:             if (!$found_server) {
                   1526:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1527:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1528:                         ($otherserver,$lowest_load) =
                   1529:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1530:                     }
                   1531:                 }
                   1532:             }
                   1533:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1534:             if (@{$offloadto} == 1) {
                   1535:                 $otherserver = $offloadto->[0];
                   1536:             } elsif (@{$offloadto} > 1) {
                   1537:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1538:                     ($otherserver,$lowest_load) =
                   1539:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1540:                 }
                   1541:             }
                   1542:         }
1.1172.2.88  raeburn  1543:         unless ($caller eq 'login') {
                   1544:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1545:                 $is_balancer = 0;
                   1546:                 if ($uname ne '' && $udom ne '') {
                   1547:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1548:                         &appenv({'user.loadbalexempt'     => $lonhost,
                   1549:                                  'user.loadbalcheck.time' => time});
                   1550:                     }
1.1172.2.5  raeburn  1551:                 }
1.1129    raeburn  1552:             }
                   1553:         }
1.1172.2.107! raeburn  1554:         unless ($homeintdom) {
        !          1555:             undef($setcookie);
        !          1556:         }
1.1129    raeburn  1557:     }
1.1172.2.107! raeburn  1558:     return ($is_balancer,$otherserver,$setcookie);
1.1129    raeburn  1559: }
                   1560: 
1.1172.2.12  raeburn  1561: sub check_balancer_result {
                   1562:     my ($result,@hosts) = @_;
1.1172.2.107! raeburn  1563:     my ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12  raeburn  1564:     if (ref($result) eq 'HASH') {
                   1565:         if ($result->{'lonhost'} ne '') {
                   1566:             my $currbalancer = $result->{'lonhost'};
                   1567:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1568:                 $is_balancer = 1;
                   1569:                 $currtargets = $result->{'targets'};
                   1570:                 $currrules = $result->{'rules'};
                   1571:             }
                   1572:         } else {
                   1573:             foreach my $key (keys(%{$result})) {
                   1574:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1575:                     (ref($result->{$key}) eq 'HASH')) {
                   1576:                     $is_balancer = 1;
                   1577:                     $currrules = $result->{$key}{'rules'};
                   1578:                     $currtargets = $result->{$key}{'targets'};
1.1172.2.107! raeburn  1579:                     $setcookie = $result->{$key}{'cookie'};
1.1172.2.12  raeburn  1580:                     last;
                   1581:                 }
                   1582:             }
                   1583:         }
                   1584:     }
1.1172.2.107! raeburn  1585:     return ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12  raeburn  1586: }
                   1587: 
1.1129    raeburn  1588: sub get_loadbalancer_targets {
                   1589:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1590:     my $offloadto;
1.1172.2.4  raeburn  1591:     if ($rule_in_effect eq 'none') {
                   1592:         return [$perlvar{'lonHostID'}];
                   1593:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1594:         $offloadto = $currtargets;
                   1595:     } else {
                   1596:         if ($rule_in_effect eq 'homeserver') {
                   1597:             my $homeserver = &homeserver($uname,$udom);
                   1598:             if ($homeserver ne 'no_host') {
                   1599:                 $offloadto = [$homeserver];
                   1600:             }
                   1601:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1602:             my %domconfig =
                   1603:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1604:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1605:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1606:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1607:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1608:                     }
                   1609:                 }
                   1610:             } else {
1.1172.2.7  raeburn  1611:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1612:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1613:                 if (&hostname($remotebalancer) ne '') {
                   1614:                     $offloadto = [$remotebalancer];
                   1615:                 }
                   1616:             }
                   1617:         } elsif (&hostname($rule_in_effect) ne '') {
                   1618:             $offloadto = [$rule_in_effect];
                   1619:         }
                   1620:     }
                   1621:     return $offloadto;
                   1622: }
                   1623: 
1.1127    raeburn  1624: sub internet_dom_servers {
                   1625:     my ($dom) = @_;
                   1626:     my (%uniqservers,%servers);
                   1627:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1628:     my @machinedoms = &machine_domains($primaryserver);
                   1629:     foreach my $mdom (@machinedoms) {
                   1630:         my %currservers = %servers;
                   1631:         my %server = &get_servers($mdom);
                   1632:         %servers = (%currservers,%server);
                   1633:     }
                   1634:     my %by_hostname;
                   1635:     foreach my $id (keys(%servers)) {
                   1636:         push(@{$by_hostname{$servers{$id}}},$id);
                   1637:     }
                   1638:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1639:         if (@{$by_hostname{$hostname}} > 1) {
                   1640:             my $match = 0;
                   1641:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1642:                 if (&host_domain($id) eq $dom) {
                   1643:                     $uniqservers{$id} = $hostname;
                   1644:                     $match = 1;
                   1645:                 }
                   1646:             }
                   1647:             unless ($match) {
                   1648:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1649:             }
                   1650:         } else {
                   1651:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1652:         }
                   1653:     }
                   1654:     return %uniqservers;
                   1655: }
                   1656: 
1.1       albertel 1657: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1658: 
1.599     albertel 1659: my %homecache;
1.1       albertel 1660: sub homeserver {
1.230     stredwic 1661:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1662:     my $index="$uname:$udom";
1.426     albertel 1663: 
1.599     albertel 1664:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1665: 
                   1666:     my %servers = &get_servers($udom,'library');
                   1667:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1668:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1669: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1670: 
                   1671: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1672: 	if ($answer eq 'found') {
                   1673: 	    delete($badServerCache{$tryserver}); 
                   1674: 	    return $homecache{$index}=$tryserver;
                   1675: 	} elsif ($answer eq 'no_host') {
                   1676: 	    $badServerCache{$tryserver}=1;
                   1677: 	}
1.1       albertel 1678:     }    
                   1679:     return 'no_host';
1.70      www      1680: }
                   1681: 
                   1682: # ------------------------------------- Find the usernames behind a list of IDs
                   1683: 
                   1684: sub idget {
                   1685:     my ($udom,@ids)=@_;
                   1686:     my %returnhash=();
                   1687:     
1.841     albertel 1688:     my %servers = &get_servers($udom,'library');
                   1689:     foreach my $tryserver (keys(%servers)) {
1.1172.2.73  raeburn  1690: 	my $idlist=join('&', map { &escape($_); } @ids);
1.841     albertel 1691: 	$idlist=~tr/A-Z/a-z/; 
                   1692: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1693: 	my @answer=();
                   1694: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1695: 	    @answer=split(/\&/,$reply);
                   1696: 	}                    ;
                   1697: 	my $i;
                   1698: 	for ($i=0;$i<=$#ids;$i++) {
                   1699: 	    if ($answer[$i]) {
1.1172.2.73  raeburn  1700: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.841     albertel 1701: 	    } 
                   1702: 	}
                   1703:     } 
1.70      www      1704:     return %returnhash;
                   1705: }
                   1706: 
                   1707: # ------------------------------------- Find the IDs behind a list of usernames
                   1708: 
                   1709: sub idrget {
                   1710:     my ($udom,@unames)=@_;
                   1711:     my %returnhash=();
1.800     albertel 1712:     foreach my $uname (@unames) {
                   1713:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1714:     }
1.70      www      1715:     return %returnhash;
                   1716: }
                   1717: 
                   1718: # ------------------------------- Store away a list of names and associated IDs
                   1719: 
                   1720: sub idput {
                   1721:     my ($udom,%ids)=@_;
                   1722:     my %servers=();
1.800     albertel 1723:     foreach my $uname (keys(%ids)) {
                   1724: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1725:         my $uhom=&homeserver($uname,$udom);
1.70      www      1726:         if ($uhom ne 'no_host') {
1.800     albertel 1727:             my $id=&escape($ids{$uname});
1.70      www      1728:             $id=~tr/A-Z/a-z/;
1.800     albertel 1729:             my $esc_unam=&escape($uname);
1.70      www      1730: 	    if ($servers{$uhom}) {
1.800     albertel 1731: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1732:             } else {
1.800     albertel 1733:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1734:             }
                   1735:         }
1.191     harris41 1736:     }
1.800     albertel 1737:     foreach my $server (keys(%servers)) {
                   1738:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1739:     }
1.344     www      1740: }
                   1741: 
1.1172.2.30  raeburn  1742: # ---------------------------------------- Delete unwanted IDs from ids.db file
                   1743: 
                   1744: sub iddel {
                   1745:     my ($udom,$idshashref,$uhome)=@_;
                   1746:     my %result=();
                   1747:     unless (ref($idshashref) eq 'HASH') {
                   1748:         return %result;
                   1749:     }
                   1750:     my %servers=();
                   1751:     while (my ($id,$uname) = each(%{$idshashref})) {
                   1752:         my $uhom;
                   1753:         if ($uhome) {
                   1754:             $uhom = $uhome;
                   1755:         } else {
                   1756:             $uhom=&homeserver($uname,$udom);
                   1757:         }
                   1758:         if ($uhom ne 'no_host') {
                   1759:             if ($servers{$uhom}) {
                   1760:                 $servers{$uhom}.='&'.&escape($id);
                   1761:             } else {
                   1762:                 $servers{$uhom}=&escape($id);
                   1763:             }
                   1764:         }
                   1765:     }
                   1766:     foreach my $server (keys(%servers)) {
                   1767:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1768:     }
                   1769:     return %result;
                   1770: }
                   1771: 
1.1023    raeburn  1772: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1773: sub dump_dom {
1.1165    droeschl 1774:     my ($namespace, $udom, $regexp) = @_;
                   1775: 
                   1776:     $udom ||= $env{'user.domain'};
                   1777: 
                   1778:     return () unless $udom;
                   1779: 
                   1780:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1781: }
                   1782: 
1.1023    raeburn  1783: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1784: 
                   1785: sub get_dom {
1.860     raeburn  1786:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1172.2.57  raeburn  1787:     return if ($udom eq 'public');
1.806     raeburn  1788:     my $items='';
                   1789:     foreach my $item (@$storearr) {
                   1790:         $items.=&escape($item).'&';
                   1791:     }
                   1792:     $items=~s/\&$//;
1.860     raeburn  1793:     if (!$udom) {
                   1794:         $udom=$env{'user.domain'};
1.1172.2.57  raeburn  1795:         return if ($udom eq 'public');
1.860     raeburn  1796:         if (defined(&domain($udom,'primary'))) {
                   1797:             $uhome=&domain($udom,'primary');
                   1798:         } else {
1.874     albertel 1799:             undef($uhome);
1.860     raeburn  1800:         }
                   1801:     } else {
                   1802:         if (!$uhome) {
                   1803:             if (defined(&domain($udom,'primary'))) {
                   1804:                 $uhome=&domain($udom,'primary');
                   1805:             }
                   1806:         }
                   1807:     }
                   1808:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1809:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1810:         my %returnhash;
1.875     albertel 1811:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1812:             return %returnhash;
                   1813:         }
1.806     raeburn  1814:         my @pairs=split(/\&/,$rep);
                   1815:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1816:             return @pairs;
                   1817:         }
                   1818:         my $i=0;
                   1819:         foreach my $item (@$storearr) {
                   1820:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1821:             $i++;
                   1822:         }
                   1823:         return %returnhash;
                   1824:     } else {
1.880     banghart 1825:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1826:     }
                   1827: }
                   1828: 
                   1829: # -------------------------------------------- put items in domain db files 
                   1830: 
                   1831: sub put_dom {
1.860     raeburn  1832:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1833:     if (!$udom) {
                   1834:         $udom=$env{'user.domain'};
                   1835:         if (defined(&domain($udom,'primary'))) {
                   1836:             $uhome=&domain($udom,'primary');
                   1837:         } else {
1.874     albertel 1838:             undef($uhome);
1.860     raeburn  1839:         }
                   1840:     } else {
                   1841:         if (!$uhome) {
                   1842:             if (defined(&domain($udom,'primary'))) {
                   1843:                 $uhome=&domain($udom,'primary');
                   1844:             }
                   1845:         }
                   1846:     } 
                   1847:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1848:         my $items='';
                   1849:         foreach my $item (keys(%$storehash)) {
                   1850:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1851:         }
                   1852:         $items=~s/\&$//;
                   1853:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1854:     } else {
1.860     raeburn  1855:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1856:     }
                   1857: }
                   1858: 
1.1023    raeburn  1859: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1860: sub newput_dom {
1.1023    raeburn  1861:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1862:     my $result;
                   1863:     if (!$udom) {
                   1864:         $udom=$env{'user.domain'};
                   1865:     }
1.1023    raeburn  1866:     if ($udom) {
                   1867:         my $uname = &get_domainconfiguser($udom);
                   1868:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1869:     }
                   1870:     return $result;
                   1871: }
                   1872: 
1.1023    raeburn  1873: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1874: sub del_dom {
1.1023    raeburn  1875:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1876:     if (ref($storearr) eq 'ARRAY') {
                   1877:         if (!$udom) {
                   1878:             $udom=$env{'user.domain'};
                   1879:         }
1.1023    raeburn  1880:         if ($udom) {
                   1881:             my $uname = &get_domainconfiguser($udom); 
                   1882:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1883:         }
                   1884:     }
                   1885: }
                   1886: 
1.1023    raeburn  1887: # ----------------------------------construct domainconfig user for a domain 
                   1888: sub get_domainconfiguser {
                   1889:     my ($udom) = @_;
                   1890:     return $udom.'-domainconfig';
                   1891: }
                   1892: 
1.837     raeburn  1893: sub retrieve_inst_usertypes {
                   1894:     my ($udom) = @_;
                   1895:     my (%returnhash,@order);
1.989     raeburn  1896:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1897:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1898:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44  raeburn  1899:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  1900:     } else {
                   1901:         if (defined(&domain($udom,'primary'))) {
                   1902:             my $uhome=&domain($udom,'primary');
                   1903:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1904:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44  raeburn  1905:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  1906:                 return (\%returnhash,\@order);
                   1907:             }
                   1908:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1909:             my @pairs=split(/\&/,$hashitems);
                   1910:             foreach my $item (@pairs) {
                   1911:                 my ($key,$value)=split(/=/,$item,2);
                   1912:                 $key = &unescape($key);
                   1913:                 next if ($key =~ /^error: 2 /);
                   1914:                 $returnhash{$key}=&thaw_unescape($value);
                   1915:             }
                   1916:             my @esc_order = split(/\&/,$orderitems);
                   1917:             foreach my $item (@esc_order) {
                   1918:                 push(@order,&unescape($item));
                   1919:             }
                   1920:         } else {
1.1172.2.44  raeburn  1921:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  1922:         }
1.1172.2.44  raeburn  1923:         return (\%returnhash,\@order);
1.837     raeburn  1924:     }
                   1925: }
                   1926: 
1.868     raeburn  1927: sub is_domainimage {
                   1928:     my ($url) = @_;
1.1172.2.74  raeburn  1929:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  1930:         if (&domain($1) ne '') {
                   1931:             return '1';
                   1932:         }
                   1933:     }
                   1934:     return;
                   1935: }
                   1936: 
1.899     raeburn  1937: sub inst_directory_query {
                   1938:     my ($srch) = @_;
                   1939:     my $udom = $srch->{'srchdomain'};
                   1940:     my %results;
                   1941:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1942:     my $outcome;
1.899     raeburn  1943:     if ($homeserver ne '') {
1.904     albertel 1944: 	my $queryid=&reply("querysend:instdirsearch:".
                   1945: 			   &escape($srch->{'srchby'}).':'.
                   1946: 			   &escape($srch->{'srchterm'}).':'.
                   1947: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1948: 	my $host=&hostname($homeserver);
                   1949: 	if ($queryid !~/^\Q$host\E\_/) {
1.1172.2.96  raeburn  1950: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 1951: 	    return;
                   1952: 	}
                   1953: 	my $response = &get_query_reply($queryid);
                   1954: 	my $maxtries = 5;
                   1955: 	my $tries = 1;
                   1956: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1957: 	    $response = &get_query_reply($queryid);
                   1958: 	    $tries ++;
                   1959: 	}
                   1960: 
                   1961:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1962:             if ($response eq 'unavailable') {
                   1963:                 $outcome = $response;
                   1964:             } else {
                   1965:                 $outcome = 'ok';
                   1966:                 my @matches = split(/\n/,$response);
                   1967:                 foreach my $match (@matches) {
                   1968:                     my ($key,$value) = split(/=/,$match);
                   1969:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1970:                 }
1.899     raeburn  1971:             }
                   1972:         }
                   1973:     }
1.909     raeburn  1974:     return ($outcome,%results);
1.899     raeburn  1975: }
                   1976: 
                   1977: sub usersearch {
                   1978:     my ($srch) = @_;
                   1979:     my $dom = $srch->{'srchdomain'};
                   1980:     my %results;
                   1981:     my %libserv = &all_library();
                   1982:     my $query = 'usersearch';
                   1983:     foreach my $tryserver (keys(%libserv)) {
                   1984:         if (&host_domain($tryserver) eq $dom) {
                   1985:             my $host=&hostname($tryserver);
                   1986:             my $queryid=
1.911     raeburn  1987:                 &reply("querysend:".&escape($query).':'.
                   1988:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1989:                        &escape($srch->{'srchtype'}).':'.
                   1990:                        &escape($srch->{'srchterm'}),$tryserver);
                   1991:             if ($queryid !~/^\Q$host\E\_/) {
                   1992:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1993:                 next;
1.899     raeburn  1994:             }
                   1995:             my $reply = &get_query_reply($queryid);
                   1996:             my $maxtries = 1;
                   1997:             my $tries = 1;
                   1998:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1999:                 $reply = &get_query_reply($queryid);
                   2000:                 $tries ++;
                   2001:             }
                   2002:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2003:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2004:             } else {
1.911     raeburn  2005:                 my @matches;
                   2006:                 if ($reply =~ /\n/) {
                   2007:                     @matches = split(/\n/,$reply);
                   2008:                 } else {
                   2009:                     @matches = split(/\&/,$reply);
                   2010:                 }
1.899     raeburn  2011:                 foreach my $match (@matches) {
                   2012:                     my ($uname,$udom,%userhash);
1.911     raeburn  2013:                     foreach my $entry (split(/:/,$match)) {
                   2014:                         my ($key,$value) =
                   2015:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2016:                         $userhash{$key} = $value;
                   2017:                         if ($key eq 'username') {
                   2018:                             $uname = $value;
                   2019:                         } elsif ($key eq 'domain') {
                   2020:                             $udom = $value;
1.911     raeburn  2021:                         }
1.899     raeburn  2022:                     }
                   2023:                     $results{$uname.':'.$udom} = \%userhash;
                   2024:                 }
                   2025:             }
                   2026:         }
                   2027:     }
                   2028:     return %results;
                   2029: }
                   2030: 
1.912     raeburn  2031: sub get_instuser {
                   2032:     my ($udom,$uname,$id) = @_;
                   2033:     my $homeserver = &domain($udom,'primary');
                   2034:     my ($outcome,%results);
                   2035:     if ($homeserver ne '') {
                   2036:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2037:                            &escape($id).':'.&escape($udom),$homeserver);
                   2038:         my $host=&hostname($homeserver);
                   2039:         if ($queryid !~/^\Q$host\E\_/) {
                   2040:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2041:             return;
                   2042:         }
                   2043:         my $response = &get_query_reply($queryid);
                   2044:         my $maxtries = 5;
                   2045:         my $tries = 1;
                   2046:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2047:             $response = &get_query_reply($queryid);
                   2048:             $tries ++;
                   2049:         }
                   2050:         if (!&error($response) && $response ne 'refused') {
                   2051:             if ($response eq 'unavailable') {
                   2052:                 $outcome = $response;
                   2053:             } else {
                   2054:                 $outcome = 'ok';
                   2055:                 my @matches = split(/\n/,$response);
                   2056:                 foreach my $match (@matches) {
                   2057:                     my ($key,$value) = split(/=/,$match);
                   2058:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2059:                 }
                   2060:             }
                   2061:         }
                   2062:     }
                   2063:     my %userinfo;
                   2064:     if (ref($results{$uname}) eq 'HASH') {
                   2065:         %userinfo = %{$results{$uname}};
                   2066:     } 
                   2067:     return ($outcome,%userinfo);
                   2068: }
                   2069: 
1.1172.2.69  raeburn  2070: sub get_multiple_instusers {
                   2071:     my ($udom,$users,$caller) = @_;
                   2072:     my ($outcome,$results);
                   2073:     if (ref($users) eq 'HASH') {
                   2074:         my $count = keys(%{$users});
                   2075:         my $requested = &freeze_escape($users);
                   2076:         my $homeserver = &domain($udom,'primary');
                   2077:         if ($homeserver ne '') {
                   2078:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2079:             my $host=&hostname($homeserver);
                   2080:             if ($queryid !~/^\Q$host\E\_/) {
                   2081:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2082:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2083:                 return ($outcome,$results);
                   2084:             }
                   2085:             my $response = &get_query_reply($queryid);
                   2086:             my $maxtries = 5;
                   2087:             if ($count > 100) {
                   2088:                 $maxtries = 1+int($count/20);
                   2089:             }
                   2090:             my $tries = 1;
                   2091:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2092:                 $response = &get_query_reply($queryid);
                   2093:                 $tries ++;
                   2094:             }
                   2095:             if ($response eq '') {
                   2096:                 $results = {};
                   2097:                 foreach my $key (keys(%{$users})) {
                   2098:                     my ($uname,$id);
                   2099:                     if ($caller eq 'id') {
                   2100:                         $id = $key;
                   2101:                     } else {
                   2102:                         $uname = $key;
                   2103:                     }
                   2104:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
                   2105:                     $outcome = $resp;
                   2106:                     if ($resp eq 'ok') {
                   2107:                         %{$results} = (%{$results}, %info);
                   2108:                     } else {
                   2109:                         last;
                   2110:                     }
                   2111:                 }
                   2112:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2113:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2114:                     $outcome = $response;
                   2115:                 } else {
                   2116:                     ($outcome,my $userdata) = split(/=/,$response,2);
                   2117:                     if ($outcome eq 'ok') {
                   2118:                         $results = &thaw_unescape($userdata);
                   2119:                     }
                   2120:                 }
                   2121:             }
                   2122:         }
                   2123:     }
                   2124:     return ($outcome,$results);
                   2125: }
                   2126: 
1.912     raeburn  2127: sub inst_rulecheck {
1.923     raeburn  2128:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2129:     my %returnhash;
                   2130:     if ($udom ne '') {
                   2131:         if (ref($rules) eq 'ARRAY') {
                   2132:             @{$rules} = map {&escape($_);} (@{$rules});
                   2133:             my $rulestr = join(':',@{$rules});
                   2134:             my $homeserver=&domain($udom,'primary');
                   2135:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2136:                 my $response;
                   2137:                 if ($item eq 'username') {                
                   2138:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2139:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2140:                                               $homeserver));
1.923     raeburn  2141:                 } elsif ($item eq 'id') {
                   2142:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2143:                                               ':'.&escape($id).':'.$rulestr,
                   2144:                                               $homeserver));
1.945     raeburn  2145:                 } elsif ($item eq 'selfcreate') {
                   2146:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2147:                                                &escape($udom).':'.&escape($uname).
                   2148:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2149:                 }
1.912     raeburn  2150:                 if ($response ne 'refused') {
                   2151:                     my @pairs=split(/\&/,$response);
                   2152:                     foreach my $item (@pairs) {
                   2153:                         my ($key,$value)=split(/=/,$item,2);
                   2154:                         $key = &unescape($key);
                   2155:                         next if ($key =~ /^error: 2 /);
                   2156:                         $returnhash{$key}=&thaw_unescape($value);
                   2157:                     }
                   2158:                 }
                   2159:             }
                   2160:         }
                   2161:     }
                   2162:     return %returnhash;
                   2163: }
                   2164: 
                   2165: sub inst_userrules {
1.923     raeburn  2166:     my ($udom,$check) = @_;
1.912     raeburn  2167:     my (%ruleshash,@ruleorder);
                   2168:     if ($udom ne '') {
                   2169:         my $homeserver=&domain($udom,'primary');
                   2170:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2171:             my $response;
                   2172:             if ($check eq 'id') {
                   2173:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2174:                                  $homeserver);
1.943     raeburn  2175:             } elsif ($check eq 'email') {
                   2176:                 $response=&reply('instemailrules:'.&escape($udom),
                   2177:                                  $homeserver);
1.923     raeburn  2178:             } else {
                   2179:                 $response=&reply('instuserrules:'.&escape($udom),
                   2180:                                  $homeserver);
                   2181:             }
1.912     raeburn  2182:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2183:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2184:                 ($response ne 'no_such_host')) {
                   2185:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2186:                 my @pairs=split(/\&/,$hashitems);
                   2187:                 foreach my $item (@pairs) {
                   2188:                     my ($key,$value)=split(/=/,$item,2);
                   2189:                     $key = &unescape($key);
                   2190:                     next if ($key =~ /^error: 2 /);
                   2191:                     $ruleshash{$key}=&thaw_unescape($value);
                   2192:                 }
                   2193:                 my @esc_order = split(/\&/,$orderitems);
                   2194:                 foreach my $item (@esc_order) {
                   2195:                     push(@ruleorder,&unescape($item));
                   2196:                 }
                   2197:             }
                   2198:         }
                   2199:     }
                   2200:     return (\%ruleshash,\@ruleorder);
                   2201: }
                   2202: 
1.976     raeburn  2203: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2204: 
                   2205: sub get_domain_defaults {
1.1172.2.35  raeburn  2206:     my ($domain,$ignore_cache) = @_;
                   2207:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2208:     my $cachetime = 60*60*24;
1.1172.2.35  raeburn  2209:     unless ($ignore_cache) {
                   2210:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2211:         if (defined($cached)) {
                   2212:             if (ref($result) eq 'HASH') {
                   2213:                 return %{$result};
                   2214:             }
1.943     raeburn  2215:         }
                   2216:     }
                   2217:     my %domdefaults;
                   2218:     my %domconfig =
1.989     raeburn  2219:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2220:                                   'requestcourses','inststatus',
1.1172.2.9  raeburn  2221:                                   'coursedefaults','usersessions',
1.1172.2.46  raeburn  2222:                                   'requestauthor','selfenrollment',
1.1172.2.89  raeburn  2223:                                   'coursecategories','autoenroll',
                   2224:                                   'helpsettings'],$domain);
1.1172.2.41  raeburn  2225:     my @coursetypes = ('official','unofficial','community','textbook');
1.943     raeburn  2226:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2227:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2228:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2229:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2230:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2231:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2232:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1172.2.91  raeburn  2233:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2234:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2235:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943     raeburn  2236:     } else {
                   2237:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2238:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2239:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2240:     }
1.976     raeburn  2241:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2242:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2243:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2244:         } else {
                   2245:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29  raeburn  2246:         }
1.1172.2.6  raeburn  2247:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2248:         foreach my $item (@usertools) {
                   2249:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2250:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2251:             }
                   2252:         }
1.1172.2.29  raeburn  2253:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2254:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2255:         }
1.976     raeburn  2256:     }
1.985     raeburn  2257:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37  raeburn  2258:         foreach my $item ('official','unofficial','community','textbook') {
1.985     raeburn  2259:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2260:         }
                   2261:     }
1.1172.2.9  raeburn  2262:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2263:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2264:     }
1.989     raeburn  2265:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44  raeburn  2266:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2267:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2268:         }
                   2269:     }
1.1047    raeburn  2270:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60  raeburn  2271:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2272:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2273:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2274:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2275:         }
1.1172.2.41  raeburn  2276:         foreach my $type (@coursetypes) {
                   2277:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2278:                 unless ($type eq 'community') {
                   2279:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2280:                 }
                   2281:             }
                   2282:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2283:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2284:             }
1.1172.2.60  raeburn  2285:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2286:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2287:                     $domdefaults{$type.'postsubtimeout'} =
                   2288:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
                   2289:                 }
                   2290:             }
1.1172.2.30  raeburn  2291:         }
1.1172.2.67  raeburn  2292:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2293:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2294:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2295:                 if (@clonecodes) {
                   2296:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2297:                 }
                   2298:             }
                   2299:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2300:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2301:         }
1.1172.2.103  raeburn  2302:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2303:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
                   2304:         }
1.1047    raeburn  2305:     }
1.1073    raeburn  2306:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2307:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2308:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2309:         }
                   2310:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2311:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2312:         }
1.1172.2.62  raeburn  2313:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2314:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2315:         }
1.1073    raeburn  2316:     }
1.1172.2.41  raeburn  2317:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2318:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2319:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2320:                             'approval','limit');
                   2321:             foreach my $type (@coursetypes) {
                   2322:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2323:                     my @mgrdc = ();
                   2324:                     foreach my $item (@settings) {
                   2325:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2326:                             push(@mgrdc,$item);
                   2327:                         }
                   2328:                     }
                   2329:                     if (@mgrdc) {
                   2330:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2331:                     }
                   2332:                 }
                   2333:             }
                   2334:         }
                   2335:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2336:             foreach my $type (@coursetypes) {
                   2337:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2338:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2339:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2340:                     }
                   2341:                 }
                   2342:             }
                   2343:         }
                   2344:     }
1.1172.2.46  raeburn  2345:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2346:         $domdefaults{'catauth'} = 'std';
                   2347:         $domdefaults{'catunauth'} = 'std';
                   2348:         if ($domconfig{'coursecategories'}{'auth'}) {
                   2349:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2350:         }
                   2351:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2352:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2353:         }
                   2354:     }
1.1172.2.76  raeburn  2355:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2356:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2357:     }
1.1172.2.89  raeburn  2358:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2359:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2360:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2361:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2362:         }
                   2363:     }
1.1172.2.23  raeburn  2364:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2365:     return %domdefaults;
                   2366: }
                   2367: 
1.1172.2.106  raeburn  2368: sub get_dom_cats {
                   2369:     my ($dom) = @_;
                   2370:     return unless (&domain($dom));
                   2371:     my ($cats,$cached)=&is_cached_new('cats',$dom);
                   2372:     unless (defined($cached)) {
                   2373:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
                   2374:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2375:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
                   2376:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
                   2377:             } else {
                   2378:                 $cats = {};
                   2379:             }
                   2380:         } else {
                   2381:             $cats = {};
                   2382:         }
                   2383:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
                   2384:     }
                   2385:     return $cats;
                   2386: }
                   2387: 
                   2388: sub get_dom_instcats {
                   2389:     my ($dom) = @_;
                   2390:     return unless (&domain($dom));
                   2391:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
                   2392:     unless (defined($cached)) {
                   2393:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
                   2394:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
                   2395:         if ($totcodes > 0) {
                   2396:             my $caller = 'global';
                   2397:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
                   2398:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
                   2399:                 $instcats = {
                   2400:                                 codes => \%codes,
                   2401:                                 codetitles => \@codetitles,
                   2402:                                 cat_titles => \%cat_titles,
                   2403:                                 cat_order => \%cat_order,
                   2404:                             };
                   2405:                 &do_cache_new('instcats',$dom,$instcats,3600);
                   2406:             }
                   2407:         }
                   2408:     }
                   2409:     return $instcats;
                   2410: }
                   2411: 
                   2412: sub retrieve_instcodes {
                   2413:     my ($coursecodes,$dom) = @_;
                   2414:     my $totcodes;
                   2415:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
                   2416:     foreach my $course (keys(%courses)) {
                   2417:         if (ref($courses{$course}) eq 'HASH') {
                   2418:             if ($courses{$course}{'inst_code'} ne '') {
                   2419:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
                   2420:                 $totcodes ++;
                   2421:             }
                   2422:         }
                   2423:     }
                   2424:     return $totcodes;
                   2425: }
                   2426: 
1.344     www      2427: # --------------------------------------------------- Assign a key to a student
                   2428: 
                   2429: sub assign_access_key {
1.364     www      2430: #
                   2431: # a valid key looks like uname:udom#comments
                   2432: # comments are being appended
                   2433: #
1.498     www      2434:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2435:     $kdom=
1.620     albertel 2436:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2437:     $knum=
1.620     albertel 2438:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2439:     $cdom=
1.620     albertel 2440:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2441:     $cnum=
1.620     albertel 2442:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2443:     $udom=$env{'user.name'} unless (defined($udom));
                   2444:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2445:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2446:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2447:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2448:                                                   # assigned to this person
                   2449:                                                   # - this should not happen,
1.345     www      2450:                                                   # unless something went wrong
                   2451:                                                   # the first time around
                   2452: # ready to assign
1.364     www      2453:         $logentry=$1.'; '.$logentry;
1.496     www      2454:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2455:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2456: # key now belongs to user
1.346     www      2457: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2458:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2459:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2460:                 return 'ok';
                   2461:             } else {
                   2462:                 return 
                   2463:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2464: 	    }
                   2465:         } else {
                   2466:             return 'error: Could not assign key, try again later.';
                   2467:         }
1.364     www      2468:     } elsif (!$existing{$ckey}) {
1.345     www      2469: # the key does not exist
                   2470: 	return 'error: The key does not exist';
                   2471:     } else {
                   2472: # the key is somebody else's
                   2473: 	return 'error: The key is already in use';
                   2474:     }
1.344     www      2475: }
                   2476: 
1.364     www      2477: # ------------------------------------------ put an additional comment on a key
                   2478: 
                   2479: sub comment_access_key {
                   2480: #
                   2481: # a valid key looks like uname:udom#comments
                   2482: # comments are being appended
                   2483: #
                   2484:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2485:     $cdom=
1.620     albertel 2486:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2487:     $cnum=
1.620     albertel 2488:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2489:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2490:     if ($existing{$ckey}) {
                   2491:         $existing{$ckey}.='; '.$logentry;
                   2492: # ready to assign
1.367     www      2493:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2494:                                                  $cdom,$cnum) eq 'ok') {
                   2495: 	    return 'ok';
                   2496:         } else {
                   2497: 	    return 'error: Count not store comment.';
                   2498:         }
                   2499:     } else {
                   2500: # the key does not exist
                   2501: 	return 'error: The key does not exist';
                   2502:     }
                   2503: }
                   2504: 
1.344     www      2505: # ------------------------------------------------------ Generate a set of keys
                   2506: 
                   2507: sub generate_access_keys {
1.364     www      2508:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2509:     $cdom=
1.620     albertel 2510:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2511:     $cnum=
1.620     albertel 2512:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2513:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2514:     unless (($cdom) && ($cnum)) { return 0; }
                   2515:     if ($number>10000) { return 0; }
                   2516:     sleep(2); # make sure don't get same seed twice
                   2517:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2518:     my $total=0;
                   2519:     for (my $i=1;$i<=$number;$i++) {
                   2520:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2521:                   sprintf("%lx",int(100000*rand)).'-'.
                   2522:                   sprintf("%lx",int(100000*rand));
                   2523:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2524:        $newkey=~s/0/h/g; # and also 0 and O
                   2525:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2526:        if ($existing{$newkey}) {
                   2527:            $i--;
                   2528:        } else {
1.364     www      2529: 	  if (&put('accesskeys',
                   2530:               { $newkey => '# generated '.localtime().
1.620     albertel 2531:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2532:                            '; '.$logentry },
                   2533: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2534:               $total++;
                   2535: 	  }
                   2536:        }
                   2537:     }
1.620     albertel 2538:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2539:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2540:     return $total;
                   2541: }
                   2542: 
                   2543: # ------------------------------------------------------- Validate an accesskey
                   2544: 
                   2545: sub validate_access_key {
                   2546:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2547:     $cdom=
1.620     albertel 2548:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2549:     $cnum=
1.620     albertel 2550:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2551:     $udom=$env{'user.domain'} unless (defined($udom));
                   2552:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2553:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2554:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2555: }
                   2556: 
                   2557: # ------------------------------------- Find the section of student in a course
1.652     albertel 2558: sub devalidate_getsection_cache {
                   2559:     my ($udom,$unam,$courseid)=@_;
                   2560:     my $hashid="$udom:$unam:$courseid";
                   2561:     &devalidate_cache_new('getsection',$hashid);
                   2562: }
1.298     matthew  2563: 
1.815     albertel 2564: sub courseid_to_courseurl {
                   2565:     my ($courseid) = @_;
                   2566:     #already url style courseid
                   2567:     return $courseid if ($courseid =~ m{^/});
                   2568: 
                   2569:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2570: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2571: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2572: 	return "/$cdom/$cnum";
                   2573:     }
                   2574: 
                   2575:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2576:     if (exists($courseinfo{'num'})) {
                   2577: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2578:     }
                   2579: 
                   2580:     return undef;
                   2581: }
                   2582: 
1.298     matthew  2583: sub getsection {
                   2584:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2585:     my $cachetime=1800;
1.551     albertel 2586: 
                   2587:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2588:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2589:     if (defined($cached)) { return $result; }
                   2590: 
1.298     matthew  2591:     my %Pending; 
                   2592:     my %Expired;
                   2593:     #
                   2594:     # Each role can either have not started yet (pending), be active, 
                   2595:     #    or have expired.
                   2596:     #
                   2597:     # If there is an active role, we are done.
                   2598:     #
                   2599:     # If there is more than one role which has not started yet, 
                   2600:     #     choose the one which will start sooner
                   2601:     # If there is one role which has not started yet, return it.
                   2602:     #
                   2603:     # If there is more than one expired role, choose the one which ended last.
                   2604:     # If there is a role which has expired, return it.
                   2605:     #
1.815     albertel 2606:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2607:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2608:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2609:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2610:         my $section=$1;
                   2611:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2612:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2613:         my $now=time;
1.548     albertel 2614:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2615:             $Expired{$end}=$section;
                   2616:             next;
                   2617:         }
1.548     albertel 2618:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2619:             $Pending{$start}=$section;
                   2620:             next;
                   2621:         }
1.599     albertel 2622:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2623:     }
                   2624:     #
                   2625:     # Presumedly there will be few matching roles from the above
                   2626:     # loop and the sorting time will be negligible.
                   2627:     if (scalar(keys(%Pending))) {
                   2628:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2629:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2630:     } 
                   2631:     if (scalar(keys(%Expired))) {
                   2632:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2633:         my $time = pop(@sorted);
1.599     albertel 2634:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2635:     }
1.599     albertel 2636:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2637: }
1.70      www      2638: 
1.599     albertel 2639: sub save_cache {
                   2640:     &purge_remembered();
1.722     albertel 2641:     #&Apache::loncommon::validate_page();
1.620     albertel 2642:     undef(%env);
1.780     albertel 2643:     undef($env_loaded);
1.599     albertel 2644: }
1.452     albertel 2645: 
1.599     albertel 2646: my $to_remember=-1;
                   2647: my %remembered;
                   2648: my %accessed;
                   2649: my $kicks=0;
                   2650: my $hits=0;
1.849     albertel 2651: sub make_key {
                   2652:     my ($name,$id) = @_;
1.872     albertel 2653:     if (length($id) > 65 
                   2654: 	&& length(&escape($id)) > 200) {
                   2655: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2656:     }
1.849     albertel 2657:     return &escape($name.':'.$id);
                   2658: }
                   2659: 
1.599     albertel 2660: sub devalidate_cache_new {
                   2661:     my ($name,$id,$debug) = @_;
                   2662:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81  raeburn  2663:     my $remembered_id=$name.':'.$id;
1.849     albertel 2664:     $id=&make_key($name,$id);
1.599     albertel 2665:     $memcache->delete($id);
1.1172.2.81  raeburn  2666:     delete($remembered{$remembered_id});
                   2667:     delete($accessed{$remembered_id});
1.599     albertel 2668: }
                   2669: 
                   2670: sub is_cached_new {
                   2671:     my ($name,$id,$debug) = @_;
1.1172.2.81  raeburn  2672:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for 
                   2673:                                      # keys in %remembered hash, which persists for
                   2674:                                      # duration of request (no restriction on key length).
                   2675:     if (exists($remembered{$remembered_id})) {
                   2676: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2677: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2678: 	$hits++;
1.1172.2.81  raeburn  2679: 	return ($remembered{$remembered_id},1);
1.599     albertel 2680:     }
1.1172.2.81  raeburn  2681:     $id=&make_key($name,$id);
1.599     albertel 2682:     my $value = $memcache->get($id);
                   2683:     if (!(defined($value))) {
                   2684: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2685: 	return (undef,undef);
1.416     albertel 2686:     }
1.599     albertel 2687:     if ($value eq '__undef__') {
                   2688: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2689: 	$value=undef;
                   2690:     }
1.1172.2.81  raeburn  2691:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2692:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2693:     return ($value,1);
                   2694: }
                   2695: 
                   2696: sub do_cache_new {
                   2697:     my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81  raeburn  2698:     my $remembered_id=$name.':'.$id;
1.849     albertel 2699:     $id=&make_key($name,$id);
1.599     albertel 2700:     my $setvalue=$value;
                   2701:     if (!defined($setvalue)) {
                   2702: 	$setvalue='__undef__';
                   2703:     }
1.623     albertel 2704:     if (!defined($time) ) {
                   2705: 	$time=600;
                   2706:     }
1.599     albertel 2707:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2708:     my $result = $memcache->set($id,$setvalue,$time);
                   2709:     if (! $result) {
1.872     albertel 2710: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2711: 	$memcache->disconnect_all();
1.872     albertel 2712:     }
1.600     albertel 2713:     # need to make a copy of $value
1.1172.2.81  raeburn  2714:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2715:     return $value;
                   2716: }
                   2717: 
                   2718: sub make_room {
1.1172.2.81  raeburn  2719:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 2720: 
1.1172.2.81  raeburn  2721:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 2722:                                     : $value;
1.599     albertel 2723:     if ($to_remember<0) { return; }
1.1172.2.81  raeburn  2724:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2725:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2726:     my $to_kick;
                   2727:     my $max_time=0;
                   2728:     foreach my $other (keys(%accessed)) {
                   2729: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2730: 	    $to_kick=$other;
                   2731: 	    $max_time=&tv_interval($accessed{$other});
                   2732: 	}
                   2733:     }
                   2734:     delete($remembered{$to_kick});
                   2735:     delete($accessed{$to_kick});
                   2736:     $kicks++;
                   2737:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2738:     return;
                   2739: }
                   2740: 
1.599     albertel 2741: sub purge_remembered {
1.604     albertel 2742:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2743:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2744:     undef(%remembered);
                   2745:     undef(%accessed);
1.428     albertel 2746: }
1.70      www      2747: # ------------------------------------- Read an entry from a user's environment
                   2748: 
                   2749: sub userenvironment {
                   2750:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2751:     my $items;
                   2752:     foreach my $item (@what) {
                   2753:         $items.=&escape($item).'&';
                   2754:     }
                   2755:     $items=~s/\&$//;
1.70      www      2756:     my %returnhash=();
1.1009    raeburn  2757:     my $uhome = &homeserver($unam,$udom);
                   2758:     unless ($uhome eq 'no_host') {
                   2759:         my @answer=split(/\&/, 
                   2760:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2761:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2762:             return %returnhash;
                   2763:         }
1.1009    raeburn  2764:         my $i;
                   2765:         for ($i=0;$i<=$#what;$i++) {
                   2766: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2767:         }
1.70      www      2768:     }
                   2769:     return %returnhash;
1.1       albertel 2770: }
                   2771: 
1.617     albertel 2772: # ---------------------------------------------------------- Get a studentphoto
                   2773: sub studentphoto {
                   2774:     my ($udom,$unam,$ext) = @_;
                   2775:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2776:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2777:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2778:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2779:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2780:             } else {
                   2781:                 my ($result,$perm_reqd)=
1.707     albertel 2782: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2783:                 if ($result eq 'ok') {
                   2784:                     if (!($perm_reqd eq 'yes')) {
                   2785:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2786:                     }
                   2787:                 }
                   2788:             }
                   2789:         }
                   2790:     } else {
                   2791:         my ($result,$perm_reqd) = 
1.707     albertel 2792: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2793:         if ($result eq 'ok') {
                   2794:             if (!($perm_reqd eq 'yes')) {
                   2795:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2796:             }
                   2797:         }
                   2798:     }
                   2799:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2800: }
                   2801: 
                   2802: sub retrievestudentphoto {
                   2803:     my ($udom,$unam,$ext,$type) = @_;
                   2804:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2805:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2806:     if ($ret eq 'ok') {
                   2807:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2808:         if ($type eq 'thumbnail') {
                   2809:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2810:         }
                   2811:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2812:         return $tokenurl;
                   2813:     } else {
                   2814:         if ($type eq 'thumbnail') {
                   2815:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2816:         } else { 
                   2817:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2818:         }
1.617     albertel 2819:     }
                   2820: }
                   2821: 
1.263     www      2822: # -------------------------------------------------------------------- New chat
                   2823: 
                   2824: sub chatsend {
1.724     raeburn  2825:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2826:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2827:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2828:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2829:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2830: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2831: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2832: }
                   2833: 
                   2834: # ------------------------------------------ Find current version of a resource
                   2835: 
                   2836: sub getversion {
                   2837:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  2838:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2839:     return &currentversion(&filelocation('',$fname));
                   2840: }
                   2841: 
                   2842: sub currentversion {
                   2843:     my $fname=shift;
                   2844:     my $author=$fname;
                   2845:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2846:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2847:     my $home=&homeserver($uname,$udom);
1.292     www      2848:     if ($home eq 'no_host') { 
                   2849:         return -1; 
                   2850:     }
1.1112    www      2851:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2852:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2853: 	return -1;
                   2854:     }
1.1112    www      2855:     return $answer;
1.263     www      2856: }
                   2857: 
1.1111    www      2858: #
                   2859: # Return special version number of resource if set by override, empty otherwise
                   2860: #
                   2861: sub usedversion {
                   2862:     my $fname=shift;
                   2863:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2864:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2865:     if ($urlversion) { return $urlversion; }
                   2866:     return '';
                   2867: }
                   2868: 
1.1       albertel 2869: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2870: 
1.1       albertel 2871: sub subscribe {
                   2872:     my $fname=shift;
1.761     raeburn  2873:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2874:     $fname=~s/[\n\r]//g;
1.1       albertel 2875:     my $author=$fname;
                   2876:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2877:     my ($udom,$uname)=split(/\//,$author);
                   2878:     my $home=homeserver($uname,$udom);
1.335     albertel 2879:     if ($home eq 'no_host') {
                   2880:         return 'not_found';
1.1       albertel 2881:     }
                   2882:     my $answer=reply("sub:$fname",$home);
1.64      www      2883:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2884: 	$answer.=' by '.$home;
                   2885:     }
1.1       albertel 2886:     return $answer;
                   2887: }
                   2888:     
1.8       www      2889: # -------------------------------------------------------------- Replicate file
                   2890: 
                   2891: sub repcopy {
                   2892:     my $filename=shift;
1.23      www      2893:     $filename=~s/\/+/\//g;
1.1142    raeburn  2894:     my $londocroot = $perlvar{'lonDocRoot'};
                   2895:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2896:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2897:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2898: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2899: 	return &repcopy_userfile($filename);
                   2900:     }
1.532     albertel 2901:     $filename=~s/[\n\r]//g;
1.8       www      2902:     my $transname="$filename.in.transfer";
1.828     www      2903: # FIXME: this should flock
1.607     raeburn  2904:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2905:     my $remoteurl=subscribe($filename);
1.64      www      2906:     if ($remoteurl =~ /^con_lost by/) {
                   2907: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2908:            return 'unavailable';
1.8       www      2909:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2910: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2911: 	   return 'not_found';
1.64      www      2912:     } elsif ($remoteurl =~ /^rejected by/) {
                   2913: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2914:            return 'forbidden';
1.20      www      2915:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2916:            return 'ok';
1.8       www      2917:     } else {
1.290     www      2918:         my $author=$filename;
                   2919:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2920:         my ($udom,$uname)=split(/\//,$author);
                   2921:         my $home=homeserver($uname,$udom);
                   2922:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2923:            my @parts=split(/\//,$filename);
                   2924:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2925:            if ($path ne "$londocroot/res") {
1.8       www      2926:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2927: 	       return 'bad_request';
1.8       www      2928:            }
                   2929:            my $count;
                   2930:            for ($count=5;$count<$#parts;$count++) {
                   2931:                $path.="/$parts[$count]";
                   2932:                if ((-e $path)!=1) {
                   2933: 		   mkdir($path,0777);
                   2934:                }
                   2935:            }
                   2936:            my $ua=new LWP::UserAgent;
                   2937:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2938:            my $response=$ua->request($request,$transname);
                   2939:            if ($response->is_error()) {
                   2940: 	       unlink($transname);
                   2941:                my $message=$response->status_line;
1.672     albertel 2942:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2943:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2944:                return 'unavailable';
1.8       www      2945:            } else {
1.16      www      2946: 	       if ($remoteurl!~/\.meta$/) {
                   2947:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2948:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2949:                   if ($mresponse->is_error()) {
                   2950: 		      unlink($filename.'.meta');
                   2951:                       &logthis(
1.672     albertel 2952:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2953:                   }
                   2954: 	       }
1.8       www      2955:                rename($transname,$filename);
1.607     raeburn  2956:                return 'ok';
1.8       www      2957:            }
1.290     www      2958:        }
1.8       www      2959:     }
1.330     www      2960: }
                   2961: 
                   2962: # ------------------------------------------------ Get server side include body
                   2963: sub ssi_body {
1.381     albertel 2964:     my ($filelink,%form)=@_;
1.606     matthew  2965:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2966:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2967:     }
1.953     www      2968:     my $output='';
                   2969:     my $response;
1.980     raeburn  2970:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2971:        ($output,$response)=&externalssi($filelink);
1.953     www      2972:     } else {
1.1004    droeschl 2973:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2974:        $filelink .= 'inhibitmenu=yes';
1.953     www      2975:        ($output,$response)=&ssi($filelink,%form);
                   2976:     }
1.778     albertel 2977:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2978:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2979:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2980:     if (wantarray) {
                   2981:         return ($output, $response);
                   2982:     } else {
                   2983:         return $output;
                   2984:     }
1.8       www      2985: }
                   2986: 
1.15      www      2987: # --------------------------------------------------------- Server Side Include
                   2988: 
1.782     albertel 2989: sub absolute_url {
                   2990:     my ($host_name) = @_;
                   2991:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2992:     if ($host_name eq '') {
                   2993: 	$host_name = $ENV{'SERVER_NAME'};
                   2994:     }
                   2995:     return $protocol.$host_name;
                   2996: }
                   2997: 
1.942     foxr     2998: #
                   2999: #   Server side include.
                   3000: # Parameters:
                   3001: #  fn     Possibly encrypted resource name/id.
                   3002: #  form   Hash that describes how the rendering should be done
                   3003: #         and other things.
1.944     foxr     3004: # Returns:
1.950     raeburn  3005: #   Scalar context: The content of the response.
                   3006: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3007: #     
1.15      www      3008: sub ssi {
                   3009: 
1.944     foxr     3010:     my ($fn,%form)=@_;
1.1172.2.100  raeburn  3011:     my ($request,$response);
1.711     albertel 3012: 
                   3013:     $form{'no_update_last_known'}=1;
1.895     albertel 3014:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3015:     if (%form) {
1.782     albertel 3016:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1172.2.58  raeburn  3017:       $request->content(join('&',map {
                   3018:             my $name = escape($_);
                   3019:             "$name=" . ( ref($form{$_}) eq 'ARRAY'
                   3020:             ? join("&$name=", map {escape($_) } @{$form{$_}})
                   3021:             : &escape($form{$_}) );
                   3022:         } keys(%form)));
1.23      www      3023:     } else {
1.782     albertel 3024:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      3025:     }
                   3026: 
1.15      www      3027:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.100  raeburn  3028: 
1.1172.2.101  raeburn  3029:     if (($env{'request.course.id'}) &&
                   3030:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
                   3031:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
                   3032:         ($form{'grade_symb'} ne '') &&
                   3033:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
                   3034:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
1.1172.2.100  raeburn  3035:         if (LWP::UserAgent->VERSION >= 5.834) {
                   3036:             my $ua=new LWP::UserAgent;
                   3037:             $ua->local_address('127.0.0.1');
                   3038:             $response = $ua->request($request);
                   3039:         } else {
                   3040:             {
                   3041:                 require LWP::Protocol::http;
                   3042:                 local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => '127.0.0.1');
                   3043:                 my $ua=new LWP::UserAgent;
                   3044:                 $response = $ua->request($request);
                   3045:                 @LWP::Protocol::http::EXTRA_SOCK_OPTS = ();
                   3046:             }
                   3047:         }
                   3048:     } else {
                   3049:         my $ua=new LWP::UserAgent;
                   3050:         $response = $ua->request($request);
                   3051:     }
1.944     foxr     3052:     if (wantarray) {
1.1172.2.3  raeburn  3053: 	return ($response->content, $response);
1.944     foxr     3054:     } else {
1.1172.2.3  raeburn  3055: 	return $response->content;
1.942     foxr     3056:     }
1.324     www      3057: }
                   3058: 
                   3059: sub externalssi {
                   3060:     my ($url)=@_;
                   3061:     my $ua=new LWP::UserAgent;
                   3062:     my $request=new HTTP::Request('GET',$url);
                   3063:     my $response=$ua->request($request);
1.954     raeburn  3064:     if (wantarray) {
                   3065:         return ($response->content, $response);
                   3066:     } else {
                   3067:         return $response->content;
                   3068:     }
1.15      www      3069: }
1.254     www      3070: 
1.1172.2.98  raeburn  3071: # If the local copy of a replicated resource is outdated, trigger a
                   3072: # connection from the homeserver to flush the delayed queue. If no update
                   3073: # happens, remove local copies of outdated resource (and corresponding
                   3074: # metadata file).
                   3075: 
                   3076: sub remove_stale_resfile {
                   3077:     my ($url) = @_;
                   3078:     my $removed;
                   3079:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3080:         my $audom = $1;
                   3081:         my $auname = $2;
                   3082:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
                   3083:             my $homeserver = &homeserver($auname,$audom);
                   3084:             unless (($homeserver eq 'no_host') ||
                   3085:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3086:                 my $fname = &filelocation('',$url);
                   3087:                 if (-e $fname) {
                   3088:                     my $ua=new LWP::UserAgent;
                   3089:                     $ua->timeout(5);
                   3090:                     my $protocol = $protocol{$homeserver};
                   3091:                     $protocol = 'http' if ($protocol ne 'https');
                   3092:                     my $hostname = &hostname($homeserver);
                   3093:                     if ($hostname) {
                   3094:                         my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
                   3095:                         my $request=new HTTP::Request('HEAD',$uri);
                   3096:                         my $response=$ua->request($request);
                   3097:                         if ($response->is_success()) {
                   3098:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3099:                             my $locmodtime = (stat($fname))[9];
                   3100:                             if ($locmodtime < $remmodtime) {
                   3101:                                 my $stale;
                   3102:                                 my $answer = &reply('pong',$homeserver);
                   3103:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3104:                                     sleep(0.2);
                   3105:                                     $locmodtime = (stat($fname))[9];
                   3106:                                     if ($locmodtime < $remmodtime) {
                   3107:                                         my $posstransfer = $fname.'.in.transfer';
                   3108:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3109:                                             $removed = 1;
                   3110:                                         } else {
                   3111:                                             $stale = 1;
                   3112:                                         }
                   3113:                                     } else {
                   3114:                                         $removed = 1;
                   3115:                                     }
                   3116:                                 } else {
                   3117:                                     $stale = 1;
                   3118:                                 }
                   3119:                                 if ($stale) {
                   3120:                                     unlink($fname);
                   3121:                                     if ($uri!~/\.meta$/) {
                   3122:                                         unlink($fname.'.meta');
                   3123:                                     }
                   3124:                                     &reply("unsub:$fname",$homeserver);
                   3125:                                     $removed = 1;
                   3126:                                 }
                   3127:                             }
                   3128:                         }
                   3129:                     }
                   3130:                 }
                   3131:             }
                   3132:         }
                   3133:     }
                   3134:     return $removed;
                   3135: }
                   3136: 
1.492     albertel 3137: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3138: 
                   3139: sub allowuploaded {
                   3140:     my ($srcurl,$url)=@_;
                   3141:     $url=&clutter(&declutter($url));
                   3142:     my $dir=$url;
                   3143:     $dir=~s/\/[^\/]+$//;
                   3144:     my %httpref=();
                   3145:     my $httpurl=&hreflocation('',$url);
                   3146:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3147:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3148: }
1.477     raeburn  3149: 
1.1172.2.13  raeburn  3150: #
                   3151: # Determine if the current user should be able to edit a particular resource,
                   3152: # when viewing in course context.
                   3153: # (a) When viewing resource used to determine if "Edit" item is included in
                   3154: #     Functions.
                   3155: # (b) When displaying folder contents in course editor, used to determine if
                   3156: #     "Edit" link will be displayed alongside resource.
                   3157: #
                   3158: #  input: six args -- filename (decluttered), course number, course domain,
                   3159: #                   url, symb (if registered) and group (if this is a group
                   3160: #                   item -- e.g., bulletin board, group page etc.).
                   3161: #  output: array of five scalars --
                   3162: #          $cfile -- url for file editing if editable on current server
                   3163: #          $home -- homeserver of resource (i.e., for author if published,
                   3164: #                                           or course if uploaded.).
                   3165: #          $switchserver --  1 if server switch will be needed.
                   3166: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   3167: #          $forceview -- 1 if icon/link should be to go to view mode
                   3168: #
                   3169: 
                   3170: sub can_edit_resource {
                   3171:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3172:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3173: #
                   3174: # For aboutme pages user can only edit his/her own.
                   3175: #
                   3176:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   3177:         my ($sdom,$sname) = ($1,$2);
                   3178:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3179:             $home = $env{'user.home'};
                   3180:             $cfile = $resurl;
                   3181:             if ($env{'form.forceedit'}) {
                   3182:                 $forceview = 1;
                   3183:             } else {
                   3184:                 $forceedit = 1;
                   3185:             }
                   3186:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3187:         } else {
                   3188:             return;
                   3189:         }
                   3190:     }
                   3191: 
                   3192:     if ($env{'request.course.id'}) {
                   3193:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3194:         if ($group ne '') {
                   3195: # if this is a group homepage or group bulletin board, check group privs
                   3196:             my $allowed = 0;
                   3197:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3198:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   3199:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3200:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3201:                     $allowed = 1;
                   3202:                 }
                   3203:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3204:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3205:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3206:                     $allowed = 1;
                   3207:                 }
                   3208:             }
                   3209:             if ($allowed) {
                   3210:                 $home=&homeserver($cnum,$cdom);
                   3211:                 if ($env{'form.forceedit'}) {
                   3212:                     $forceview = 1;
                   3213:                 } else {
                   3214:                     $forceedit = 1;
                   3215:                 }
                   3216:                 $cfile = $resurl;
                   3217:             } else {
                   3218:                 return;
                   3219:             }
                   3220:         } else {
1.1172.2.15  raeburn  3221:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3222:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3223:                     return;
                   3224:                 }
                   3225:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  3226: #
                   3227: # No edit allowed where CC has switched to student role.
                   3228: #
                   3229:                 return;
                   3230:             }
                   3231:         }
                   3232:     }
                   3233: 
                   3234:     if ($file ne '') {
                   3235:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   3236:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3237:                 $uploaded = 1;
                   3238:                 $incourse = 1;
                   3239:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3240:                     $cfile = &hreflocation('',$file);
                   3241:                     if ($env{'form.forceedit'}) {
                   3242:                         $forceview = 1;
                   3243:                     } else {
                   3244:                         $forceedit = 1;
                   3245:                     }
                   3246:                 }
                   3247:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3248:                 $incourse = 1;
                   3249:                 if ($env{'form.forceedit'}) {
                   3250:                     $forceview = 1;
                   3251:                 } else {
                   3252:                     $forceedit = 1;
                   3253:                 }
                   3254:                 $cfile = $resurl;
                   3255:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   3256:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3257:                     $incourse = 1;
                   3258:                     if ($env{'form.forceedit'}) {
                   3259:                         $forceview = 1;
                   3260:                     } else {
                   3261:                         $forceedit = 1;
                   3262:                     }
                   3263:                     $cfile = $resurl;
                   3264:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   3265:                     $incourse = 1;
                   3266:                     $cfile = $resurl.'/smpedit';
                   3267:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   3268:                     $incourse = 1;
                   3269:                     if ($env{'form.forceedit'}) {
                   3270:                         $forceview = 1;
                   3271:                     } else {
                   3272:                         $forceedit = 1;
                   3273:                     }
                   3274:                     $cfile = $resurl;
1.1172.2.15  raeburn  3275:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3276:                     $incourse = 1;
                   3277:                     if ($env{'form.forceedit'}) {
                   3278:                         $forceview = 1;
                   3279:                     } else {
                   3280:                         $forceedit = 1;
                   3281:                     }
                   3282:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3283:                 }
                   3284:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3285:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3286:                 if (&is_on_map($template)) {
                   3287:                     $incourse = 1;
                   3288:                     $forceview = 1;
                   3289:                     $cfile = $template;
                   3290:                 }
                   3291:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3292:                     $incourse = 1;
                   3293:                     if ($env{'form.forceedit'}) {
                   3294:                         $forceview = 1;
                   3295:                     } else {
                   3296:                         $forceedit = 1;
                   3297:                     }
                   3298:                     $cfile = $resurl;
                   3299:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3300:                 $incourse = 1;
                   3301:                 $forceview = 1;
                   3302:                 if ($symb) {
                   3303:                     my ($map,$id,$res)=&decode_symb($symb);
                   3304:                     $env{'request.symb'} = $symb;
                   3305:                     $cfile = &clutter($res);
                   3306:                 } else {
                   3307:                     $cfile = $env{'form.suppurl'};
                   3308:                     $cfile =~ s{^http://}{};
                   3309:                     $cfile = '/adm/wrapper/ext/'.$cfile;
                   3310:                 }
1.1172.2.31  raeburn  3311:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3312:                 if ($env{'form.forceedit'}) {
                   3313:                     $forceview = 1;
                   3314:                 } else {
                   3315:                     $forceedit = 1;
                   3316:                 }
                   3317:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3318:             }
                   3319:         }
                   3320:         if ($uploaded || $incourse) {
                   3321:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  3322:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  3323:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3324:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3325:             # Check that the user has permission to edit this resource
                   3326:             my $setpriv = 1;
                   3327:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3328:             if (defined($cfudom)) {
                   3329:                 $home=&homeserver($cfuname,$cfudom);
                   3330:                 $cfile=$file;
                   3331:             }
                   3332:         }
                   3333:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   3334:             (($home ne '') && ($home ne 'no_host'))) {
                   3335:             my @ids=&current_machine_ids();
                   3336:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3337:                 $switchserver=1;
                   3338:             }
                   3339:         }
                   3340:     }
                   3341:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3342: }
                   3343: 
                   3344: sub is_course_upload {
                   3345:     my ($file,$cnum,$cdom) = @_;
                   3346:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3347:     $uploadpath =~ s{^\/}{};
                   3348:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3349:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   3350:         return 1;
                   3351:     }
                   3352:     return;
                   3353: }
                   3354: 
                   3355: sub in_course {
                   3356:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3357:     if ($hideprivileged) {
                   3358:         my $skipuser;
1.1172.2.23  raeburn  3359:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3360:         my @possdoms = ($cdom);
                   3361:         if ($coursehash{'checkforpriv'}) {
                   3362:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   3363:         }
                   3364:         if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13  raeburn  3365:             $skipuser = 1;
                   3366:             if ($coursehash{'nothideprivileged'}) {
                   3367:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3368:                     my $user;
                   3369:                     if ($item =~ /:/) {
                   3370:                         $user = $item;
                   3371:                     } else {
                   3372:                         $user = join(':',split(/[\@]/,$item));
                   3373:                     }
                   3374:                     if ($user eq $uname.':'.$udom) {
                   3375:                         undef($skipuser);
                   3376:                         last;
                   3377:                     }
                   3378:                 }
                   3379:             }
                   3380:             if ($skipuser) {
                   3381:                 return 0;
                   3382:             }
                   3383:         }
                   3384:     }
                   3385:     $type ||= 'any';
                   3386:     if (!defined($cdom) || !defined($cnum)) {
                   3387:         my $cid  = $env{'request.course.id'};
                   3388:         $cdom = $env{'course.'.$cid.'.domain'};
                   3389:         $cnum = $env{'course.'.$cid.'.num'};
                   3390:     }
                   3391:     my $typesref;
                   3392:     if (($type eq 'any') || ($type eq 'all')) {
                   3393:         $typesref = ['active','previous','future'];
                   3394:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3395:         $typesref = [$type];
                   3396:     }
                   3397:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3398:                               $typesref,undef,[$cdom]);
                   3399:     my ($tmp) = keys(%roles);
                   3400:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3401:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3402:     if (@course_roles > 0) {
                   3403:         return 1;
                   3404:     }
                   3405:     return 0;
                   3406: }
                   3407: 
1.478     albertel 3408: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3409: # input: action, courseID, current domain, intended
1.637     raeburn  3410: #        path to file, source of file, instruction to parse file for objects,
                   3411: #        ref to hash for embedded objects,
                   3412: #        ref to hash for codebase of java objects.
1.1095    raeburn  3413: #        reference to scalar to accommodate mime type determined
                   3414: #          from File::MMagic if $parser = parse.
1.637     raeburn  3415: #
1.485     raeburn  3416: # output: url to file (if action was uploaddoc), 
                   3417: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3418: #
1.478     albertel 3419: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3420: # course.
1.477     raeburn  3421: #
1.478     albertel 3422: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3423: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3424: #          course's home server.
1.477     raeburn  3425: #
1.478     albertel 3426: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3427: #          be copied from $source (current location) to 
                   3428: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3429: #         and will then be copied to
                   3430: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3431: #         course's home server.
1.485     raeburn  3432: #
1.481     raeburn  3433: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3434: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3435: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3436: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3437: #         in course's home server.
1.637     raeburn  3438: #
1.477     raeburn  3439: 
                   3440: sub process_coursefile {
1.1095    raeburn  3441:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3442:         $mimetype)=@_;
1.477     raeburn  3443:     my $fetchresult;
1.638     albertel 3444:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3445:     if ($action eq 'propagate') {
1.638     albertel 3446:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3447: 			     $home);
1.481     raeburn  3448:     } else {
1.477     raeburn  3449:         my $fpath = '';
                   3450:         my $fname = $file;
1.478     albertel 3451:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3452:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3453:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3454:         if ($action eq 'copy') {
                   3455:             if ($source eq '') {
                   3456:                 $fetchresult = 'no source file';
                   3457:                 return $fetchresult;
                   3458:             } else {
                   3459:                 my $destination = $filepath.'/'.$fname;
                   3460:                 rename($source,$destination);
                   3461:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3462:                                  $home);
1.481     raeburn  3463:             }
                   3464:         } elsif ($action eq 'uploaddoc') {
1.1172.2.96  raeburn  3465:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3466:             print $fh $env{'form.'.$source};
1.481     raeburn  3467:             close($fh);
1.637     raeburn  3468:             if ($parser eq 'parse') {
1.1024    raeburn  3469:                 my $mm = new File::MMagic;
1.1095    raeburn  3470:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3471:                 if ($type eq 'text/html') {
1.1024    raeburn  3472:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3473:                     unless ($parse_result eq 'ok') {
                   3474:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3475:                     }
1.637     raeburn  3476:                 }
1.1095    raeburn  3477:                 if (ref($mimetype)) {
                   3478:                     $$mimetype = $type;
                   3479:                 } 
1.637     raeburn  3480:             }
1.477     raeburn  3481:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3482:                                  $home);
1.481     raeburn  3483:             if ($fetchresult eq 'ok') {
                   3484:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3485:             } else {
                   3486:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3487:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3488:                 return '/adm/notfound.html';
                   3489:             }
1.477     raeburn  3490:         }
                   3491:     }
1.485     raeburn  3492:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3493:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3494:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3495:     }
                   3496:     return $fetchresult;
                   3497: }
                   3498: 
1.637     raeburn  3499: sub build_filepath {
                   3500:     my ($fpath) = @_;
                   3501:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3502:     unless ($fpath eq '') {
                   3503:         my @parts=split('/',$fpath);
                   3504:         foreach my $part (@parts) {
                   3505:             $filepath.= '/'.$part;
                   3506:             if ((-e $filepath)!=1) {
                   3507:                 mkdir($filepath,0777);
                   3508:             }
                   3509:         }
                   3510:     }
                   3511:     return $filepath;
                   3512: }
                   3513: 
                   3514: sub store_edited_file {
1.638     albertel 3515:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3516:     my $file = $primary_url;
                   3517:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3518:     my $fpath = '';
                   3519:     my $fname = $file;
                   3520:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3521:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3522:     my $filepath = &build_filepath($fpath);
1.1172.2.96  raeburn  3523:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  3524:     print $fh $content;
                   3525:     close($fh);
1.638     albertel 3526:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3527:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3528: 			  $home);
1.637     raeburn  3529:     if ($$fetchresult eq 'ok') {
                   3530:         return '/uploaded/'.$fpath.'/'.$fname;
                   3531:     } else {
1.638     albertel 3532:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3533: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3534:         return '/adm/notfound.html';
                   3535:     }
                   3536: }
                   3537: 
1.531     albertel 3538: sub clean_filename {
1.831     albertel 3539:     my ($fname,$args)=@_;
1.315     www      3540: # Replace Windows backslashes by forward slashes
1.257     www      3541:     $fname=~s/\\/\//g;
1.831     albertel 3542:     if (!$args->{'keep_path'}) {
                   3543:         # Get rid of everything but the actual filename
                   3544: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3545:     }
1.315     www      3546: # Replace spaces by underscores
                   3547:     $fname=~s/\s+/\_/g;
                   3548: # Replace all other weird characters by nothing
1.831     albertel 3549:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3550: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3551: # numbers
                   3552:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3553:     return $fname;
                   3554: }
1.1051    raeburn  3555: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3556: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3557: # image with the same aspect ratio as the original, but with dimensions which do 
                   3558: # not exceed $resizewidth and $resizeheight.
                   3559:  
1.984     neumanie 3560: sub resizeImage {
1.1051    raeburn  3561:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3562:     my $ima = Image::Magick->new;
                   3563:     my $resized;
                   3564:     if (-e $img_path) {
                   3565:         $ima->Read($img_path);
                   3566:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3567:             my $width = $ima->Get('width');
                   3568:             my $height = $ima->Get('height');
                   3569:             if ($width > $resizewidth) {
                   3570: 	        my $factor = $width/$resizewidth;
                   3571:                 my $newheight = $height/$factor;
                   3572:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3573:                 $resized = 1;
                   3574:             }
                   3575:         }
                   3576:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3577:             my $width = $ima->Get('width');
                   3578:             my $height = $ima->Get('height');
                   3579:             if ($height > $resizeheight) {
                   3580:                 my $factor = $height/$resizeheight;
                   3581:                 my $newwidth = $width/$factor;
                   3582:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3583:                 $resized = 1;
                   3584:             }
                   3585:         }
                   3586:         if ($resized) {
                   3587:             $ima->Write($img_path);
                   3588:         }
                   3589:     }
                   3590:     return;
1.977     amueller 3591: }
                   3592: 
1.608     albertel 3593: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3594: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3595: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3596: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3597: #                                    canceloverwrite, or ''. 
                   3598: #                   if 'coursedoc': upload to the current course
                   3599: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3600: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3601: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3602: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3603: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3604: #        $allfiles - reference to hash for embedded objects
                   3605: #        $codebase - reference to hash for codebase of java objects
                   3606: #        $desuname - username for permanent storage of uploaded file
                   3607: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3608: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3609: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3610: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3611: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3612: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3613: #                    from File::MMagic.
1.858     raeburn  3614: # 
1.686     albertel 3615: # output: url of file in userspace, or error: <message> 
                   3616: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3617: 
1.531     albertel 3618: sub userfileupload {
1.1090    raeburn  3619:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3620:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3621:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3622:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3623:     $fname=&clean_filename($fname);
1.1090    raeburn  3624:     # See if there is anything left
1.257     www      3625:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3626:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3627:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3628:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3629:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3630:         my $now = time;
1.1090    raeburn  3631:         my $filepath;
1.1095    raeburn  3632:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3633:              $filepath = 'tmp/helprequests/'.$now;
                   3634:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3635:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3636:                          '_'.$env{'user.domain'}.'/pending';
                   3637:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3638:             my ($docuname,$docudom);
1.1172.2.96  raeburn  3639:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  3640:                 $docudom = $destudom;
                   3641:             } else {
                   3642:                 $docudom = $env{'user.domain'};
                   3643:             }
1.1172.2.96  raeburn  3644:             if ($destuname =~ /^$match_username$/) { 
1.1090    raeburn  3645:                 $docuname = $destuname;
                   3646:             } else {
                   3647:                 $docuname = $env{'user.name'};
                   3648:             }
                   3649:             if (exists($env{'form.group'})) {
                   3650:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3651:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3652:             }
                   3653:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3654:             if ($context eq 'canceloverwrite') {
                   3655:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3656:                 if (-e  $tempfile) {
                   3657:                     my @info = stat($tempfile);
                   3658:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3659:                         unlink($tempfile);
                   3660:                     }
                   3661:                 }
                   3662:                 return;
1.523     raeburn  3663:             }
                   3664:         }
1.1090    raeburn  3665:         # Create the directory if not present
1.741     raeburn  3666:         my @parts=split(/\//,$filepath);
                   3667:         my $fullpath = $perlvar{'lonDaemons'};
                   3668:         for (my $i=0;$i<@parts;$i++) {
                   3669:             $fullpath .= '/'.$parts[$i];
                   3670:             if ((-e $fullpath)!=1) {
                   3671:                 mkdir($fullpath,0777);
                   3672:             }
                   3673:         }
1.1172.2.96  raeburn  3674:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  3675:         print $fh $env{'form.'.$formname};
                   3676:         close($fh);
1.1090    raeburn  3677:         if ($context eq 'existingfile') {
                   3678:             my @info = stat($fullpath.'/'.$fname);
                   3679:             return ($fullpath.'/'.$fname,$info[9]);
                   3680:         } else {
                   3681:             return $fullpath.'/'.$fname;
                   3682:         }
1.523     raeburn  3683:     }
1.995     raeburn  3684:     if ($subdir eq 'scantron') {
                   3685:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3686:     } else {
1.995     raeburn  3687:         $fname="$subdir/$fname";
                   3688:     }
1.1090    raeburn  3689:     if ($context eq 'coursedoc') {
1.638     albertel 3690: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3691: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3692:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3693:             return &finishuserfileupload($docuname,$docudom,
                   3694: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3695: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3696:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3697:         } else {
1.1172.2.21  raeburn  3698:             if ($env{'form.folder'}) {
                   3699:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3700:             }
1.638     albertel 3701:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3702: 				       $fname,$formname,$parser,
1.1095    raeburn  3703: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3704:         }
1.719     banghart 3705:     } elsif (defined($destuname)) {
                   3706:         my $docuname=$destuname;
                   3707:         my $docudom=$destudom;
1.860     raeburn  3708: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3709: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3710:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3711:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3712:     } else {
1.638     albertel 3713:         my $docuname=$env{'user.name'};
                   3714:         my $docudom=$env{'user.domain'};
1.1172.2.23  raeburn  3715:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3716:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3717:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3718:         }
1.860     raeburn  3719: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3720: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3721:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3722:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3723:     }
1.271     www      3724: }
                   3725: 
                   3726: sub finishuserfileupload {
1.860     raeburn  3727:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3728:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3729:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3730:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3731:   
1.860     raeburn  3732:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3733:     $file=$fname;
                   3734:     if ($fname=~m|/|) {
                   3735:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3736: 	$path.=$fnamepath.'/';
                   3737:     }
1.259     www      3738:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3739:     my $count;
                   3740:     for ($count=4;$count<=$#parts;$count++) {
                   3741:         $filepath.="/$parts[$count]";
                   3742:         if ((-e $filepath)!=1) {
                   3743: 	    mkdir($filepath,0777);
                   3744:         }
                   3745:     }
1.984     neumanie 3746: 
1.258     www      3747: # Save the file
                   3748:     {
1.1172.2.96  raeburn  3749: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 3750: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3751: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3752: 	    return '/adm/notfound.html';
                   3753: 	}
1.1090    raeburn  3754:         if ($context eq 'overwrite') {
1.1117    foxr     3755:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3756:             my $target = $filepath.'/'.$file;
                   3757:             if (-e $source) {
                   3758:                 my @info = stat($source);
                   3759:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3760:                     unless (&File::Copy::move($source,$target)) {
                   3761:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3762:                         return "Moving from $source failed";
                   3763:                     }
                   3764:                 } else {
                   3765:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3766:                 }
                   3767:             } else {
                   3768:                 return "Temporary file: $source missing";
                   3769:             }
                   3770:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3771: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3772: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3773: 	    return '/adm/notfound.html';
                   3774: 	}
1.570     albertel 3775: 	close(FH);
1.1051    raeburn  3776:         if ($resizewidth && $resizeheight) {
                   3777:             my $mm = new File::MMagic;
                   3778:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3779:             if ($mime_type =~ m{^image/}) {
                   3780: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3781:             }  
1.977     amueller 3782: 	}
1.258     www      3783:     }
1.1152    raeburn  3784:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3785:         if (ref($mimetype)) {
                   3786:             if ($$mimetype eq '') {
                   3787:                 my $mm = new File::MMagic;
                   3788:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3789:                 $$mimetype = $type;
                   3790:             }
                   3791:         }
                   3792:     }
1.637     raeburn  3793:     if ($parser eq 'parse') {
1.1152    raeburn  3794:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3795:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3796:                                                        $allfiles,$codebase);
                   3797:             unless ($parse_result eq 'ok') {
                   3798:                 &logthis('Failed to parse '.$filepath.$file.
                   3799: 	   	         ' for embedded media: '.$parse_result); 
                   3800:             }
1.637     raeburn  3801:         }
                   3802:     }
1.860     raeburn  3803:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3804:         my $input = $filepath.'/'.$file;
                   3805:         my $output = $filepath.'/'.'tn-'.$file;
                   3806:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1172.2.96  raeburn  3807:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   3808:         system({$args[0]} @args);
1.860     raeburn  3809:         if (-e $filepath.'/'.'tn-'.$file) {
                   3810:             $fetchthumb  = 1; 
                   3811:         }
                   3812:     }
1.858     raeburn  3813:  
1.259     www      3814: # Notify homeserver to grep it
                   3815: #
1.984     neumanie 3816:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3817:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3818:     if ($fetchresult eq 'ok') {
1.860     raeburn  3819:         if ($fetchthumb) {
                   3820:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3821:             if ($thumbresult ne 'ok') {
                   3822:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3823:                          $docuhome.': '.$thumbresult);
                   3824:             }
                   3825:         }
1.259     www      3826: #
1.258     www      3827: # Return the URL to it
1.494     albertel 3828:         return '/uploaded/'.$path.$file;
1.263     www      3829:     } else {
1.494     albertel 3830:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3831: 		 ': '.$fetchresult);
1.263     www      3832:         return '/adm/notfound.html';
1.858     raeburn  3833:     }
1.493     albertel 3834: }
                   3835: 
1.637     raeburn  3836: sub extract_embedded_items {
1.961     raeburn  3837:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3838:     my @state = ();
1.1164    raeburn  3839:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3840:     my %javafiles = (
                   3841:                       codebase => '',
                   3842:                       code => '',
                   3843:                       archive => ''
                   3844:                     );
                   3845:     my %mediafiles = (
                   3846:                       src => '',
                   3847:                       movie => '',
                   3848:                      );
1.648     raeburn  3849:     my $p;
                   3850:     if ($content) {
                   3851:         $p = HTML::LCParser->new($content);
                   3852:     } else {
1.961     raeburn  3853:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3854:     }
1.641     albertel 3855:     while (my $t=$p->get_token()) {
1.640     albertel 3856: 	if ($t->[0] eq 'S') {
                   3857: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3858: 	    push(@state, $tagname);
1.648     raeburn  3859:             if (lc($tagname) eq 'allow') {
                   3860:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3861:             }
1.640     albertel 3862: 	    if (lc($tagname) eq 'img') {
                   3863: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3864: 	    }
1.886     albertel 3865: 	    if (lc($tagname) eq 'a') {
1.1172.2.24  raeburn  3866:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
                   3867: 		    &add_filetype($allfiles,$attr->{'href'},'href');
                   3868:                 }
1.886     albertel 3869: 	    }
1.645     raeburn  3870:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3871:                 my $src;
1.645     raeburn  3872:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3873:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3874:                 } else {
1.1164    raeburn  3875:                     if ($attr->{'src'} ne '') {
                   3876:                         $src = $attr->{'src'};
                   3877:                         &add_filetype($allfiles,$src,'src');
                   3878:                     }
                   3879:                 }
                   3880:                 my $text = $p->get_trimmed_text();
                   3881:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3882:                     my @swfargs = split(/,/,$1);
                   3883:                     foreach my $item (@swfargs) {
                   3884:                         $item =~ s/["']//g;
                   3885:                         $item =~ s/^\s+//;
                   3886:                         $item =~ s/\s+$//;
                   3887:                     }
                   3888:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3889:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3890:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3891:                         } else {
                   3892:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3893:                         }
                   3894:                     }
1.645     raeburn  3895:                 }
                   3896:             }
                   3897:             if (lc($tagname) eq 'link') {
                   3898:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3899:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3900:                 }
                   3901:             }
1.640     albertel 3902: 	    if (lc($tagname) eq 'object' ||
                   3903: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3904: 		foreach my $item (keys(%javafiles)) {
                   3905: 		    $javafiles{$item} = '';
                   3906: 		}
1.1164    raeburn  3907:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3908:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3909:                 }
1.640     albertel 3910: 	    }
                   3911: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3912: 		my $name = lc($attr->{'name'});
                   3913: 		foreach my $item (keys(%javafiles)) {
                   3914: 		    if ($name eq $item) {
                   3915: 			$javafiles{$item} = $attr->{'value'};
                   3916: 			last;
                   3917: 		    }
                   3918: 		}
1.1164    raeburn  3919:                 my $pathfrom;
1.640     albertel 3920: 		foreach my $item (keys(%mediafiles)) {
                   3921: 		    if ($name eq $item) {
1.1164    raeburn  3922:                         $pathfrom = $attr->{'value'};
                   3923:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3924: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3925: 			last;
                   3926: 		    }
                   3927: 		}
1.1164    raeburn  3928:                 if ($name eq 'flashvars') {
                   3929:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3930:                 }
                   3931:                 if ($pathfrom ne '') {
                   3932:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3933:                                          $pathfrom);
                   3934:                 }
1.640     albertel 3935: 	    }
                   3936: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3937: 		foreach my $item (keys(%javafiles)) {
                   3938: 		    if ($attr->{$item}) {
                   3939: 			$javafiles{$item} = $attr->{$item};
                   3940: 			last;
                   3941: 		    }
                   3942: 		}
                   3943: 		foreach my $item (keys(%mediafiles)) {
                   3944: 		    if ($attr->{$item}) {
                   3945: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3946: 			last;
                   3947: 		    }
                   3948: 		}
1.1164    raeburn  3949:                 if (lc($tagname) eq 'embed') {
                   3950:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3951:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3952:                                              $attr->{'src'});
                   3953:                     }
                   3954:                 }
1.640     albertel 3955: 	    }
1.1172.2.35  raeburn  3956:             if (lc($tagname) eq 'iframe') {
                   3957:                 my $src = $attr->{'src'} ;
                   3958:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   3959:                     &add_filetype($allfiles,$src,'src');
                   3960:                 } elsif ($src =~ m{^/}) {
                   3961:                     if ($env{'request.course.id'}) {
                   3962:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3963:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3964:                         my $url = &hreflocation('',$fullpath);
                   3965:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   3966:                             my $relpath = $1;
                   3967:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   3968:                                 &add_filetype($allfiles,$1,'src');
                   3969:                             }
                   3970:                         }
                   3971:                     }
                   3972:                 }
                   3973:             }
1.1164    raeburn  3974:             if ($t->[4] =~ m{/>$}) {
1.1172.2.35  raeburn  3975:                 pop(@state);
1.1164    raeburn  3976:             }
1.640     albertel 3977: 	} elsif ($t->[0] eq 'E') {
                   3978: 	    my ($tagname) = ($t->[1]);
                   3979: 	    if ($javafiles{'codebase'} ne '') {
                   3980: 		$javafiles{'codebase'} .= '/';
                   3981: 	    }  
                   3982: 	    if (lc($tagname) eq 'applet' ||
                   3983: 		lc($tagname) eq 'object' ||
                   3984: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3985: 		) {
                   3986: 		foreach my $item (keys(%javafiles)) {
                   3987: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3988: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3989: 			&add_filetype($allfiles,$file,$item);
                   3990: 		    }
                   3991: 		}
                   3992: 	    } 
                   3993: 	    pop @state;
                   3994: 	}
                   3995:     }
1.1164    raeburn  3996:     foreach my $id (sort(keys(%flashvars))) {
                   3997:         if ($shockwave{$id} ne '') {
                   3998:             my @pairs = split(/\&/,$flashvars{$id});
                   3999:             foreach my $pair (@pairs) {
                   4000:                 my ($key,$value) = split(/\=/,$pair);
                   4001:                 if ($key eq 'thumb') {
                   4002:                     &add_filetype($allfiles,$value,$key);
                   4003:                 } elsif ($key eq 'content') {
                   4004:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4005:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4006:                     if ($ext ne '') {
                   4007:                         &add_filetype($allfiles,$path.$value,$ext);
                   4008:                     }
                   4009:                 }
                   4010:             }
                   4011:         }
                   4012:     }
1.637     raeburn  4013:     return 'ok';
                   4014: }
                   4015: 
1.639     albertel 4016: sub add_filetype {
                   4017:     my ($allfiles,$file,$type)=@_;
                   4018:     if (exists($allfiles->{$file})) {
                   4019: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4020: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4021: 	}
                   4022:     } else {
                   4023: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4024:     }
                   4025: }
                   4026: 
1.1164    raeburn  4027: sub embedded_dependency {
                   4028:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4029:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4030:         if (($identifier ne '') &&
                   4031:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4032:             ($pathfrom ne '')) {
                   4033:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4034:             foreach my $dep (@{$related->{$identifier}}) {
                   4035:                 &add_filetype($allfiles,$path.$dep,'object');
                   4036:             }
                   4037:         }
                   4038:     }
                   4039:     return;
                   4040: }
                   4041: 
1.493     albertel 4042: sub removeuploadedurl {
1.984     neumanie 4043:     my ($url)=@_;	
                   4044:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4045:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4046: }
                   4047: 
                   4048: sub removeuserfile {
                   4049:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4050:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4051:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4052:     if ($result eq 'ok') {	
1.798     raeburn  4053:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4054:             my $metafile = $fname.'.meta';
                   4055:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4056: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4057:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4058:             my $sqlresult = 
1.823     albertel 4059:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4060:                                         'portfolio_metadata',$group,
                   4061:                                         'delete');
1.798     raeburn  4062:         }
                   4063:     }
                   4064:     return $result;
1.257     www      4065: }
1.15      www      4066: 
1.530     albertel 4067: sub mkdiruserfile {
                   4068:     my ($docuname,$docudom,$dir)=@_;
                   4069:     my $home=&homeserver($docuname,$docudom);
                   4070:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4071: }
                   4072: 
1.531     albertel 4073: sub renameuserfile {
                   4074:     my ($docuname,$docudom,$old,$new)=@_;
                   4075:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4076:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4077:                         &escape("$old").':'.&escape("$new"),$home);
                   4078:     if ($result eq 'ok') {
                   4079:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4080:             my $oldmeta = $old.'.meta';
                   4081:             my $newmeta = $new.'.meta';
                   4082:             my $metaresult = 
                   4083:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4084: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4085:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4086:             my $sqlresult = 
1.823     albertel 4087:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4088:                                         'portfolio_metadata',$group,
                   4089:                                         'delete');
1.798     raeburn  4090:         }
                   4091:     }
                   4092:     return $result;
1.531     albertel 4093: }
                   4094: 
1.14      www      4095: # ------------------------------------------------------------------------- Log
                   4096: 
                   4097: sub log {
                   4098:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4099:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4100: }
                   4101: 
                   4102: # ------------------------------------------------------------------ Course Log
1.352     www      4103: #
                   4104: # This routine flushes several buffers of non-mission-critical nature
                   4105: #
1.157     www      4106: 
                   4107: sub flushcourselogs {
1.352     www      4108:     &logthis('Flushing log buffers');
                   4109: #
                   4110: # course logs
                   4111: # This is a log of all transactions in a course, which can be used
                   4112: # for data mining purposes
                   4113: #
                   4114: # It also collects the courseid database, which lists last transaction
                   4115: # times and course titles for all courseids
                   4116: #
                   4117:     my %courseidbuffer=();
1.921     raeburn  4118:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4119:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4120: 		          &escape($courselogs{$crsid}),
                   4121: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4122: 	    delete $courselogs{$crsid};
                   4123:         } else {
                   4124:             &logthis('Failed to flush log buffer for '.$crsid);
                   4125:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4126:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4127:                         " exceeded maximum size, deleting.</font>");
                   4128:                delete $courselogs{$crsid};
                   4129:             }
1.352     www      4130:         }
1.920     raeburn  4131:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4132:             'description' => $coursedescrbuf{$crsid},
                   4133:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4134:             'type'        => $coursetypebuf{$crsid},
                   4135:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4136:         };
1.191     harris41 4137:     }
1.352     www      4138: #
                   4139: # Write course id database (reverse lookup) to homeserver of courses 
                   4140: # Is used in pickcourse
                   4141: #
1.840     albertel 4142:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4143:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4144:                                     $courseidbuffer{$crs_home},
                   4145:                                     $crs_home,'timeonly');
1.352     www      4146:     }
                   4147: #
                   4148: # File accesses
                   4149: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4150: #
1.449     matthew  4151:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4152:         if ($entry =~ /___count$/) {
                   4153:             my ($dom,$name);
1.807     albertel 4154:             ($dom,$name,undef)=
1.811     albertel 4155: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4156:             if (! defined($dom) || $dom eq '' || 
                   4157:                 ! defined($name) || $name eq '') {
1.620     albertel 4158:                 my $cid = $env{'request.course.id'};
                   4159:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4160:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4161:             }
1.450     matthew  4162:             my $value = $accesshash{$entry};
                   4163:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4164:             my %temphash=($url => $value);
1.449     matthew  4165:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4166:             if ($result eq 'ok') {
                   4167:                 delete $accesshash{$entry};
                   4168:             }
                   4169:         } else {
1.811     albertel 4170:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4171:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4172:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4173:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4174:                 delete $accesshash{$entry};
                   4175:             }
1.185     www      4176:         }
1.191     harris41 4177:     }
1.352     www      4178: #
                   4179: # Roles
                   4180: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4181: #
1.800     albertel 4182:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4183:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4184: 	    split(/\:/,$entry);
                   4185:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4186:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4187:                 $rudom,$runame) eq 'ok') {
                   4188: 	    delete $userrolehash{$entry};
                   4189:         }
                   4190:     }
1.662     raeburn  4191: #
1.1172.2.90  raeburn  4192: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4193: #
                   4194:     my %domrolebuffer = ();
1.1000    raeburn  4195:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4196:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4197:         if ($domrolebuffer{$rudom}) {
                   4198:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4199:                       '='.&escape($domainrolehash{$entry});
                   4200:         } else {
                   4201:             $domrolebuffer{$rudom}.=&escape($entry).
                   4202:                       '='.&escape($domainrolehash{$entry});
                   4203:         }
                   4204:         delete $domainrolehash{$entry};
                   4205:     }
                   4206:     foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82  raeburn  4207:         my %servers;
                   4208:         if (defined(&domain($dom,'primary'))) {
                   4209:             my $primary=&domain($dom,'primary');
                   4210:             my $hostname=&hostname($primary);
                   4211:             $servers{$primary} = $hostname;
                   4212:         } else {
                   4213:             %servers = &get_servers($dom,'library');
                   4214:         }
1.841     albertel 4215: 	foreach my $tryserver (keys(%servers)) {
1.1172.2.82  raeburn  4216: 	    if (&reply('domroleput:'.$dom.':'.
                   4217: 	               $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4218: 	        last;
                   4219: 	    } else {
1.841     albertel 4220: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4221: 	    }
1.662     raeburn  4222:         }
                   4223:     }
1.186     www      4224:     $dumpcount++;
1.157     www      4225: }
                   4226: 
                   4227: sub courselog {
                   4228:     my $what=shift;
1.158     www      4229:     $what=time.':'.$what;
1.620     albertel 4230:     unless ($env{'request.course.id'}) { return ''; }
                   4231:     $coursedombuf{$env{'request.course.id'}}=
                   4232:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4233:     $coursenumbuf{$env{'request.course.id'}}=
                   4234:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4235:     $coursehombuf{$env{'request.course.id'}}=
                   4236:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4237:     $coursedescrbuf{$env{'request.course.id'}}=
                   4238:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4239:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4240:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4241:     $courseownerbuf{$env{'request.course.id'}}=
                   4242:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4243:     $coursetypebuf{$env{'request.course.id'}}=
                   4244:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4245:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4246: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4247:     } else {
1.620     albertel 4248: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4249:     }
1.620     albertel 4250:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4251: 	&flushcourselogs();
                   4252:     }
1.158     www      4253: }
                   4254: 
                   4255: sub courseacclog {
                   4256:     my $fnsymb=shift;
1.620     albertel 4257:     unless ($env{'request.course.id'}) { return ''; }
                   4258:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4259:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4260:         $what.=':POST';
1.583     matthew  4261:         # FIXME: Probably ought to escape things....
1.800     albertel 4262: 	foreach my $key (keys(%env)) {
                   4263:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4264:                 my $formitem = $1;
                   4265:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4266:                     $what.=':'.$formitem.'='.$env{$key};
                   4267:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   4268:                     $what.=':'.$formitem.'='.$env{$key};
                   4269:                 }
1.158     www      4270:             }
1.191     harris41 4271:         }
1.583     matthew  4272:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4273:         # FIXME: We should not be depending on a form parameter that someone
                   4274:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4275:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4276:             $what.= ':POST';
                   4277:             # FIXME: Probably ought to escape things....
                   4278:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4279:                                  'crsdiscuss') {
1.620     albertel 4280:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4281:             }
                   4282:         }
1.158     www      4283:     }
                   4284:     &courselog($what);
1.149     www      4285: }
                   4286: 
1.185     www      4287: sub countacc {
                   4288:     my $url=&declutter(shift);
1.458     matthew  4289:     return if (! defined($url) || $url eq '');
1.620     albertel 4290:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4291: #
                   4292: # Mark that this url was used in this course
                   4293: #
1.620     albertel 4294:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4295: #
                   4296: # Increase the access count for this resource in this child process
                   4297: #
1.281     www      4298:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4299:     $accesshash{$key}++;
1.185     www      4300: }
1.349     www      4301: 
1.361     www      4302: sub linklog {
                   4303:     my ($from,$to)=@_;
                   4304:     $from=&declutter($from);
                   4305:     $to=&declutter($to);
                   4306:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4307:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4308: }
1.1160    www      4309: 
                   4310: sub statslog {
                   4311:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4312:     if ($users<2) { return; }
                   4313:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4314:             'course'       => $env{'request.course.id'},
                   4315:             'sections'     => '"all"',
                   4316:             'num_students' => $users,
                   4317:             'part'         => $part,
                   4318:             'symb'         => $symb,
                   4319:             'mean_tries'   => $av_attempts,
                   4320:             'deg_of_diff'  => $degdiff});
                   4321:     foreach my $key (keys(%dynstore)) {
                   4322:         $accesshash{$key}=$dynstore{$key};
                   4323:     }
                   4324: }
1.361     www      4325:   
1.349     www      4326: sub userrolelog {
                   4327:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4328:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4329:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4330:        $userrolehash
                   4331:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4332:                     =$tend.':'.$tstart;
1.662     raeburn  4333:     }
1.1169    droeschl 4334:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4335:        $userrolehash
                   4336:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4337:                     =$tend.':'.$tstart;
                   4338:     }
1.1172.2.90  raeburn  4339:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4340:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4341:        $domainrolehash
                   4342:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4343:                     = $tend.':'.$tstart;
                   4344:     }
1.351     www      4345: }
                   4346: 
1.957     raeburn  4347: sub courserolelog {
                   4348:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  4349:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4350:         my $cdom = $1;
                   4351:         my $cnum = $2;
                   4352:         my $sec = $3;
                   4353:         my $namespace = 'rolelog';
                   4354:         my %storehash = (
                   4355:                            role    => $trole,
                   4356:                            start   => $tstart,
                   4357:                            end     => $tend,
                   4358:                            selfenroll => $selfenroll,
                   4359:                            context    => $context,
                   4360:                         );
                   4361:         if ($trole eq 'gr') {
                   4362:             $namespace = 'groupslog';
                   4363:             $storehash{'group'} = $sec;
                   4364:         } else {
                   4365:             $storehash{'section'} = $sec;
                   4366:         }
                   4367:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4368:                    $domain,$cnum,$cdom);
                   4369:         if (($trole ne 'st') || ($sec ne '')) {
                   4370:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4371:         }
                   4372:     }
                   4373:     return;
                   4374: }
                   4375: 
1.1172.2.9  raeburn  4376: sub domainrolelog {
                   4377:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4378:     if ($area =~ m{^/($match_domain)/$}) {
                   4379:         my $cdom = $1;
                   4380:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4381:         my $namespace = 'rolelog';
                   4382:         my %storehash = (
                   4383:                            role    => $trole,
                   4384:                            start   => $tstart,
                   4385:                            end     => $tend,
                   4386:                            context => $context,
                   4387:                         );
                   4388:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4389:                    $domain,$domconfiguser,$cdom);
                   4390:     }
                   4391:     return;
                   4392: 
                   4393: }
                   4394: 
                   4395: sub coauthorrolelog {
                   4396:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4397:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4398:         my $audom = $1;
                   4399:         my $auname = $2;
                   4400:         my $namespace = 'rolelog';
                   4401:         my %storehash = (
                   4402:                            role    => $trole,
                   4403:                            start   => $tstart,
                   4404:                            end     => $tend,
                   4405:                            context => $context,
                   4406:                         );
                   4407:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4408:                    $domain,$auname,$audom);
                   4409:     }
                   4410:     return;
                   4411: }
                   4412: 
1.351     www      4413: sub get_course_adv_roles {
1.948     raeburn  4414:     my ($cid,$codes) = @_;
1.620     albertel 4415:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4416:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4417:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4418:     my %nothide=();
1.800     albertel 4419:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4420:         if ($user !~ /:/) {
                   4421: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4422:         } else {
                   4423:             $nothide{$user}=1;
                   4424:         }
1.470     www      4425:     }
1.1172.2.23  raeburn  4426:     my @possdoms = ($coursehash{'domain'});
                   4427:     if ($coursehash{'checkforpriv'}) {
                   4428:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4429:     }
1.351     www      4430:     my %returnhash=();
                   4431:     my %dumphash=
                   4432:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4433:     my $now=time;
1.997     raeburn  4434:     my %privileged;
1.1000    raeburn  4435:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4436: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4437:         if (($tstart) && ($tstart<0)) { next; }
                   4438:         if (($tend) && ($tend<$now)) { next; }
                   4439:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4440:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4441: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  4442:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4443:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4444: 	if ($role eq 'cr') { next; }
1.948     raeburn  4445:         if ($codes) {
                   4446:             if ($section) { $role .= ':'.$section; }
                   4447:             if ($returnhash{$role}) {
                   4448:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4449:             } else {
                   4450:                 $returnhash{$role}=$username.':'.$domain;
                   4451:             }
1.351     www      4452:         } else {
1.988     raeburn  4453:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4454:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4455:             if ($returnhash{$key}) {
                   4456: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4457:             } else {
                   4458:                 $returnhash{$key}=$username.':'.$domain;
                   4459:             }
1.351     www      4460:         }
1.948     raeburn  4461:     }
1.400     www      4462:     return %returnhash;
                   4463: }
                   4464: 
                   4465: sub get_my_roles {
1.937     raeburn  4466:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4467:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4468:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4469:     my (%dumphash,%nothide);
1.1086    raeburn  4470:     if ($context eq 'userroles') {
1.1166    raeburn  4471:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4472:     } else {
1.1172.2.23  raeburn  4473:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4474:         if ($hidepriv) {
                   4475:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4476:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4477:                 if ($user !~ /:/) {
                   4478:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4479:                 } else {
                   4480:                     $nothide{$user} = 1;
                   4481:                 }
                   4482:             }
                   4483:         }
1.858     raeburn  4484:     }
1.400     www      4485:     my %returnhash=();
                   4486:     my $now=time;
1.999     raeburn  4487:     my %privileged;
1.800     albertel 4488:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4489:         my ($role,$tend,$tstart);
                   4490:         if ($context eq 'userroles') {
1.1149    raeburn  4491:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4492: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4493:         } else {
                   4494:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4495:         }
1.400     www      4496:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4497:         my $status = 'active';
1.939     raeburn  4498:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4499:             $status = 'previous';
                   4500:         } 
                   4501:         if (($tstart) && ($now<$tstart)) {
                   4502:             $status = 'future';
                   4503:         }
                   4504:         if (ref($types) eq 'ARRAY') {
                   4505:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4506:                 next;
                   4507:             } 
                   4508:         } else {
                   4509:             if ($status ne 'active') {
                   4510:                 next;
                   4511:             }
                   4512:         }
1.867     raeburn  4513:         my ($rolecode,$username,$domain,$section,$area);
                   4514:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  4515:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4516:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4517:         } else {
                   4518:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4519:         }
1.832     raeburn  4520:         if (ref($roledoms) eq 'ARRAY') {
                   4521:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4522:                 next;
                   4523:             }
                   4524:         }
                   4525:         if (ref($roles) eq 'ARRAY') {
                   4526:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4527:                 if ($role =~ /^cr\//) {
                   4528:                     if (!grep(/^cr$/,@{$roles})) {
                   4529:                         next;
                   4530:                     }
1.1104    raeburn  4531:                 } elsif ($role =~ /^gr\//) {
                   4532:                     if (!grep(/^gr$/,@{$roles})) {
                   4533:                         next;
                   4534:                     }
1.922     raeburn  4535:                 } else {
                   4536:                     next;
                   4537:                 }
1.832     raeburn  4538:             }
1.867     raeburn  4539:         }
1.937     raeburn  4540:         if ($hidepriv) {
1.1172.2.23  raeburn  4541:             my @privroles = ('dc','su');
1.999     raeburn  4542:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  4543:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4544:             } else {
1.1172.2.23  raeburn  4545:                 my $possdoms = [$domain];
                   4546:                 if (ref($roledoms) eq 'ARRAY') {
                   4547:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  4548:                 }
1.1172.2.23  raeburn  4549:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4550:                     if (!$nothide{$username.':'.$domain}) {
                   4551:                         next;
                   4552:                     }
                   4553:                 }
1.937     raeburn  4554:             }
                   4555:         }
1.933     raeburn  4556:         if ($withsec) {
                   4557:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4558:                 $tstart.':'.$tend;
                   4559:         } else {
                   4560:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4561:         }
1.832     raeburn  4562:     }
1.373     www      4563:     return %returnhash;
1.399     www      4564: }
                   4565: 
1.1172.2.89  raeburn  4566: sub get_all_adhocroles {
                   4567:     my ($dom) = @_;
                   4568:     my @roles_by_num = ();
                   4569:     my %domdefaults = &get_domain_defaults($dom);
                   4570:     my (%description,%access_in_dom,%access_info);
                   4571:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   4572:         my $count = 0;
                   4573:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   4574:         my %ordered;
                   4575:         foreach my $role (sort(keys(%domcurrent))) {
                   4576:             my ($order,$desc,$access_in_dom);
                   4577:             if (ref($domcurrent{$role}) eq 'HASH') {
                   4578:                 $order = $domcurrent{$role}{'order'};
                   4579:                 $desc = $domcurrent{$role}{'desc'};
                   4580:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   4581:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   4582:             }
                   4583:             if ($order eq '') {
                   4584:                 $order = $count;
                   4585:             }
                   4586:             $ordered{$order} = $role;
                   4587:             if ($desc ne '') {
                   4588:                 $description{$role} = $desc;
                   4589:             } else {
                   4590:                 $description{$role}= $role;
                   4591:             }
                   4592:             $count++;
                   4593:         }
                   4594:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   4595:             push(@roles_by_num,$ordered{$item});
                   4596:         }
                   4597:     }
                   4598:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   4599: }
                   4600: 
                   4601: sub get_my_adhocroles {
                   4602:     my ($cid,$checkreg) = @_;
                   4603:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   4604:     if ($env{'request.course.id'} eq $cid) {
                   4605:         $cdom = $env{'course.'.$cid.'.domain'};
                   4606:         $cnum = $env{'course.'.$cid.'.num'};
                   4607:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   4608:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   4609:         $cdom = $1;
                   4610:         $cnum = $2;
                   4611:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   4612:                                      $cdom,$cnum);
                   4613:     }
                   4614:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   4615:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   4616:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   4617:         if ($rosterhash{$user} ne '') {
                   4618:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   4619:             return ([],{}) if ($type eq 'auto');
                   4620:         }
                   4621:     }
                   4622:     if (($cdom ne '') && ($cnum ne ''))  {
1.1172.2.90  raeburn  4623:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89  raeburn  4624:             my $then=$env{'user.login.time'};
                   4625:             my $update=$env{'user.update.time'};
1.1172.2.90  raeburn  4626:             if (!$update) {
                   4627:                 $update = $then;
                   4628:             }
                   4629:             my @liveroles;
                   4630:             foreach my $role ('dh','da') {
                   4631:                 if ($env{"user.role.$role./$cdom/"}) {
                   4632:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
                   4633:                     my $limit = $update;
                   4634:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   4635:                         $limit = $then;
                   4636:                     }
                   4637:                     my $activerole = 1;
                   4638:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   4639:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   4640:                     if ($activerole) {
                   4641:                         push(@liveroles,$role);
                   4642:                     }
                   4643:                 }
                   4644:             }
                   4645:             if (@liveroles) {
1.1172.2.89  raeburn  4646:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
                   4647:                     my ($accessref,$accessinfo,%access_in_dom);
                   4648:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   4649:                     if (ref($roles_by_num) eq 'ARRAY') {
                   4650:                         if (@{$roles_by_num}) {
                   4651:                             my %settings;
                   4652:                             if ($env{'request.course.id'} eq $cid) {
                   4653:                                 foreach my $envkey (keys(%env)) {
                   4654:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   4655:                                         $settings{$1} = $env{$envkey};
                   4656:                                     }
                   4657:                                 }
                   4658:                             } else {
                   4659:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   4660:                             }
                   4661:                             my %setincrs;
                   4662:                             if ($settings{'internal.adhocaccess'}) {
                   4663:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   4664:                             }
                   4665:                             my @statuses;
                   4666:                             if ($env{'environment.inststatus'}) {
                   4667:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   4668:                             }
                   4669:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   4670:                             if (ref($accessref) eq 'HASH') {
                   4671:                                 %access_in_dom = %{$accessref};
                   4672:                             }
                   4673:                             foreach my $role (@{$roles_by_num}) {
                   4674:                                 my ($curraccess,@okstatus,@personnel);
                   4675:                                 if ($setincrs{$role}) {
                   4676:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   4677:                                     if ($curraccess eq 'status') {
                   4678:                                         @okstatus = split(/\&/,$rest);
                   4679:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4680:                                         @personnel = split(/\&/,$rest);
                   4681:                                     }
                   4682:                                 } else {
                   4683:                                     $curraccess = $access_in_dom{$role};
                   4684:                                     if (ref($accessinfo) eq 'HASH') {
                   4685:                                         if ($curraccess eq 'status') {
                   4686:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   4687:                                                 @okstatus = @{$accessinfo->{$role}};
                   4688:                                             }
                   4689:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4690:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   4691:                                                 @personnel = @{$accessinfo->{$role}};
                   4692:                                             }
                   4693:                                         }
                   4694:                                     }
                   4695:                                 }
                   4696:                                 if ($curraccess eq 'none') {
                   4697:                                     next;
                   4698:                                 } elsif ($curraccess eq 'all') {
                   4699:                                     push(@possroles,$role);
1.1172.2.90  raeburn  4700:                                 } elsif ($curraccess eq 'dh') {
                   4701:                                     if (grep(/^dh$/,@liveroles)) {
                   4702:                                         push(@possroles,$role);
                   4703:                                     } else {
                   4704:                                         next;
                   4705:                                     }
                   4706:                                 } elsif ($curraccess eq 'da') {
                   4707:                                     if (grep(/^da$/,@liveroles)) {
                   4708:                                         push(@possroles,$role);
                   4709:                                     } else {
                   4710:                                         next;
                   4711:                                     }
1.1172.2.89  raeburn  4712:                                 } elsif ($curraccess eq 'status') {
                   4713:                                     if (@okstatus) {
                   4714:                                         if (!@statuses) {
                   4715:                                             if (grep(/^default$/,@okstatus)) {
                   4716:                                                 push(@possroles,$role);
                   4717:                                             }
                   4718:                                         } else {
                   4719:                                             foreach my $status (@okstatus) {
                   4720:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   4721:                                                     push(@possroles,$role);
                   4722:                                                     last;
                   4723:                                                 }
                   4724:                                             }
                   4725:                                         }
                   4726:                                     }
                   4727:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4728:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   4729:                                         if ($curraccess eq 'exc') {
                   4730:                                             push(@possroles,$role);
                   4731:                                         }
                   4732:                                     } elsif ($curraccess eq 'inc') {
                   4733:                                         push(@possroles,$role);
                   4734:                                     }
                   4735:                                 }
                   4736:                             }
                   4737:                         }
                   4738:                     }
                   4739:                 }
                   4740:             }
                   4741:         }
                   4742:     }
                   4743:     unless (ref($description) eq 'HASH') {
                   4744:         if (ref($roles_by_num) eq 'ARRAY') {
                   4745:             my %desc;
                   4746:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   4747:             $description = \%desc;
                   4748:         } else {
                   4749:             $description = {};
                   4750:         }
                   4751:     }
                   4752:     return (\@possroles,$description);
                   4753: }
                   4754: 
1.399     www      4755: # ----------------------------------------------------- Frontpage Announcements
                   4756: #
                   4757: #
                   4758: 
                   4759: sub postannounce {
                   4760:     my ($server,$text)=@_;
1.844     albertel 4761:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4762:     unless ($text=~/\w/) { $text=''; }
                   4763:     return &reply('setannounce:'.&escape($text),$server);
                   4764: }
                   4765: 
                   4766: sub getannounce {
1.448     albertel 4767: 
1.1172.2.96  raeburn  4768:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4769: 	my $announcement='';
1.800     albertel 4770: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4771: 	close($fh);
1.399     www      4772: 	if ($announcement=~/\w/) { 
                   4773: 	    return 
                   4774:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4775:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4776: 	} else {
                   4777: 	    return '';
                   4778: 	}
                   4779:     } else {
                   4780: 	return '';
                   4781:     }
1.351     www      4782: }
1.353     www      4783: 
                   4784: # ---------------------------------------------------------- Course ID routines
                   4785: # Deal with domain's nohist_courseid.db files
                   4786: #
                   4787: 
                   4788: sub courseidput {
1.921     raeburn  4789:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4790:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4791:     my $outcome;
                   4792:     if ($caller eq 'timeonly') {
                   4793:         my $cids = '';
                   4794:         foreach my $item (keys(%$storehash)) {
                   4795:             $cids.=&escape($item).'&';
                   4796:         }
                   4797:         $cids=~s/\&$//;
                   4798:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4799:                           $coursehome);       
                   4800:     } else {
                   4801:         my $items = '';
                   4802:         foreach my $item (keys(%$storehash)) {
                   4803:             $items.= &escape($item).'='.
                   4804:                      &freeze_escape($$storehash{$item}).'&';
                   4805:         }
                   4806:         $items=~s/\&$//;
                   4807:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4808:                           $coursehome);
1.918     raeburn  4809:     }
                   4810:     if ($outcome eq 'unknown_cmd') {
                   4811:         my $what;
                   4812:         foreach my $cid (keys(%$storehash)) {
                   4813:             $what .= &escape($cid).'=';
1.921     raeburn  4814:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4815:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4816:             }
                   4817:             $what =~ s/\:$/&/;
                   4818:         }
                   4819:         $what =~ s/\&$//;  
                   4820:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4821:     } else {
                   4822:         return $outcome;
                   4823:     }
1.353     www      4824: }
                   4825: 
                   4826: sub courseiddump {
1.921     raeburn  4827:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4828:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4829:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38  raeburn  4830:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68  raeburn  4831:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  4832:     my $as_hash = 1;
                   4833:     my %returnhash;
                   4834:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4835:     my %libserv = &all_library();
                   4836:     foreach my $tryserver (keys(%libserv)) {
                   4837:         if ( (  $hostidflag == 1 
                   4838: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4839: 	     || (!defined($hostidflag)) ) {
                   4840: 
1.918     raeburn  4841: 	    if (($domfilter eq '') ||
                   4842: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  4843:                 my $rep;
                   4844:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   4845:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   4846:                         join(":", (&host_domain($tryserver), $sincefilter,
                   4847:                                 &escape($descfilter), &escape($instcodefilter),
                   4848:                                 &escape($ownerfilter), &escape($coursefilter),
                   4849:                                 &escape($typefilter), &escape($regexp_ok),
                   4850:                                 $as_hash, &escape($selfenrollonly),
                   4851:                                 &escape($catfilter), $showhidden, $caller,
                   4852:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   4853:                                 &escape($createdbefore), &escape($createdafter),
1.1172.2.68  raeburn  4854:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   4855:                                 $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22  raeburn  4856:                 } else {
                   4857:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4858:                              $sincefilter.':'.&escape($descfilter).':'.
                   4859:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   4860:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   4861:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   4862:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   4863:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   4864:                              &escape($cc_clone).':'.$cloneonly.':'.
                   4865:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68  raeburn  4866:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   4867:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22  raeburn  4868:                 }
                   4869: 
1.918     raeburn  4870:                 my @pairs=split(/\&/,$rep);
                   4871:                 foreach my $item (@pairs) {
                   4872:                     my ($key,$value)=split(/\=/,$item,2);
                   4873:                     $key = &unescape($key);
                   4874:                     next if ($key =~ /^error: 2 /);
                   4875:                     my $result = &thaw_unescape($value);
                   4876:                     if (ref($result) eq 'HASH') {
                   4877:                         $returnhash{$key}=$result;
                   4878:                     } else {
1.921     raeburn  4879:                         my @responses = split(/:/,$value);
                   4880:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4881:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4882:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4883:                         }
1.1008    raeburn  4884:                     }
1.353     www      4885:                 }
                   4886:             }
                   4887:         }
                   4888:     }
                   4889:     return %returnhash;
                   4890: }
                   4891: 
1.1055    raeburn  4892: sub courselastaccess {
                   4893:     my ($cdom,$cnum,$hostidref) = @_;
                   4894:     my %returnhash;
                   4895:     if ($cdom && $cnum) {
                   4896:         my $chome = &homeserver($cnum,$cdom);
                   4897:         if ($chome ne 'no_host') {
                   4898:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4899:             &extract_lastaccess(\%returnhash,$rep);
                   4900:         }
                   4901:     } else {
                   4902:         if (!$cdom) { $cdom=''; }
                   4903:         my %libserv = &all_library();
                   4904:         foreach my $tryserver (keys(%libserv)) {
                   4905:             if (ref($hostidref) eq 'ARRAY') {
                   4906:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4907:             } 
                   4908:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4909:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4910:                 &extract_lastaccess(\%returnhash,$rep);
                   4911:             }
                   4912:         }
                   4913:     }
                   4914:     return %returnhash;
                   4915: }
                   4916: 
                   4917: sub extract_lastaccess {
                   4918:     my ($returnhash,$rep) = @_;
                   4919:     if (ref($returnhash) eq 'HASH') {
                   4920:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4921:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4922:                  $rep eq '') {
                   4923:             my @pairs=split(/\&/,$rep);
                   4924:             foreach my $item (@pairs) {
                   4925:                 my ($key,$value)=split(/\=/,$item,2);
                   4926:                 $key = &unescape($key);
                   4927:                 next if ($key =~ /^error: 2 /);
                   4928:                 $returnhash->{$key} = &thaw_unescape($value);
                   4929:             }
                   4930:         }
                   4931:     }
                   4932:     return;
                   4933: }
                   4934: 
1.658     raeburn  4935: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4936: 
                   4937: sub dcmailput {
1.685     raeburn  4938:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4939:     my $status = &Apache::lonnet::critical(
1.740     www      4940:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4941:        &escape($message),$server);
1.662     raeburn  4942:     return $status;
                   4943: }
                   4944: 
1.658     raeburn  4945: sub dcmaildump {
                   4946:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4947:     my %returnhash=();
1.846     albertel 4948: 
                   4949:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4950:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4951:                                                          &escape($enddate).':';
                   4952: 	my @esc_senders=map { &escape($_)} @$senders;
                   4953: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4954: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4955:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4956:             if (($key) && ($value)) {
                   4957:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4958:             }
                   4959:         }
                   4960:     }
                   4961:     return %returnhash;
                   4962: }
1.662     raeburn  4963: # ---------------------------------------------------------- Domain roles
                   4964: 
                   4965: sub get_domain_roles {
                   4966:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4967:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4968:         $startdate = '.';
                   4969:     }
1.1018    raeburn  4970:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4971:         $enddate = '.';
                   4972:     }
1.922     raeburn  4973:     my $rolelist;
                   4974:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  4975:         $rolelist = join('&',@{$roles});
1.922     raeburn  4976:     }
1.662     raeburn  4977:     my %personnel = ();
1.841     albertel 4978: 
                   4979:     my %servers = &get_servers($dom,'library');
                   4980:     foreach my $tryserver (keys(%servers)) {
                   4981: 	%{$personnel{$tryserver}}=();
                   4982: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4983: 					    &escape($startdate).':'.
                   4984: 					    &escape($enddate).':'.
                   4985: 					    &escape($rolelist), $tryserver))) {
                   4986: 	    my ($key,$value) = split(/\=/,$line,2);
                   4987: 	    if (($key) && ($value)) {
                   4988: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4989: 	    }
                   4990: 	}
1.662     raeburn  4991:     }
                   4992:     return %personnel;
                   4993: }
1.658     raeburn  4994: 
1.1172.2.89  raeburn  4995: sub get_active_domroles {
                   4996:     my ($dom,$roles) = @_;
                   4997:     return () unless (ref($roles) eq 'ARRAY');
                   4998:     my $now = time;
                   4999:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5000:     my %domroles;
                   5001:     foreach my $server (keys(%dompersonnel)) {
                   5002:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5003:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5004:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5005:         }
                   5006:     }
                   5007:     return %domroles;
                   5008: }
                   5009: 
1.1057    www      5010: # ----------------------------------------------------------- Interval timing 
1.149     www      5011: 
1.1153    www      5012: {
                   5013: # Caches needed for speedup of navmaps
                   5014: # We don't want to cache this for very long at all (5 seconds at most)
                   5015: # 
                   5016: # The user for whom we cache
                   5017: my $cachedkey='';
                   5018: # The cached times for this user
                   5019: my %cachedtimes=();
                   5020: # When this was last done
1.1172.2.66  raeburn  5021: my $cachedtime='';
1.1153    www      5022: 
                   5023: sub load_all_first_access {
1.1154    raeburn  5024:     my ($uname,$udom)=@_;
1.1156    www      5025:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2  raeburn  5026:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  5027:         return;
                   5028:     }
                   5029:     $cachedtime=time;
                   5030:     $cachedkey=$uname.':'.$udom;
                   5031:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5032: }
                   5033: 
1.504     albertel 5034: sub get_first_access {
1.1162    raeburn  5035:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 5036:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5037:     if ($argsymb) { $symb=$argsymb; }
                   5038:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5039:     if ($argmap) { $map = $argmap; }
1.926     albertel 5040:     if ($type eq 'course') {
                   5041: 	$res='course';
                   5042:     } elsif ($type eq 'map') {
1.588     albertel 5043: 	$res=&symbread($map);
                   5044:     } else {
                   5045: 	$res=$symb;
                   5046:     }
1.1153    www      5047:     &load_all_first_access($uname,$udom);
                   5048:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5049: }
                   5050: 
                   5051: sub set_first_access {
1.1162    raeburn  5052:     my ($type,$interval)=@_;
1.790     albertel 5053:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5054:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5055:     if ($type eq 'course') {
                   5056: 	$res='course';
                   5057:     } elsif ($type eq 'map') {
1.588     albertel 5058: 	$res=&symbread($map);
                   5059:     } else {
                   5060: 	$res=$symb;
                   5061:     }
1.1153    www      5062:     $cachedkey='';
1.1162    raeburn  5063:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1172.2.102  raeburn  5064:     if ($firstaccess) {
                   5065:         &logthis("First access time already set ($firstaccess) when attempting ".
                   5066:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
                   5067:                  "in $courseid");
                   5068:         return 'already_set';
                   5069:     } else {
1.1162    raeburn  5070:         my $start = time;
                   5071: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5072:                           $udom,$uname);
                   5073:         if ($putres eq 'ok') {
                   5074:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5075:                  $udom,$uname); 
                   5076:             &appenv(
                   5077:                      {
                   5078:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5079:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5080:                      }
                   5081:                   );
1.1172.2.97  raeburn  5082:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5083:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5084:             }
1.1172.2.102  raeburn  5085:         } elsif ($putres ne 'refused') {
                   5086:             &logthis("Result: $putres when attempting to set first access time ".
                   5087:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  5088:         }
                   5089:         return $putres;
1.505     albertel 5090:     }
                   5091:     return 'already_set';
1.504     albertel 5092: }
1.1153    www      5093: }
1.1172.2.32  raeburn  5094: 
                   5095: sub checkout {
                   5096:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   5097:     my $now=time;
                   5098:     my $lonhost=$perlvar{'lonHostID'};
                   5099:     my $infostr=&escape(
                   5100:                  'CHECKOUTTOKEN&'.
                   5101:                  $tuname.'&'.
                   5102:                  $tudom.'&'.
                   5103:                  $tcrsid.'&'.
                   5104:                  $symb.'&'.
                   5105:                  $now.'&'.$ENV{'REMOTE_ADDR'});
                   5106:     my $token=&reply('tmpput:'.$infostr,$lonhost);
                   5107:     if ($token=~/^error\:/) {
                   5108:         &logthis("<font color=\"blue\">WARNING: ".
                   5109:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5110:                  "</font>");
                   5111:         return '';
                   5112:     }
                   5113: 
                   5114:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   5115:     $token=~tr/a-z/A-Z/;
                   5116: 
                   5117:     my %infohash=('resource.0.outtoken' => $token,
                   5118:                   'resource.0.checkouttime' => $now,
                   5119:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
                   5120: 
                   5121:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5122:        return '';
                   5123:     } else {
                   5124:         &logthis("<font color=\"blue\">WARNING: ".
                   5125:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5126:                  "</font>");
                   5127:     }
                   5128: 
                   5129:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5130:                          &escape('Checkout '.$infostr.' - '.
                   5131:                                                  $token)) ne 'ok') {
                   5132:         return '';
                   5133:     } else {
                   5134:         &logthis("<font color=\"blue\">WARNING: ".
                   5135:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5136:                  "</font>");
                   5137:     }
                   5138:     return $token;
                   5139: }
                   5140: 
                   5141: # ------------------------------------------------------------ Check in an item
                   5142: 
                   5143: sub checkin {
                   5144:     my $token=shift;
                   5145:     my $now=time;
                   5146:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   5147:     $lonhost=~tr/A-Z/a-z/;
                   5148:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
                   5149:     $dtoken=~s/\W/\_/g;
                   5150:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                   5151:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   5152: 
                   5153:     unless (($tuname) && ($tudom)) {
                   5154:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   5155:         return '';
                   5156:     }
                   5157: 
                   5158:     unless (&allowed('mgr',$tcrsid)) {
                   5159:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   5160:                  $env{'user.name'}.' - '.$env{'user.domain'});
                   5161:         return '';
                   5162:     }
                   5163: 
                   5164:     my %infohash=('resource.0.intoken' => $token,
                   5165:                   'resource.0.checkintime' => $now,
                   5166:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
                   5167: 
                   5168:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5169:        return '';
                   5170:     }
                   5171: 
                   5172:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5173:                          &escape('Checkin - '.$token)) ne 'ok') {
                   5174:         return '';
                   5175:     }
                   5176: 
                   5177:     return ($symb,$tuname,$tudom,$tcrsid);
                   5178: }
                   5179: 
1.110     www      5180: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5181: 
                   5182: sub expirespread {
                   5183:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5184:     my $cid=$env{'request.course.id'}; 
1.110     www      5185:     if ($cid) {
                   5186:        my $now=time;
                   5187:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5188:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5189:                             $env{'course.'.$cid.'.num'}.
1.110     www      5190: 	        	    ':nohist_expirationdates:'.
                   5191:                             &escape($key).'='.$now,
1.620     albertel 5192:                             $env{'course.'.$cid.'.home'})
1.110     www      5193:     }
                   5194:     return 'ok';
1.14      www      5195: }
                   5196: 
1.109     www      5197: # ----------------------------------------------------- Devalidate Spreadsheets
                   5198: 
                   5199: sub devalidate {
1.325     www      5200:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5201:     my $cid=$env{'request.course.id'}; 
1.109     www      5202:     if ($cid) {
1.391     matthew  5203:         # delete the stored spreadsheets for
                   5204:         # - the student level sheet of this user in course's homespace
                   5205:         # - the assessment level sheet for this resource 
                   5206:         #   for this user in user's homespace
1.553     albertel 5207: 	# - current conditional state info
1.325     www      5208: 	my $key=$uname.':'.$udom.':';
1.109     www      5209:         my $status=
1.299     matthew  5210: 	    &del('nohist_calculatedsheets',
1.391     matthew  5211: 		 [$key.'studentcalc:'],
1.620     albertel 5212: 		 $env{'course.'.$cid.'.domain'},
                   5213: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5214: 		.' '.
                   5215: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5216: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5217:         unless ($status eq 'ok ok') {
                   5218:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5219:                     $uname.' at '.$udom.' for '.
1.109     www      5220: 		    $symb.': '.$status);
1.133     albertel 5221:         }
1.553     albertel 5222: 	&delenv('user.state.'.$cid);
1.109     www      5223:     }
                   5224: }
                   5225: 
1.265     albertel 5226: sub get_scalar {
                   5227:     my ($string,$end) = @_;
                   5228:     my $value;
                   5229:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5230: 	$value = $1;
                   5231:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5232: 	$value = $1;
                   5233:     }
                   5234:     return &unescape($value);
                   5235: }
                   5236: 
                   5237: sub array2str {
                   5238:   my (@array) = @_;
                   5239:   my $result=&arrayref2str(\@array);
                   5240:   $result=~s/^__ARRAY_REF__//;
                   5241:   $result=~s/__END_ARRAY_REF__$//;
                   5242:   return $result;
                   5243: }
                   5244: 
1.204     albertel 5245: sub arrayref2str {
                   5246:   my ($arrayref) = @_;
1.265     albertel 5247:   my $result='__ARRAY_REF__';
1.204     albertel 5248:   foreach my $elem (@$arrayref) {
1.265     albertel 5249:     if(ref($elem) eq 'ARRAY') {
                   5250:       $result.=&arrayref2str($elem).'&';
                   5251:     } elsif(ref($elem) eq 'HASH') {
                   5252:       $result.=&hashref2str($elem).'&';
                   5253:     } elsif(ref($elem)) {
                   5254:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5255:     } else {
                   5256:       $result.=&escape($elem).'&';
                   5257:     }
                   5258:   }
                   5259:   $result=~s/\&$//;
1.265     albertel 5260:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5261:   return $result;
                   5262: }
                   5263: 
1.168     albertel 5264: sub hash2str {
1.204     albertel 5265:   my (%hash) = @_;
                   5266:   my $result=&hashref2str(\%hash);
1.265     albertel 5267:   $result=~s/^__HASH_REF__//;
                   5268:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5269:   return $result;
                   5270: }
                   5271: 
                   5272: sub hashref2str {
                   5273:   my ($hashref)=@_;
1.265     albertel 5274:   my $result='__HASH_REF__';
1.800     albertel 5275:   foreach my $key (sort(keys(%$hashref))) {
                   5276:     if (ref($key) eq 'ARRAY') {
                   5277:       $result.=&arrayref2str($key).'=';
                   5278:     } elsif (ref($key) eq 'HASH') {
                   5279:       $result.=&hashref2str($key).'=';
                   5280:     } elsif (ref($key)) {
1.265     albertel 5281:       $result.='=';
1.800     albertel 5282:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5283:     } else {
1.1132    raeburn  5284: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5285:     }
                   5286: 
1.800     albertel 5287:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5288:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5289:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5290:       $result.=&hashref2str($hashref->{$key}).'&';
                   5291:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5292:        $result.='&';
1.800     albertel 5293:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5294:     } else {
1.800     albertel 5295:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5296:     }
                   5297:   }
1.168     albertel 5298:   $result=~s/\&$//;
1.265     albertel 5299:   $result .= '__END_HASH_REF__';
1.168     albertel 5300:   return $result;
                   5301: }
                   5302: 
                   5303: sub str2hash {
1.265     albertel 5304:     my ($string)=@_;
                   5305:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5306:     return %$hash;
                   5307: }
                   5308: 
                   5309: sub str2hashref {
1.168     albertel 5310:   my ($string) = @_;
1.265     albertel 5311: 
                   5312:   my %hash;
                   5313: 
                   5314:   if($string !~ /^__HASH_REF__/) {
                   5315:       if (! ($string eq '' || !defined($string))) {
                   5316: 	  $hash{'error'}='Not hash reference';
                   5317:       }
                   5318:       return (\%hash, $string);
                   5319:   }
                   5320: 
                   5321:   $string =~ s/^__HASH_REF__//;
                   5322: 
                   5323:   while($string !~ /^__END_HASH_REF__/) {
                   5324:       #key
                   5325:       my $key='';
                   5326:       if($string =~ /^__HASH_REF__/) {
                   5327:           ($key, $string)=&str2hashref($string);
                   5328:           if(defined($key->{'error'})) {
                   5329:               $hash{'error'}='Bad data';
                   5330:               return (\%hash, $string);
                   5331:           }
                   5332:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5333:           ($key, $string)=&str2arrayref($string);
                   5334:           if($key->[0] eq 'Array reference error') {
                   5335:               $hash{'error'}='Bad data';
                   5336:               return (\%hash, $string);
                   5337:           }
                   5338:       } else {
                   5339:           $string =~ s/^(.*?)=//;
1.267     albertel 5340: 	  $key=&unescape($1);
1.265     albertel 5341:       }
                   5342:       $string =~ s/^=//;
                   5343: 
                   5344:       #value
                   5345:       my $value='';
                   5346:       if($string =~ /^__HASH_REF__/) {
                   5347:           ($value, $string)=&str2hashref($string);
                   5348:           if(defined($value->{'error'})) {
                   5349:               $hash{'error'}='Bad data';
                   5350:               return (\%hash, $string);
                   5351:           }
                   5352:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5353:           ($value, $string)=&str2arrayref($string);
                   5354:           if($value->[0] eq 'Array reference error') {
                   5355:               $hash{'error'}='Bad data';
                   5356:               return (\%hash, $string);
                   5357:           }
                   5358:       } else {
                   5359: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5360:       }
                   5361:       $string =~ s/^&//;
                   5362: 
                   5363:       $hash{$key}=$value;
1.204     albertel 5364:   }
1.265     albertel 5365: 
                   5366:   $string =~ s/^__END_HASH_REF__//;
                   5367: 
                   5368:   return (\%hash, $string);
1.204     albertel 5369: }
                   5370: 
                   5371: sub str2array {
1.265     albertel 5372:     my ($string)=@_;
                   5373:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5374:     return @$array;
                   5375: }
                   5376: 
                   5377: sub str2arrayref {
1.204     albertel 5378:   my ($string) = @_;
1.265     albertel 5379:   my @array;
                   5380: 
                   5381:   if($string !~ /^__ARRAY_REF__/) {
                   5382:       if (! ($string eq '' || !defined($string))) {
                   5383: 	  $array[0]='Array reference error';
                   5384:       }
                   5385:       return (\@array, $string);
                   5386:   }
                   5387: 
                   5388:   $string =~ s/^__ARRAY_REF__//;
                   5389: 
                   5390:   while($string !~ /^__END_ARRAY_REF__/) {
                   5391:       my $value='';
                   5392:       if($string =~ /^__HASH_REF__/) {
                   5393:           ($value, $string)=&str2hashref($string);
                   5394:           if(defined($value->{'error'})) {
                   5395:               $array[0] ='Array reference error';
                   5396:               return (\@array, $string);
                   5397:           }
                   5398:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5399:           ($value, $string)=&str2arrayref($string);
                   5400:           if($value->[0] eq 'Array reference error') {
                   5401:               $array[0] ='Array reference error';
                   5402:               return (\@array, $string);
                   5403:           }
                   5404:       } else {
                   5405: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5406:       }
                   5407:       $string =~ s/^&//;
                   5408: 
                   5409:       push(@array, $value);
1.191     harris41 5410:   }
1.265     albertel 5411: 
                   5412:   $string =~ s/^__END_ARRAY_REF__//;
                   5413: 
                   5414:   return (\@array, $string);
1.168     albertel 5415: }
                   5416: 
1.167     albertel 5417: # -------------------------------------------------------------------Temp Store
                   5418: 
1.168     albertel 5419: sub tmpreset {
                   5420:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5421:   if (!$symb) {
                   5422:     $symb=&symbread();
1.620     albertel 5423:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5424:   }
                   5425:   $symb=escape($symb);
                   5426: 
1.620     albertel 5427:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5428:   $namespace=~s/\//\_/g;
                   5429:   $namespace=~s/\W//g;
                   5430: 
1.620     albertel 5431:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5432:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5433:   if ($domain eq 'public' && $stuname eq 'public') {
                   5434:       $stuname=$ENV{'REMOTE_ADDR'};
                   5435:   }
1.1117    foxr     5436:   my $path=LONCAPA::tempdir();
1.168     albertel 5437:   my %hash;
                   5438:   if (tie(%hash,'GDBM_File',
                   5439: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5440: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5441:     foreach my $key (keys(%hash)) {
1.180     albertel 5442:       if ($key=~ /:$symb/) {
1.168     albertel 5443: 	delete($hash{$key});
                   5444:       }
                   5445:     }
                   5446:   }
                   5447: }
                   5448: 
1.167     albertel 5449: sub tmpstore {
1.168     albertel 5450:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5451: 
                   5452:   if (!$symb) {
                   5453:     $symb=&symbread();
1.620     albertel 5454:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5455:   }
                   5456:   $symb=escape($symb);
                   5457: 
                   5458:   if (!$namespace) {
                   5459:     # I don't think we would ever want to store this for a course.
                   5460:     # it seems this will only be used if we don't have a course.
1.620     albertel 5461:     #$namespace=$env{'request.course.id'};
1.168     albertel 5462:     #if (!$namespace) {
1.620     albertel 5463:       $namespace=$env{'request.state'};
1.168     albertel 5464:     #}
                   5465:   }
                   5466:   $namespace=~s/\//\_/g;
                   5467:   $namespace=~s/\W//g;
1.620     albertel 5468:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5469:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5470:   if ($domain eq 'public' && $stuname eq 'public') {
                   5471:       $stuname=$ENV{'REMOTE_ADDR'};
                   5472:   }
1.168     albertel 5473:   my $now=time;
                   5474:   my %hash;
1.1117    foxr     5475:   my $path=LONCAPA::tempdir();
1.168     albertel 5476:   if (tie(%hash,'GDBM_File',
                   5477: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5478: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5479:     $hash{"version:$symb"}++;
                   5480:     my $version=$hash{"version:$symb"};
                   5481:     my $allkeys=''; 
                   5482:     foreach my $key (keys(%$storehash)) {
                   5483:       $allkeys.=$key.':';
1.591     albertel 5484:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5485:     }
                   5486:     $hash{"$version:$symb:timestamp"}=$now;
                   5487:     $allkeys.='timestamp';
                   5488:     $hash{"$version:keys:$symb"}=$allkeys;
                   5489:     if (untie(%hash)) {
                   5490:       return 'ok';
                   5491:     } else {
                   5492:       return "error:$!";
                   5493:     }
                   5494:   } else {
                   5495:     return "error:$!";
                   5496:   }
                   5497: }
1.167     albertel 5498: 
1.168     albertel 5499: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5500: 
1.168     albertel 5501: sub tmprestore {
                   5502:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5503: 
1.168     albertel 5504:   if (!$symb) {
                   5505:     $symb=&symbread();
1.620     albertel 5506:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5507:   }
                   5508:   $symb=escape($symb);
                   5509: 
1.620     albertel 5510:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5511: 
1.620     albertel 5512:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5513:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5514:   if ($domain eq 'public' && $stuname eq 'public') {
                   5515:       $stuname=$ENV{'REMOTE_ADDR'};
                   5516:   }
1.168     albertel 5517:   my %returnhash;
                   5518:   $namespace=~s/\//\_/g;
                   5519:   $namespace=~s/\W//g;
                   5520:   my %hash;
1.1117    foxr     5521:   my $path=LONCAPA::tempdir();
1.168     albertel 5522:   if (tie(%hash,'GDBM_File',
                   5523: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5524: 	  &GDBM_READER(),0640)) {
1.168     albertel 5525:     my $version=$hash{"version:$symb"};
                   5526:     $returnhash{'version'}=$version;
                   5527:     my $scope;
                   5528:     for ($scope=1;$scope<=$version;$scope++) {
                   5529:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5530:       my @keys=split(/:/,$vkeys);
                   5531:       my $key;
                   5532:       $returnhash{"$scope:keys"}=$vkeys;
                   5533:       foreach $key (@keys) {
1.591     albertel 5534: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   5535: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 5536:       }
                   5537:     }
1.168     albertel 5538:     if (!(untie(%hash))) {
                   5539:       return "error:$!";
                   5540:     }
                   5541:   } else {
                   5542:     return "error:$!";
                   5543:   }
                   5544:   return %returnhash;
1.167     albertel 5545: }
                   5546: 
1.9       www      5547: # ----------------------------------------------------------------------- Store
                   5548: 
                   5549: sub store {
1.1172.2.64  raeburn  5550:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5551:     my $home='';
                   5552: 
1.168     albertel 5553:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5554: 
1.213     www      5555:     $symb=&symbclean($symb);
1.122     albertel 5556:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5557: 
1.620     albertel 5558:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5559:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5560: 
                   5561:     &devalidate($symb,$stuname,$domain);
1.109     www      5562: 
                   5563:     $symb=escape($symb);
1.187     www      5564:     if (!$namespace) { 
1.620     albertel 5565:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5566:           return ''; 
                   5567:        } 
                   5568:     }
1.620     albertel 5569:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5570: 
                   5571:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5572:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   5573: 
1.12      www      5574:     my $namevalue='';
1.800     albertel 5575:     foreach my $key (keys(%$storehash)) {
                   5576:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5577:     }
1.12      www      5578:     $namevalue=~s/\&$//;
1.187     www      5579:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64  raeburn  5580:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      5581: }
                   5582: 
1.47      www      5583: # -------------------------------------------------------------- Critical Store
                   5584: 
                   5585: sub cstore {
1.1172.2.64  raeburn  5586:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5587:     my $home='';
                   5588: 
1.168     albertel 5589:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5590: 
1.213     www      5591:     $symb=&symbclean($symb);
1.122     albertel 5592:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5593: 
1.620     albertel 5594:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5595:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5596: 
                   5597:     &devalidate($symb,$stuname,$domain);
1.109     www      5598: 
                   5599:     $symb=escape($symb);
1.187     www      5600:     if (!$namespace) { 
1.620     albertel 5601:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5602:           return ''; 
                   5603:        } 
                   5604:     }
1.620     albertel 5605:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5606: 
                   5607:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5608:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 5609: 
1.47      www      5610:     my $namevalue='';
1.800     albertel 5611:     foreach my $key (keys(%$storehash)) {
                   5612:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5613:     }
1.47      www      5614:     $namevalue=~s/\&$//;
1.187     www      5615:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      5616:     return critical
1.1172.2.64  raeburn  5617:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      5618: }
                   5619: 
1.9       www      5620: # --------------------------------------------------------------------- Restore
                   5621: 
                   5622: sub restore {
1.124     www      5623:     my ($symb,$namespace,$domain,$stuname) = @_;
                   5624:     my $home='';
                   5625: 
1.168     albertel 5626:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5627: 
1.122     albertel 5628:     if (!$symb) {
1.1172.2.26  raeburn  5629:         return if ($namespace eq 'courserequests');
                   5630:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 5631:     } else {
1.1172.2.26  raeburn  5632:         unless ($namespace eq 'courserequests') {
                   5633:             $symb=&escape(&symbclean($symb));
                   5634:         }
1.122     albertel 5635:     }
1.188     www      5636:     if (!$namespace) { 
1.620     albertel 5637:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      5638:           return ''; 
                   5639:        } 
                   5640:     }
1.620     albertel 5641:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5642:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   5643:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 5644:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   5645: 
1.12      www      5646:     my %returnhash=();
1.800     albertel 5647:     foreach my $line (split(/\&/,$answer)) {
                   5648: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 5649:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 5650:     }
1.75      www      5651:     my $version;
                   5652:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 5653:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   5654:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 5655:        }
1.75      www      5656:     }
1.13      www      5657:     return %returnhash;
1.34      www      5658: }
                   5659: 
                   5660: # ---------------------------------------------------------- Course Description
1.1118    foxr     5661: #
                   5662: #  
1.34      www      5663: 
                   5664: sub coursedescription {
1.731     albertel 5665:     my ($courseid,$args)=@_;
1.34      www      5666:     $courseid=~s/^\///;
1.49      www      5667:     $courseid=~s/\_/\//g;
1.34      www      5668:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 5669:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 5670:     my $normalid=$cdomain.'_'.$cnum;
                   5671:     # need to always cache even if we get errors otherwise we keep 
                   5672:     # trying and trying and trying to get the course description.
                   5673:     my %envhash=();
                   5674:     my %returnhash=();
1.731     albertel 5675:     
                   5676:     my $expiretime=600;
                   5677:     if ($env{'request.course.id'} eq $normalid) {
                   5678: 	$expiretime=120;
                   5679:     }
                   5680: 
                   5681:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   5682:     if (!$args->{'freshen_cache'}
                   5683: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   5684: 	foreach my $key (keys(%env)) {
                   5685: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   5686: 	    my ($setting) = $1;
                   5687: 	    $returnhash{$setting} = $env{$key};
                   5688: 	}
                   5689: 	return %returnhash;
                   5690:     }
                   5691: 
1.1118    foxr     5692:     # get the data again
                   5693: 
1.731     albertel 5694:     if (!$args->{'one_time'}) {
                   5695: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   5696:     }
1.811     albertel 5697: 
1.34      www      5698:     if ($chome ne 'no_host') {
1.302     albertel 5699:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 5700:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     5701: 	   my $username = $env{'user.name'}; # Defult username
                   5702: 	   if(defined $args->{'user'}) {
                   5703: 	       $username = $args->{'user'};
                   5704: 	   }
1.129     albertel 5705:            $returnhash{'home'}= $chome;
                   5706: 	   $returnhash{'domain'} = $cdomain;
                   5707: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  5708:            if (!defined($returnhash{'type'})) {
                   5709:                $returnhash{'type'} = 'Course';
                   5710:            }
1.130     albertel 5711:            while (my ($name,$value) = each %returnhash) {
1.53      www      5712:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 5713:            }
1.270     www      5714:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     5715:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     5716: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      5717:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   5718:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   5719:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      5720:        }
                   5721:     }
1.731     albertel 5722:     if (!$args->{'one_time'}) {
1.949     raeburn  5723: 	&appenv(\%envhash);
1.731     albertel 5724:     }
1.302     albertel 5725:     return %returnhash;
1.461     www      5726: }
                   5727: 
1.1080    raeburn  5728: sub update_released_required {
                   5729:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   5730:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   5731:         $cid = $env{'request.course.id'};
                   5732:         $cdom = $env{'course.'.$cid.'.domain'};
                   5733:         $cnum = $env{'course.'.$cid.'.num'};
                   5734:         $chome = $env{'course.'.$cid.'.home'};
                   5735:     }
                   5736:     if ($needsrelease) {
                   5737:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   5738:         my $needsupdate;
                   5739:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   5740:             $needsupdate = 1;
                   5741:         } else {
                   5742:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   5743:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   5744:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   5745:                 $needsupdate = 1;
                   5746:             }
                   5747:         }
                   5748:         if ($needsupdate) {
                   5749:             my %needshash = (
                   5750:                              'internal.releaserequired' => $needsrelease,
                   5751:                             );
                   5752:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   5753:             if ($putresult eq 'ok') {
                   5754:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   5755:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   5756:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   5757:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   5758:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   5759:                 }
                   5760:             }
                   5761:         }
                   5762:     }
                   5763:     return;
                   5764: }
                   5765: 
1.461     www      5766: # -------------------------------------------------See if a user is privileged
                   5767: 
                   5768: sub privileged {
1.1172.2.23  raeburn  5769:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5770:     my $now = time;
1.1172.2.23  raeburn  5771:     my $roles;
                   5772:     if (ref($possroles) eq 'ARRAY') {
                   5773:         $roles = $possroles;
                   5774:     } else {
                   5775:         $roles = ['dc','su'];
                   5776:     }
                   5777:     if (ref($possdomains) eq 'ARRAY') {
                   5778:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   5779:         foreach my $dom (@{$possdomains}) {
                   5780:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   5781:                 (ref($privileged{$dom}) eq 'HASH')) {
                   5782:                 foreach my $role (@{$roles}) {
                   5783:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5784:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5785:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5786:                             return 1 unless (($end && $end < $now) ||
                   5787:                                              ($start && $start > $now));
                   5788:                         }
                   5789:                     }
                   5790:                 }
                   5791:             }
                   5792:         }
                   5793:     } else {
                   5794:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   5795:         my $now = time;
1.1170    droeschl 5796: 
1.1172.2.58  raeburn  5797:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 5798:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  5799:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   5800:                 return 1 unless ($tend && $tend < $now)
                   5801:                         or ($tstart && $tstart > $now);
1.1170    droeschl 5802:             }
1.1172.2.23  raeburn  5803:         }
                   5804:     }
1.461     www      5805:     return 0;
1.9       www      5806: }
1.1       albertel 5807: 
1.1172.2.23  raeburn  5808: sub privileged_by_domain {
                   5809:     my ($domains,$roles) = @_;
                   5810:     my %privileged = ();
                   5811:     my $cachetime = 60*60*24;
                   5812:     my $now = time;
                   5813:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   5814:         return %privileged;
                   5815:     }
                   5816:     foreach my $dom (@{$domains}) {
                   5817:         next if (ref($privileged{$dom}) eq 'HASH');
                   5818:         my $needroles;
                   5819:         foreach my $role (@{$roles}) {
                   5820:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   5821:             if (defined($cached)) {
                   5822:                 if (ref($result) eq 'HASH') {
                   5823:                     $privileged{$dom}{$role} = $result;
                   5824:                 }
                   5825:             } else {
                   5826:                 $needroles = 1;
                   5827:             }
                   5828:         }
                   5829:         if ($needroles) {
                   5830:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   5831:             $privileged{$dom} = {};
                   5832:             foreach my $server (keys(%dompersonnel)) {
                   5833:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   5834:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   5835:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   5836:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   5837:                         next if ($end && $end < $now);
                   5838:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   5839:                             $dompersonnel{$server}{$item};
                   5840:                     }
                   5841:                 }
                   5842:             }
                   5843:             if (ref($privileged{$dom}) eq 'HASH') {
                   5844:                 foreach my $role (@{$roles}) {
                   5845:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5846:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   5847:                     } else {
                   5848:                         my %hash = ();
                   5849:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   5850:                     }
                   5851:                 }
                   5852:             }
                   5853:         }
                   5854:     }
                   5855:     return %privileged;
                   5856: }
                   5857: 
1.103     harris41 5858: # -------------------------------------------------------- Get user privileges
1.11      www      5859: 
                   5860: sub rolesinit {
1.1169    droeschl 5861:     my ($domain, $username) = @_;
                   5862:     my %userroles = ('user.login.time' => time);
                   5863:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   5864: 
                   5865:     # firstaccess and timerinterval are related to timed maps/resources. 
                   5866:     # also, blocking can be triggered by an activating timer
                   5867:     # it's saved in the user's %env.
                   5868:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   5869:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   5870:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   5871:         %timerintchk, %timerintenv);
                   5872: 
1.1162    raeburn  5873:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 5874:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  5875:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   5876:     }
1.1169    droeschl 5877: 
1.1162    raeburn  5878:     foreach my $key (keys(%timerinterval)) {
                   5879:         my ($cid,$rest) = split(/\0/,$key);
                   5880:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   5881:     }
1.1169    droeschl 5882: 
1.11      www      5883:     my %allroles=();
1.1162    raeburn  5884:     my %allgroups=();
1.11      www      5885: 
1.1172.2.58  raeburn  5886:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 5887:         my $role = $rolesdump{$area};
                   5888:         $area =~ s/\_\w\w$//;
                   5889: 
                   5890:         my ($trole, $tend, $tstart, $group_privs);
                   5891: 
                   5892:         if ($role =~ /^cr/) {
                   5893:         # Custom role, defined by a user 
                   5894:         # e.g., user.role.cr/msu/smith/mynewrole
                   5895:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5896:                 $trole = $1;
                   5897:                 ($tend, $tstart) = split('_', $2);
                   5898:             } else {
                   5899:                 $trole = $role;
                   5900:             }
                   5901:         } elsif ($role =~ m|^gr/|) {
                   5902:         # Role of member in a group, defined within a course/community
                   5903:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5904:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5905:             next if $tstart eq '-1';
                   5906:             ($trole, $group_privs) = split(/\//, $trole);
                   5907:             $group_privs = &unescape($group_privs);
                   5908:         } else {
                   5909:         # Just a normal role, defined in roles.tab
                   5910:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5911:         }
                   5912: 
                   5913:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5914:                  $username);
                   5915:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5916: 
                   5917:         # role expired or not available yet?
                   5918:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5919:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5920: 
                   5921:         next if $area eq '' or $trole eq '';
                   5922: 
                   5923:         my $spec = "$trole.$area";
                   5924:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5925: 
                   5926:         if ($trole =~ /^cr\//) {
                   5927:         # Custom role, defined by a user
                   5928:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5929:         } elsif ($trole eq 'gr') {
                   5930:         # Role of a member in a group, defined within a course/community
                   5931:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5932:             next;
                   5933:         } else {
                   5934:         # Normal role, defined in roles.tab
                   5935:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5936:         }
                   5937: 
                   5938:         my $cid = $tdomain.'_'.$trest;
                   5939:         unless ($firstaccchk{$cid}) {
                   5940:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5941:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5942:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5943:                         $coursetimerstarts{$cid}{$item}; 
                   5944:                 }
                   5945:             }
                   5946:             $firstaccchk{$cid} = 1;
                   5947:         }
                   5948:         unless ($timerintchk{$cid}) {
                   5949:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5950:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5951:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5952:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5953:                 }
1.12      www      5954:             }
1.1169    droeschl 5955:             $timerintchk{$cid} = 1;
1.191     harris41 5956:         }
1.11      www      5957:     }
1.1169    droeschl 5958: 
1.1172.2.91  raeburn  5959:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   5960:                                                           \%allroles, \%allgroups);
1.1169    droeschl 5961:     $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91  raeburn  5962:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 5963: 
1.1162    raeburn  5964:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5965: }
                   5966: 
1.567     raeburn  5967: sub set_arearole {
1.1172.2.19  raeburn  5968:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   5969:     unless ($nolog) {
1.567     raeburn  5970: # log the associated role with the area
1.1172.2.19  raeburn  5971:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   5972:     }
1.743     albertel 5973:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5974: }
                   5975: 
                   5976: sub custom_roleprivs {
                   5977:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5978:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40  raeburn  5979:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 5980:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5981:         my ($rdummy,$roledef)=
                   5982:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5983:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5984:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5985:             if (defined($syspriv)) {
1.1043    raeburn  5986:                 if ($trest =~ /^$match_community$/) {
                   5987:                     $syspriv =~ s/bre\&S//; 
                   5988:                 }
1.567     raeburn  5989:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5990:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5991:             }
                   5992:             if ($tdomain ne '') {
                   5993:                 if (defined($dompriv)) {
                   5994:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5995:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5996:                 }
                   5997:                 if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89  raeburn  5998:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   5999:                         my $rolename = $1;
                   6000:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6001:                     }
1.567     raeburn  6002:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6003:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6004:                 }
                   6005:             }
                   6006:         }
                   6007:     }
                   6008: }
                   6009: 
1.1172.2.89  raeburn  6010: sub course_adhocrole_privs {
                   6011:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6012:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6013:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6014:         my (%currprivs,%storeprivs);
                   6015:         foreach my $item (split(/:/,$coursepriv)) {
                   6016:             my ($priv,$restrict) = split(/\&/,$item);
                   6017:             $currprivs{$priv} = $restrict;
                   6018:         }
                   6019:         my (%possadd,%possremove,%full);
                   6020:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6021:             my ($priv,$restrict)=split(/\&/,$item);
                   6022:             $full{$priv} = $restrict;
                   6023:         }
                   6024:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   6025:              next if ($item eq '');
                   6026:              my ($rule,$rest) = split(/=/,$item);
                   6027:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   6028:              foreach my $priv (split(/:/,$rest)) {
                   6029:                  if ($priv ne '') {
                   6030:                      if ($rule eq 'off') {
                   6031:                          $possremove{$priv} = 1;
                   6032:                      } else {
                   6033:                          $possadd{$priv} = 1;
                   6034:                      }
                   6035:                  }
                   6036:              }
                   6037:          }
                   6038:          foreach my $priv (sort(keys(%full))) {
                   6039:              if (exists($currprivs{$priv})) {
                   6040:                  unless (exists($possremove{$priv})) {
                   6041:                      $storeprivs{$priv} = $currprivs{$priv};
                   6042:                  }
                   6043:              } elsif (exists($possadd{$priv})) {
                   6044:                  $storeprivs{$priv} = $full{$priv};
                   6045:              }
                   6046:          }
                   6047:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6048:      }
                   6049:      return $coursepriv;
                   6050: }
                   6051: 
1.678     raeburn  6052: sub group_roleprivs {
                   6053:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6054:     my $access = 1;
                   6055:     my $now = time;
                   6056:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6057:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6058:     if ($access) {
1.811     albertel 6059:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6060:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6061:     }
                   6062: }
1.567     raeburn  6063: 
                   6064: sub standard_roleprivs {
                   6065:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6066:     if (defined($pr{$trole.':s'})) {
                   6067:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6068:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6069:     }
                   6070:     if ($tdomain ne '') {
                   6071:         if (defined($pr{$trole.':d'})) {
                   6072:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6073:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6074:         }
                   6075:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6076:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6077:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6078:         }
                   6079:     }
                   6080: }
                   6081: 
                   6082: sub set_userprivs {
1.1064    raeburn  6083:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6084:     my $author=0;
                   6085:     my $adv=0;
1.1172.2.91  raeburn  6086:     my $rar=0;
1.678     raeburn  6087:     my %grouproles = ();
                   6088:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6089:         my @groupkeys; 
1.1000    raeburn  6090:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6091:             push(@groupkeys,$role);
                   6092:         }
                   6093:         if (ref($groups_roles) eq 'HASH') {
                   6094:             foreach my $key (keys(%{$groups_roles})) {
                   6095:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6096:                     push(@groupkeys,$key);
                   6097:                 }
                   6098:             }
                   6099:         }
                   6100:         if (@groupkeys > 0) {
                   6101:             foreach my $role (@groupkeys) {
                   6102:                 my ($trole,$area,$sec,$extendedarea);
                   6103:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6104:                     $trole = $1;
                   6105:                     $area = $2;
                   6106:                     $sec = $3;
                   6107:                     $extendedarea = $area.$sec;
                   6108:                     if (exists($$allgroups{$area})) {
                   6109:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6110:                             my $spec = $trole.'.'.$extendedarea;
                   6111:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6112:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6113:                         }
1.678     raeburn  6114:                     }
                   6115:                 }
                   6116:             }
                   6117:         }
                   6118:     }
1.800     albertel 6119:     foreach my $group (keys(%grouproles)) {
                   6120:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6121:     }
1.800     albertel 6122:     foreach my $role (keys(%{$allroles})) {
                   6123:         my %thesepriv;
1.941     raeburn  6124:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6125:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6126:             if ($item ne '') {
                   6127:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6128:                 if ($restrictions eq '') {
                   6129:                     $thesepriv{$privilege}='F';
                   6130:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6131:                     $thesepriv{$privilege}.=$restrictions;
                   6132:                 }
                   6133:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91  raeburn  6134:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6135:             }
                   6136:         }
                   6137:         my $thesestr='';
1.1104    raeburn  6138:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6139: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6140: 	}
                   6141:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6142:     }
1.1172.2.91  raeburn  6143:     return ($author,$adv,$rar);
1.567     raeburn  6144: }
                   6145: 
1.994     raeburn  6146: sub role_status {
1.1104    raeburn  6147:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6148:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40  raeburn  6149:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6150:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6151:         unless (!defined($$role) || $$role eq '') {
1.1172.2.40  raeburn  6152:             $$where = '/'.$two;
1.994     raeburn  6153:             $$trolecode=$$role.'.'.$$where;
                   6154:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6155:             $$tstatus='is';
1.1104    raeburn  6156:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6157:                 $$tstatus='future';
1.1034    raeburn  6158:                 if ($$tstart<$now) {
                   6159:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6160:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6161:                             my (%allroles,%allgroups,$group_privs,
                   6162:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6163:                             my %userroles = (
                   6164:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6165:                             );
1.1064    raeburn  6166:                             @rolecodes = ('cm'); 
1.1002    raeburn  6167:                             my $spec=$$role.'.'.$$where;
                   6168:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6169:                             if ($$role =~ /^cr\//) {
                   6170:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6171:                                 push(@rolecodes,'cr');
1.1002    raeburn  6172:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6173:                                 push(@rolecodes,$$role);
1.1002    raeburn  6174:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6175:                                                     $env{'user.name'});
1.1064    raeburn  6176:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6177:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6178:                                 $group_privs = &unescape($group_privs);
                   6179:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6180:                                 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  6181:                                 &get_groups_roles($tdomain,$trest,
                   6182:                                                   \%course_roles,\@rolecodes,
                   6183:                                                   \%groups_roles);
1.1002    raeburn  6184:                             } else {
1.1064    raeburn  6185:                                 push(@rolecodes,$$role);
1.1002    raeburn  6186:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6187:                             }
1.1172.2.91  raeburn  6188:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6189:                                                                    \%groups_roles);
1.1064    raeburn  6190:                             &appenv(\%userroles,\@rolecodes);
1.1172.2.92  raeburn  6191:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6192:                         }
                   6193:                     }
1.1034    raeburn  6194:                     $$tstatus = 'is';
1.1002    raeburn  6195:                 }
1.994     raeburn  6196:             }
                   6197:             if ($$tend) {
1.1104    raeburn  6198:                 if ($$tend<$update) {
1.994     raeburn  6199:                     $$tstatus='expired';
                   6200:                 } elsif ($$tend<$now) {
                   6201:                     $$tstatus='will_not';
                   6202:                 }
                   6203:             }
                   6204:         }
                   6205:     }
                   6206: }
                   6207: 
1.1104    raeburn  6208: sub get_groups_roles {
                   6209:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6210:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6211:                   (ref($rolecodes) eq 'ARRAY') && 
                   6212:                   (ref($groups_roles) eq 'HASH')); 
                   6213:     if (keys(%{$cdom_courseroles}) > 0) {
                   6214:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6215:         if ($cdom ne '' && $cnum ne '') {
                   6216:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6217:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6218:                     my $crsrole = $1;
                   6219:                     my $crssec = $2;
                   6220:                     if ($crsrole =~ /^cr/) {
                   6221:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6222:                             push(@{$rolecodes},'cr');
                   6223:                         }
                   6224:                     } else {
                   6225:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6226:                             push(@{$rolecodes},$crsrole);
                   6227:                         }
                   6228:                     }
                   6229:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6230:                     if ($crssec ne '') {
                   6231:                         $rolekey .= "/$crssec";
                   6232:                     }
                   6233:                     $rolekey .= './';
                   6234:                     $groups_roles->{$rolekey} = $rolecodes;
                   6235:                 }
                   6236:             }
                   6237:         }
                   6238:     }
                   6239:     return;
                   6240: }
                   6241: 
                   6242: sub delete_env_groupprivs {
                   6243:     my ($where,$courseroles,$possroles) = @_;
                   6244:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6245:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6246:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6247:         %{$courseroles->{$udom}} =
                   6248:             &get_my_roles('','','userroles',['active'],
                   6249:                           $possroles,[$udom],1);
                   6250:     }
                   6251:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6252:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6253:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6254:             my $area = '/'.$cdom.'/'.$cnum;
                   6255:             my $privkey = "user.priv.$crsrole.$area";
                   6256:             if ($crssec ne '') {
                   6257:                 $privkey .= '/'.$crssec;
                   6258:             }
                   6259:             $privkey .= ".$area/$group";
                   6260:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6261:         }
                   6262:     }
                   6263:     return;
                   6264: }
                   6265: 
1.994     raeburn  6266: sub check_adhoc_privs {
1.1172.2.86  raeburn  6267:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6268:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86  raeburn  6269:     if ($sec) {
                   6270:         $cckey .= '/'.$sec;
                   6271:     }
1.1172.2.9  raeburn  6272:     my $setprivs;
1.994     raeburn  6273:     if ($env{$cckey}) {
                   6274:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6275:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6276:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86  raeburn  6277:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6278:             $setprivs = 1;
1.994     raeburn  6279:         }
                   6280:     } else {
1.1172.2.87  raeburn  6281:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6282:         $setprivs = 1;
1.994     raeburn  6283:     }
1.1172.2.9  raeburn  6284:     return $setprivs;
1.994     raeburn  6285: }
                   6286: 
                   6287: sub set_adhoc_privileges {
1.1172.2.84  raeburn  6288: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86  raeburn  6289:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6290:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86  raeburn  6291:     if ($sec ne '') {
                   6292:         $area .= '/'.$sec;
                   6293:     }
1.994     raeburn  6294:     my $spec = $role.'.'.$area;
                   6295:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  6296:                                   $env{'user.name'},1);
1.1172.2.84  raeburn  6297:     my %rolehash = ();
1.1172.2.89  raeburn  6298:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6299:         my $rolename = $1;
1.1172.2.84  raeburn  6300:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89  raeburn  6301:         my %domdef = &get_domain_defaults($dcdom);
                   6302:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6303:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6304:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6305:             }
                   6306:         }
1.1172.2.84  raeburn  6307:     } else {
                   6308:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6309:     }
1.1172.2.91  raeburn  6310:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6311:     &appenv(\%userroles,[$role,'cm']);
1.1172.2.92  raeburn  6312:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088    raeburn  6313:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   6314:         &appenv( {'request.role'        => $spec,
                   6315:                   'request.role.domain' => $dcdom,
1.1172.2.89  raeburn  6316:                   'request.course.sec'  => $sec, 
1.1088    raeburn  6317:                  }
                   6318:                );
                   6319:         my $tadv=0;
                   6320:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6321:         &appenv({'request.role.adv'    => $tadv});
                   6322:     }
1.994     raeburn  6323: }
                   6324: 
1.12      www      6325: # --------------------------------------------------------------- get interface
                   6326: 
                   6327: sub get {
1.131     albertel 6328:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6329:    my $items='';
1.800     albertel 6330:    foreach my $item (@$storearr) {
                   6331:        $items.=&escape($item).'&';
1.191     harris41 6332:    }
1.12      www      6333:    $items=~s/\&$//;
1.620     albertel 6334:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6335:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6336:    my $uhome=&homeserver($uname,$udomain);
                   6337: 
1.133     albertel 6338:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6339:    my @pairs=split(/\&/,$rep);
1.273     albertel 6340:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6341:      return @pairs;
                   6342:    }
1.15      www      6343:    my %returnhash=();
1.42      www      6344:    my $i=0;
1.800     albertel 6345:    foreach my $item (@$storearr) {
                   6346:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6347:       $i++;
1.191     harris41 6348:    }
1.15      www      6349:    return %returnhash;
1.27      www      6350: }
                   6351: 
                   6352: # --------------------------------------------------------------- del interface
                   6353: 
                   6354: sub del {
1.133     albertel 6355:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6356:    my $items='';
1.800     albertel 6357:    foreach my $item (@$storearr) {
                   6358:        $items.=&escape($item).'&';
1.191     harris41 6359:    }
1.984     neumanie 6360: 
1.27      www      6361:    $items=~s/\&$//;
1.620     albertel 6362:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6363:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6364:    my $uhome=&homeserver($uname,$udomain);
                   6365:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6366: }
                   6367: 
                   6368: # -------------------------------------------------------------- dump interface
                   6369: 
1.1172.2.22  raeburn  6370: sub unserialize {
                   6371:     my ($rep, $escapedkeys) = @_;
                   6372: 
                   6373:     return {} if $rep =~ /^error/;
                   6374: 
                   6375:     my %returnhash=();
                   6376:     foreach my $item (split(/\&/,$rep)) {
                   6377:         my ($key, $value) = split(/=/, $item, 2);
                   6378:         $key = unescape($key) unless $escapedkeys;
                   6379:         next if $key =~ /^error: 2 /;
                   6380:         $returnhash{$key} = &thaw_unescape($value);
                   6381:     }
                   6382:     return \%returnhash;
                   6383: }
                   6384: 
                   6385: # see Lond::dump_with_regexp
                   6386: # if $escapedkeys hash keys won't get unescaped.
1.15      www      6387: sub dump {
1.1172.2.22  raeburn  6388:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 6389:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6390:     if (!$uname) { $uname=$env{'user.name'}; }
                   6391:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 6392: 
1.1172.2.55  raeburn  6393:     if ($regexp) {
                   6394:         $regexp=&escape($regexp);
                   6395:     } else {
                   6396:         $regexp='.';
                   6397:     }
1.1172.2.22  raeburn  6398:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   6399:         # user is hosted on this machine
1.1172.2.55  raeburn  6400:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  6401:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  6402:         return %{&unserialize($reply, $escapedkeys)};
                   6403:     }
1.1166    raeburn  6404:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 6405:     my @pairs=split(/\&/,$rep);
                   6406:     my %returnhash=();
1.1098    foxr     6407:     if (!($rep =~ /^error/ )) {
                   6408: 	foreach my $item (@pairs) {
                   6409: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  6410:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     6411: 	    next if ($key =~ /^error: 2 /);
                   6412: 	    $returnhash{$key}=&thaw_unescape($value);
                   6413: 	}
1.755     albertel 6414:     }
                   6415:     return %returnhash;
1.407     www      6416: }
                   6417: 
1.1098    foxr     6418: 
1.717     albertel 6419: # --------------------------------------------------------- dumpstore interface
                   6420: 
                   6421: sub dumpstore {
                   6422:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  6423:    # same as dump but keys must be escaped. They may contain colon separated
                   6424:    # lists of values that may themself contain colons (e.g. symbs).
                   6425:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 6426: }
                   6427: 
1.407     www      6428: # -------------------------------------------------------------- keys interface
                   6429: 
                   6430: sub getkeys {
                   6431:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 6432:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6433:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      6434:    my $uhome=&homeserver($uname,$udomain);
                   6435:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   6436:    my @keyarray=();
1.800     albertel 6437:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  6438:       next if ($key =~ /^error: 2 /);
1.800     albertel 6439:       push(@keyarray,&unescape($key));
1.407     www      6440:    }
                   6441:    return @keyarray;
1.318     matthew  6442: }
                   6443: 
1.319     matthew  6444: # --------------------------------------------------------------- currentdump
                   6445: sub currentdump {
1.328     matthew  6446:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 6447:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   6448:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   6449:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  6450:    my $uhome = &homeserver($sname,$sdom);
1.1172.2.50  raeburn  6451:    my $rep;
                   6452: 
                   6453:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   6454:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
                   6455:                    $courseid)));
                   6456:    } else {
                   6457:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6458:    }
                   6459: 
1.318     matthew  6460:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6461:    #
1.318     matthew  6462:    my %returnhash=();
1.319     matthew  6463:    #
                   6464:    if ($rep eq "unknown_cmd") { 
                   6465:        # an old lond will not know currentdump
                   6466:        # Do a dump and make it look like a currentdump
1.822     albertel 6467:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6468:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6469:        my %hash = @tmp;
                   6470:        @tmp=();
1.424     matthew  6471:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6472:    } else {
                   6473:        my @pairs=split(/\&/,$rep);
1.800     albertel 6474:        foreach my $pair (@pairs) {
                   6475:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6476:            my ($symb,$param) = split(/:/,$key);
                   6477:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6478:                                                         &thaw_unescape($value);
1.319     matthew  6479:        }
1.191     harris41 6480:    }
1.12      www      6481:    return %returnhash;
1.424     matthew  6482: }
                   6483: 
                   6484: sub convert_dump_to_currentdump{
                   6485:     my %hash = %{shift()};
                   6486:     my %returnhash;
                   6487:     # Code ripped from lond, essentially.  The only difference
                   6488:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6489:     # we might run in to problems with parameter names =~ /^v\./
                   6490:     while (my ($key,$value) = each(%hash)) {
                   6491:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6492: 	$symb  = &unescape($symb);
                   6493: 	$param = &unescape($param);
1.424     matthew  6494:         next if ($v eq 'version' || $symb eq 'keys');
                   6495:         next if (exists($returnhash{$symb}) &&
                   6496:                  exists($returnhash{$symb}->{$param}) &&
                   6497:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6498:         $returnhash{$symb}->{$param}=$value;
                   6499:         $returnhash{$symb}->{'v.'.$param}=$v;
                   6500:     }
                   6501:     #
                   6502:     # Remove all of the keys in the hashes which keep track of
                   6503:     # the version of the parameter.
                   6504:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   6505:         # use a foreach because we are going to delete from the hash.
                   6506:         foreach my $key (keys(%$param_hash)) {
                   6507:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   6508:         }
                   6509:     }
                   6510:     return \%returnhash;
1.12      www      6511: }
                   6512: 
1.627     albertel 6513: # ------------------------------------------------------ critical inc interface
                   6514: 
                   6515: sub cinc {
                   6516:     return &inc(@_,'critical');
                   6517: }
                   6518: 
1.449     matthew  6519: # --------------------------------------------------------------- inc interface
                   6520: 
                   6521: sub inc {
1.627     albertel 6522:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 6523:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6524:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  6525:     my $uhome=&homeserver($uname,$udomain);
                   6526:     my $items='';
                   6527:     if (! ref($store)) {
                   6528:         # got a single value, so use that instead
                   6529:         $items = &escape($store).'=&';
                   6530:     } elsif (ref($store) eq 'SCALAR') {
                   6531:         $items = &escape($$store).'=&';        
                   6532:     } elsif (ref($store) eq 'ARRAY') {
                   6533:         $items = join('=&',map {&escape($_);} @{$store});
                   6534:     } elsif (ref($store) eq 'HASH') {
                   6535:         while (my($key,$value) = each(%{$store})) {
                   6536:             $items.= &escape($key).'='.&escape($value).'&';
                   6537:         }
                   6538:     }
                   6539:     $items=~s/\&$//;
1.627     albertel 6540:     if ($critical) {
                   6541: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6542:     } else {
                   6543: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6544:     }
1.449     matthew  6545: }
                   6546: 
1.12      www      6547: # --------------------------------------------------------------- put interface
                   6548: 
                   6549: sub put {
1.134     albertel 6550:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6551:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6552:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6553:    my $uhome=&homeserver($uname,$udomain);
1.12      www      6554:    my $items='';
1.800     albertel 6555:    foreach my $item (keys(%$storehash)) {
                   6556:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6557:    }
1.12      www      6558:    $items=~s/\&$//;
1.134     albertel 6559:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      6560: }
                   6561: 
1.631     albertel 6562: # ------------------------------------------------------------ newput interface
                   6563: 
                   6564: sub newput {
                   6565:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   6566:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6567:    if (!$uname) { $uname=$env{'user.name'}; }
                   6568:    my $uhome=&homeserver($uname,$udomain);
                   6569:    my $items='';
                   6570:    foreach my $key (keys(%$storehash)) {
                   6571:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   6572:    }
                   6573:    $items=~s/\&$//;
                   6574:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   6575: }
                   6576: 
                   6577: # ---------------------------------------------------------  putstore interface
                   6578: 
1.524     raeburn  6579: sub putstore {
1.1172.2.59  raeburn  6580:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 6581:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6582:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  6583:    my $uhome=&homeserver($uname,$udomain);
                   6584:    my $items='';
1.715     albertel 6585:    foreach my $key (keys(%$storehash)) {
                   6586:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  6587:    }
1.715     albertel 6588:    $items=~s/\&$//;
1.716     albertel 6589:    my $esc_symb=&escape($symb);
                   6590:    my $esc_v=&escape($version);
1.715     albertel 6591:    my $reply =
1.716     albertel 6592:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 6593: 	      $uhome);
1.1172.2.59  raeburn  6594:    if (($tolog) && ($reply eq 'ok')) {
                   6595:        my $namevalue='';
                   6596:        foreach my $key (keys(%{$storehash})) {
                   6597:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   6598:        }
                   6599:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   6600:                      '&host='.&escape($perlvar{'lonHostID'}).
                   6601:                      '&version='.$esc_v.
                   6602:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   6603:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   6604:    }
1.715     albertel 6605:    if ($reply eq 'unknown_cmd') {
1.716     albertel 6606:        # gfall back to way things use to be done
1.715     albertel 6607:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   6608: 			    $uname);
1.524     raeburn  6609:    }
1.715     albertel 6610:    return $reply;
                   6611: }
                   6612: 
                   6613: sub old_putstore {
1.716     albertel 6614:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   6615:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6616:     if (!$uname) { $uname=$env{'user.name'}; }
                   6617:     my $uhome=&homeserver($uname,$udomain);
                   6618:     my %newstorehash;
1.800     albertel 6619:     foreach my $item (keys(%$storehash)) {
                   6620: 	my $key = $version.':'.&escape($symb).':'.$item;
                   6621: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 6622:     }
                   6623:     my $items='';
                   6624:     my %allitems = ();
1.800     albertel 6625:     foreach my $item (keys(%newstorehash)) {
                   6626: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 6627: 	    my $key = $1.':keys:'.$2;
                   6628: 	    $allitems{$key} .= $3.':';
                   6629: 	}
1.800     albertel 6630: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 6631:     }
1.800     albertel 6632:     foreach my $item (keys(%allitems)) {
                   6633: 	$allitems{$item} =~ s/\:$//;
                   6634: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 6635:     }
                   6636:     $items=~s/\&$//;
                   6637:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  6638: }
                   6639: 
1.47      www      6640: # ------------------------------------------------------ critical put interface
                   6641: 
                   6642: sub cput {
1.134     albertel 6643:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6644:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6645:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6646:    my $uhome=&homeserver($uname,$udomain);
1.47      www      6647:    my $items='';
1.800     albertel 6648:    foreach my $item (keys(%$storehash)) {
                   6649:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6650:    }
1.47      www      6651:    $items=~s/\&$//;
1.134     albertel 6652:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6653: }
                   6654: 
                   6655: # -------------------------------------------------------------- eget interface
                   6656: 
                   6657: sub eget {
1.133     albertel 6658:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6659:    my $items='';
1.800     albertel 6660:    foreach my $item (@$storearr) {
                   6661:        $items.=&escape($item).'&';
1.191     harris41 6662:    }
1.12      www      6663:    $items=~s/\&$//;
1.620     albertel 6664:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6665:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6666:    my $uhome=&homeserver($uname,$udomain);
                   6667:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6668:    my @pairs=split(/\&/,$rep);
                   6669:    my %returnhash=();
1.42      www      6670:    my $i=0;
1.800     albertel 6671:    foreach my $item (@$storearr) {
                   6672:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6673:       $i++;
1.191     harris41 6674:    }
1.12      www      6675:    return %returnhash;
                   6676: }
                   6677: 
1.667     albertel 6678: # ------------------------------------------------------------ tmpput interface
                   6679: sub tmpput {
1.802     raeburn  6680:     my ($storehash,$server,$context)=@_;
1.667     albertel 6681:     my $items='';
1.800     albertel 6682:     foreach my $item (keys(%$storehash)) {
                   6683: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 6684:     }
                   6685:     $items=~s/\&$//;
1.802     raeburn  6686:     if (defined($context)) {
                   6687:         $items .= ':'.&escape($context);
                   6688:     }
1.667     albertel 6689:     return &reply("tmpput:$items",$server);
                   6690: }
                   6691: 
                   6692: # ------------------------------------------------------------ tmpget interface
                   6693: sub tmpget {
1.688     albertel 6694:     my ($token,$server)=@_;
                   6695:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6696:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 6697:     my %returnhash;
1.1172.2.85  raeburn  6698:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   6699:         return %returnhash;
                   6700:     }
1.667     albertel 6701:     foreach my $item (split(/\&/,$rep)) {
                   6702: 	my ($key,$value)=split(/=/,$item);
                   6703: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   6704:     }
                   6705:     return %returnhash;
                   6706: }
                   6707: 
1.1113    raeburn  6708: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 6709: sub tmpdel {
                   6710:     my ($token,$server)=@_;
                   6711:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6712:     return &reply("tmpdel:$token",$server);
                   6713: }
                   6714: 
1.1172.2.13  raeburn  6715: # ------------------------------------------------------------ get_timebased_id
                   6716: 
                   6717: sub get_timebased_id {
                   6718:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   6719:         $maxtries) = @_;
                   6720:     my ($newid,$error,$dellock);
                   6721:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   6722:         return ('','ok','invalid call to get suffix');
                   6723:     }
                   6724: 
                   6725: # set defaults for any optional args for which values were not supplied
                   6726:     if ($who eq '') {
                   6727:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   6728:     }
                   6729:     if (!$locktries) {
                   6730:         $locktries = 3;
                   6731:     }
                   6732:     if (!$maxtries) {
                   6733:         $maxtries = 10;
                   6734:     }
                   6735: 
                   6736:     if (($cdom eq '') || ($cnum eq '')) {
                   6737:         if ($env{'request.course.id'}) {
                   6738:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6739:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6740:         }
                   6741:         if (($cdom eq '') || ($cnum eq '')) {
                   6742:             return ('','ok','call to get suffix not in course context');
                   6743:         }
                   6744:     }
                   6745: 
                   6746: # construct locking item
                   6747:     my $lockhash = {
                   6748:                       $prefix."\0".'locked_'.$keyid => $who,
                   6749:                    };
                   6750:     my $tries = 0;
                   6751: 
                   6752: # attempt to get lock on nohist_$namespace file
                   6753:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6754:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   6755:         $tries ++;
                   6756:         sleep 1;
                   6757:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6758:     }
                   6759: 
                   6760: # attempt to get unique identifier, based on current timestamp
                   6761:     if ($gotlock eq 'ok') {
                   6762:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   6763:         my $id = time;
                   6764:         $newid = $id;
1.1172.2.56  raeburn  6765:         if ($idtype eq 'addcode') {
                   6766:             $newid .= &sixnum_code();
                   6767:         }
1.1172.2.13  raeburn  6768:         my $idtries = 0;
                   6769:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   6770:             if ($idtype eq 'concat') {
                   6771:                 $newid = $id.$idtries;
1.1172.2.56  raeburn  6772:             } elsif ($idtype eq 'addcode') {
                   6773:                 $newid = $newid.&sixnum_code();
1.1172.2.13  raeburn  6774:             } else {
                   6775:                 $newid ++;
                   6776:             }
                   6777:             $idtries ++;
                   6778:         }
                   6779:         if (!exists($inuse{$prefix."\0".$newid})) {
                   6780:             my %new_item =  (
                   6781:                               $prefix."\0".$newid => $who,
                   6782:                             );
                   6783:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   6784:                                                  $cdom,$cnum);
                   6785:             if ($putresult ne 'ok') {
                   6786:                 undef($newid);
                   6787:                 $error = 'error saving new item: '.$putresult;
                   6788:             }
                   6789:         } else {
1.1172.2.56  raeburn  6790:              undef($newid);
1.1172.2.13  raeburn  6791:              $error = ('error: no unique suffix available for the new item ');
                   6792:         }
                   6793: #  remove lock
                   6794:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   6795:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   6796:     } else {
                   6797:         $error = "error: could not obtain lockfile\n";
                   6798:         $dellock = 'ok';
1.1172.2.58  raeburn  6799:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   6800:             $dellock = 'nolock';
                   6801:         }
1.1172.2.13  raeburn  6802:     }
                   6803:     return ($newid,$dellock,$error);
                   6804: }
                   6805: 
1.1172.2.56  raeburn  6806: sub sixnum_code {
                   6807:     my $code;
                   6808:     for (0..6) {
                   6809:         $code .= int( rand(9) );
                   6810:     }
                   6811:     return $code;
                   6812: }
                   6813: 
1.765     albertel 6814: # -------------------------------------------------- portfolio access checking
                   6815: 
                   6816: sub portfolio_access {
1.1172.2.77  raeburn  6817:     my ($requrl,$clientip) = @_;
1.765     albertel 6818:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77  raeburn  6819:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  6820:     if ($result) {
                   6821:         my %setters;
                   6822:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6823:             my ($startblock,$endblock) =
                   6824:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   6825:             if ($startblock && $endblock) {
                   6826:                 return 'B';
                   6827:             }
                   6828:         } else {
                   6829:             my ($startblock,$endblock) =
                   6830:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   6831:             if ($startblock && $endblock) {
                   6832:                 return 'B';
                   6833:             }
                   6834:         }
                   6835:     }
1.765     albertel 6836:     if ($result eq 'ok') {
1.766     albertel 6837:        return 'F';
1.765     albertel 6838:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 6839:        return 'A';
1.765     albertel 6840:     }
1.766     albertel 6841:     return '';
1.765     albertel 6842: }
                   6843: 
                   6844: sub get_portfolio_access {
1.1172.2.77  raeburn  6845:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 6846: 
                   6847:     if (!ref($access_hash)) {
                   6848: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   6849: 	my %access_controls = &get_access_controls($current_perms,$group,
                   6850: 						   $file_name);
                   6851: 	$access_hash = $access_controls{$file_name};
                   6852:     }
                   6853: 
1.1172.2.77  raeburn  6854:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 6855:     my $now = time;
                   6856:     if (ref($access_hash) eq 'HASH') {
                   6857:         foreach my $key (keys(%{$access_hash})) {
                   6858:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6859:             if ($start > $now) {
                   6860:                 next;
                   6861:             }
                   6862:             if ($end && $end<$now) {
                   6863:                 next;
                   6864:             }
                   6865:             if ($scope eq 'public') {
                   6866:                 $public = $key;
                   6867:                 last;
                   6868:             } elsif ($scope eq 'guest') {
                   6869:                 $guest = $key;
                   6870:             } elsif ($scope eq 'domains') {
                   6871:                 push(@domains,$key);
                   6872:             } elsif ($scope eq 'users') {
                   6873:                 push(@users,$key);
                   6874:             } elsif ($scope eq 'course') {
                   6875:                 push(@courses,$key);
                   6876:             } elsif ($scope eq 'group') {
                   6877:                 push(@groups,$key);
1.1172.2.77  raeburn  6878:             } elsif ($scope eq 'ip') {
                   6879:                 push(@ips,$key);
1.765     albertel 6880:             }
                   6881:         }
                   6882:         if ($public) {
                   6883:             return 'ok';
1.1172.2.77  raeburn  6884:         } elsif (@ips > 0) {
                   6885:             my $allowed;
                   6886:             foreach my $ipkey (@ips) {
                   6887:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   6888:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   6889:                         $allowed = 1;
                   6890:                         last;
                   6891:                     }
                   6892:                 }
                   6893:             }
                   6894:             if ($allowed) {
                   6895:                 return 'ok';
                   6896:             }
1.765     albertel 6897:         }
                   6898:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6899:             if ($guest) {
                   6900:                 return $guest;
                   6901:             }
                   6902:         } else {
                   6903:             if (@domains > 0) {
                   6904:                 foreach my $domkey (@domains) {
                   6905:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   6906:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   6907:                             return 'ok';
                   6908:                         }
                   6909:                     }
                   6910:                 }
                   6911:             }
                   6912:             if (@users > 0) {
                   6913:                 foreach my $userkey (@users) {
1.865     raeburn  6914:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   6915:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   6916:                             if (ref($item) eq 'HASH') {
                   6917:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   6918:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   6919:                                     return 'ok';
                   6920:                                 }
                   6921:                             }
                   6922:                         }
                   6923:                     } 
1.765     albertel 6924:                 }
                   6925:             }
                   6926:             my %roleshash;
                   6927:             my @courses_and_groups = @courses;
                   6928:             push(@courses_and_groups,@groups); 
                   6929:             if (@courses_and_groups > 0) {
                   6930:                 my (%allgroups,%allroles); 
                   6931:                 my ($start,$end,$role,$sec,$group);
                   6932:                 foreach my $envkey (%env) {
1.1060    raeburn  6933:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6934:                         my $cid = $2.'_'.$3; 
                   6935:                         if ($1 eq 'gr') {
                   6936:                             $group = $4;
                   6937:                             $allgroups{$cid}{$group} = $env{$envkey};
                   6938:                         } else {
                   6939:                             if ($4 eq '') {
                   6940:                                 $sec = 'none';
                   6941:                             } else {
                   6942:                                 $sec = $4;
                   6943:                             }
                   6944:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6945:                         }
1.811     albertel 6946:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6947:                         my $cid = $2.'_'.$3;
                   6948:                         if ($4 eq '') {
                   6949:                             $sec = 'none';
                   6950:                         } else {
                   6951:                             $sec = $4;
                   6952:                         }
                   6953:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6954:                     }
                   6955:                 }
                   6956:                 if (keys(%allroles) == 0) {
                   6957:                     return;
                   6958:                 }
                   6959:                 foreach my $key (@courses_and_groups) {
                   6960:                     my %content = %{$$access_hash{$key}};
                   6961:                     my $cnum = $content{'number'};
                   6962:                     my $cdom = $content{'domain'};
                   6963:                     my $cid = $cdom.'_'.$cnum;
                   6964:                     if (!exists($allroles{$cid})) {
                   6965:                         next;
                   6966:                     }    
                   6967:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   6968:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   6969:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   6970:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   6971:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   6972:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   6973:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   6974:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   6975:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   6976:                                         if (grep/^all$/,@sections) {
                   6977:                                             return 'ok';
                   6978:                                         } else {
                   6979:                                             if (grep/^$sec$/,@sections) {
                   6980:                                                 return 'ok';
                   6981:                                             }
                   6982:                                         }
                   6983:                                     }
                   6984:                                 }
                   6985:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   6986:                                     if (grep/^none$/,@groups) {
                   6987:                                         return 'ok';
                   6988:                                     }
                   6989:                                 } else {
                   6990:                                     if (grep/^all$/,@groups) {
                   6991:                                         return 'ok';
                   6992:                                     } 
                   6993:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   6994:                                         if (grep/^$group$/,@groups) {
                   6995:                                             return 'ok';
                   6996:                                         }
                   6997:                                     }
                   6998:                                 } 
                   6999:                             }
                   7000:                         }
                   7001:                     }
                   7002:                 }
                   7003:             }
                   7004:             if ($guest) {
                   7005:                 return $guest;
                   7006:             }
                   7007:         }
                   7008:     }
                   7009:     return;
                   7010: }
                   7011: 
                   7012: sub course_group_datechecker {
                   7013:     my ($dates,$now,$status) = @_;
                   7014:     my ($start,$end) = split(/\./,$dates);
                   7015:     if (!$start && !$end) {
                   7016:         return 'ok';
                   7017:     }
                   7018:     if (grep/^active$/,@{$status}) {
                   7019:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7020:             return 'ok';
                   7021:         }
                   7022:     }
                   7023:     if (grep/^previous$/,@{$status}) {
                   7024:         if ($end > $now ) {
                   7025:             return 'ok';
                   7026:         }
                   7027:     }
                   7028:     if (grep/^future$/,@{$status}) {
                   7029:         if ($start > $now) {
                   7030:             return 'ok';
                   7031:         }
                   7032:     }
                   7033:     return; 
                   7034: }
                   7035: 
                   7036: sub parse_portfolio_url {
                   7037:     my ($url) = @_;
                   7038: 
                   7039:     my ($type,$udom,$unum,$group,$file_name);
                   7040:     
1.823     albertel 7041:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7042: 	$type = 1;
                   7043:         $udom = $1;
                   7044:         $unum = $2;
                   7045:         $file_name = $3;
1.823     albertel 7046:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7047: 	$type = 2;
                   7048:         $udom = $1;
                   7049:         $unum = $2;
                   7050:         $group = $3;
                   7051:         $file_name = $3.'/'.$4;
                   7052:     }
                   7053:     if (wantarray) {
                   7054: 	return ($type,$udom,$unum,$file_name,$group);
                   7055:     }
                   7056:     return $type;
                   7057: }
                   7058: 
                   7059: sub is_portfolio_url {
                   7060:     my ($url) = @_;
                   7061:     return scalar(&parse_portfolio_url($url));
                   7062: }
                   7063: 
1.798     raeburn  7064: sub is_portfolio_file {
                   7065:     my ($file) = @_;
1.820     raeburn  7066:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7067:         return 1;
                   7068:     }
                   7069:     return;
                   7070: }
                   7071: 
1.976     raeburn  7072: sub usertools_access {
1.1084    raeburn  7073:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7074:     my ($access,%tools);
                   7075:     if ($context eq '') {
                   7076:         $context = 'tools';
                   7077:     }
                   7078:     if ($context eq 'requestcourses') {
                   7079:         %tools = (
                   7080:                       official   => 1,
                   7081:                       unofficial => 1,
1.1006    raeburn  7082:                       community  => 1,
1.1172.2.37  raeburn  7083:                       textbook   => 1,
1.985     raeburn  7084:                  );
1.1172.2.9  raeburn  7085:     } elsif ($context eq 'requestauthor') {
                   7086:         %tools = (
                   7087:                       requestauthor => 1,
                   7088:                  );
1.985     raeburn  7089:     } else {
                   7090:         %tools = (
                   7091:                       aboutme   => 1,
                   7092:                       blog      => 1,
1.1172.2.6  raeburn  7093:                       webdav    => 1,
1.985     raeburn  7094:                       portfolio => 1,
                   7095:                  );
                   7096:     }
1.976     raeburn  7097:     return if (!defined($tools{$tool}));
                   7098: 
1.1172.2.35  raeburn  7099:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7100:         $udom = $env{'user.domain'};
                   7101:         $uname = $env{'user.name'};
                   7102:     }
                   7103: 
1.978     raeburn  7104:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7105:         if ($action ne 'reload') {
1.985     raeburn  7106:             if ($context eq 'requestcourses') {
                   7107:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  7108:             } elsif ($context eq 'requestauthor') {
                   7109:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7110:             } else {
                   7111:                 return $env{'environment.availabletools.'.$tool};
                   7112:             }
                   7113:         }
1.976     raeburn  7114:     }
                   7115: 
1.1172.2.9  raeburn  7116:     my ($toolstatus,$inststatus,$envkey);
                   7117:     if ($context eq 'requestauthor') {
                   7118:         $envkey = $context;
                   7119:     } else {
                   7120:         $envkey = $context.'.'.$tool;
                   7121:     }
1.976     raeburn  7122: 
1.985     raeburn  7123:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7124:          ($action ne 'reload')) {
1.1172.2.9  raeburn  7125:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7126:         $inststatus = $env{'environment.inststatus'};
                   7127:     } else {
1.1084    raeburn  7128:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  7129:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7130:             $inststatus = $userenvref->{'inststatus'};
                   7131:         } else {
1.1172.2.9  raeburn  7132:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7133:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7134:             $inststatus = $userenv{'inststatus'};
                   7135:         }
1.976     raeburn  7136:     }
                   7137: 
                   7138:     if ($toolstatus ne '') {
                   7139:         if ($toolstatus) {
                   7140:             $access = 1;
                   7141:         } else {
                   7142:             $access = 0;
                   7143:         }
                   7144:         return $access;
                   7145:     }
                   7146: 
1.1084    raeburn  7147:     my ($is_adv,%domdef);
                   7148:     if (ref($is_advref) eq 'HASH') {
                   7149:         $is_adv = $is_advref->{'is_adv'};
                   7150:     } else {
                   7151:         $is_adv = &is_advanced_user($udom,$uname);
                   7152:     }
                   7153:     if (ref($domdefref) eq 'HASH') {
                   7154:         %domdef = %{$domdefref};
                   7155:     } else {
                   7156:         %domdef = &get_domain_defaults($udom);
                   7157:     }
1.976     raeburn  7158:     if (ref($domdef{$tool}) eq 'HASH') {
                   7159:         if ($is_adv) {
                   7160:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7161:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7162:                     $access = 1;
                   7163:                 } else {
                   7164:                     $access = 0;
                   7165:                 }
                   7166:                 return $access;
                   7167:             }
                   7168:         }
                   7169:         if ($inststatus ne '') {
                   7170:             my ($hasaccess,$hasnoaccess);
                   7171:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7172:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7173:                     if ($domdef{$tool}{$affiliation}) {
                   7174:                         $hasaccess = 1;
                   7175:                     } else {
                   7176:                         $hasnoaccess = 1;
                   7177:                     }
                   7178:                 }
                   7179:             }
                   7180:             if ($hasaccess || $hasnoaccess) {
                   7181:                 if ($hasaccess) {
                   7182:                     $access = 1;
                   7183:                 } elsif ($hasnoaccess) {
                   7184:                     $access = 0; 
                   7185:                 }
                   7186:                 return $access;
                   7187:             }
                   7188:         } else {
                   7189:             if ($domdef{$tool}{'default'} ne '') {
                   7190:                 if ($domdef{$tool}{'default'}) {
                   7191:                     $access = 1;
                   7192:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7193:                     $access = 0;
                   7194:                 }
                   7195:                 return $access;
                   7196:             }
                   7197:         }
                   7198:     } else {
1.1172.2.6  raeburn  7199:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7200:             $access = 1;
                   7201:         } else {
                   7202:             $access = 0;
                   7203:         }
1.976     raeburn  7204:         return $access;
                   7205:     }
                   7206: }
                   7207: 
1.1050    raeburn  7208: sub is_course_owner {
                   7209:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7210:     if (($udom eq '') || ($uname eq '')) {
                   7211:         $udom = $env{'user.domain'};
                   7212:         $uname = $env{'user.name'};
                   7213:     }
                   7214:     unless (($udom eq '') || ($uname eq '')) {
                   7215:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7216:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7217:                 return 1;
                   7218:             } else {
                   7219:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7220:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7221:                     return 1;
                   7222:                 }
                   7223:             }
                   7224:         }
                   7225:     }
                   7226:     return;
                   7227: }
                   7228: 
1.976     raeburn  7229: sub is_advanced_user {
                   7230:     my ($udom,$uname) = @_;
1.1085    raeburn  7231:     if ($udom ne '' && $uname ne '') {
                   7232:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7233:             if (wantarray) {
                   7234:                 return ($env{'user.adv'},$env{'user.author'});
                   7235:             } else {
                   7236:                 return $env{'user.adv'};
                   7237:             }
1.1085    raeburn  7238:         }
                   7239:     }
1.976     raeburn  7240:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7241:     my %allroles;
1.1128    raeburn  7242:     my ($is_adv,$is_author);
1.976     raeburn  7243:     foreach my $role (keys(%roleshash)) {
                   7244:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7245:         my $area = '/'.$tdomain.'/'.$trest;
                   7246:         if ($sec ne '') {
                   7247:             $area .= '/'.$sec;
                   7248:         }
                   7249:         if (($area ne '') && ($trole ne '')) {
                   7250:             my $spec=$trole.'.'.$area;
                   7251:             if ($trole =~ /^cr\//) {
                   7252:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7253:             } elsif ($trole ne 'gr') {
                   7254:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7255:             }
1.1128    raeburn  7256:             if ($trole eq 'au') {
                   7257:                 $is_author = 1;
                   7258:             }
1.976     raeburn  7259:         }
                   7260:     }
                   7261:     foreach my $role (keys(%allroles)) {
                   7262:         last if ($is_adv);
                   7263:         foreach my $item (split(/:/,$allroles{$role})) {
                   7264:             if ($item ne '') {
                   7265:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7266:                 if ($privilege eq 'adv') {
                   7267:                     $is_adv = 1;
                   7268:                     last;
                   7269:                 }
                   7270:             }
                   7271:         }
                   7272:     }
1.1128    raeburn  7273:     if (wantarray) {
                   7274:         return ($is_adv,$is_author);
                   7275:     }
1.976     raeburn  7276:     return $is_adv;
                   7277: }
1.798     raeburn  7278: 
1.1035    raeburn  7279: sub check_can_request {
1.1036    raeburn  7280:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  7281:     my $canreq = 0;
                   7282:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7283:     my @options = ('approval','validate','autolimit');
                   7284:     my $optregex = join('|',@options);
                   7285:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7286:         foreach my $type (@{$types}) {
                   7287:             if (&usertools_access($env{'user.name'},
                   7288:                                   $env{'user.domain'},
                   7289:                                   $type,undef,'requestcourses')) {
                   7290:                 $canreq ++;
1.1036    raeburn  7291:                 if (ref($request_domains) eq 'HASH') {
                   7292:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   7293:                 }
1.1035    raeburn  7294:                 if ($dom eq $env{'user.domain'}) {
                   7295:                     $can_request->{$type} = 1;
                   7296:                 }
                   7297:             }
                   7298:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   7299:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7300:                 if (@curr > 0) {
1.1036    raeburn  7301:                     foreach my $item (@curr) {
                   7302:                         if (ref($request_domains) eq 'HASH') {
                   7303:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7304:                             if ($otherdom ne '') {
                   7305:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7306:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7307:                                         push(@{$request_domains->{$type}},$otherdom);
                   7308:                                     }
                   7309:                                 } else {
                   7310:                                     push(@{$request_domains->{$type}},$otherdom);
                   7311:                                 }
                   7312:                             }
                   7313:                         }
                   7314:                     }
                   7315:                     unless($dom eq $env{'user.domain'}) {
                   7316:                         $canreq ++;
1.1035    raeburn  7317:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7318:                             $can_request->{$type} = 1;
                   7319:                         }
                   7320:                     }
                   7321:                 }
                   7322:             }
                   7323:         }
                   7324:     }
                   7325:     return $canreq;
                   7326: }
                   7327: 
1.341     www      7328: # ---------------------------------------------- Custom access rule evaluation
                   7329: 
                   7330: sub customaccess {
                   7331:     my ($priv,$uri)=@_;
1.807     albertel 7332:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7333:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7334:     $udom = &LONCAPA::clean_domain($udom);
                   7335:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7336:     my $access=0;
1.800     albertel 7337:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7338: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7339: 	if ($type eq 'user') {
                   7340: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7341: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7342: 		if ($tdom) {
                   7343: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7344: 		}
1.896     albertel 7345: 		if ($tuname) {
                   7346: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7347: 		}
                   7348: 		$access=($effect eq 'allow');
                   7349: 		last;
                   7350: 	    }
                   7351: 	} else {
                   7352: 	    if ($role) {
                   7353: 		if ($role ne $urole) { next; }
                   7354: 	    }
                   7355: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7356: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7357: 		if ($tdom) {
                   7358: 		    if ($tdom ne $udom) { next; }
                   7359: 		}
                   7360: 		if ($tcrs) {
                   7361: 		    if ($tcrs ne $ucrs) { next; }
                   7362: 		}
                   7363: 		if ($tsec) {
                   7364: 		    if ($tsec ne $usec) { next; }
                   7365: 		}
                   7366: 		$access=($effect eq 'allow');
                   7367: 		last;
                   7368: 	    }
                   7369: 	    if ($realm eq '' && $role eq '') {
                   7370: 		$access=($effect eq 'allow');
                   7371: 	    }
1.402     bowersj2 7372: 	}
1.341     www      7373:     }
                   7374:     return $access;
                   7375: }
                   7376: 
1.103     harris41 7377: # ------------------------------------------------- Check for a user privilege
1.12      www      7378: 
                   7379: sub allowed {
1.1172.2.65  raeburn  7380:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 7381:     my $ver_orguri=$uri;
1.439     www      7382:     $uri=&deversion($uri);
1.152     www      7383:     my $orguri=$uri;
1.52      www      7384:     $uri=&declutter($uri);
1.809     raeburn  7385: 
1.810     raeburn  7386:     if ($priv eq 'evb') {
                   7387: # Evade communication block restrictions for specified role in a course
                   7388:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   7389:             return $1;
                   7390:         } else {
                   7391:             return;
                   7392:         }
                   7393:     }
                   7394: 
1.620     albertel 7395:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      7396: # Free bre access to adm and meta resources
1.775     albertel 7397:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 7398: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   7399: 	&& ($priv eq 'bre')) {
1.14      www      7400: 	return 'F';
1.159     www      7401:     }
                   7402: 
1.545     banghart 7403: # Free bre access to user's own portfolio contents
1.714     raeburn  7404:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  7405:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  7406: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  7407:         my %setters;
                   7408:         my ($startblock,$endblock) = 
                   7409:             &Apache::loncommon::blockcheck(\%setters,'port');
                   7410:         if ($startblock && $endblock) {
                   7411:             return 'B';
                   7412:         } else {
                   7413:             return 'F';
                   7414:         }
1.545     banghart 7415:     }
                   7416: 
1.762     raeburn  7417: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  7418:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   7419:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   7420:         if (exists($env{'request.course.id'})) {
                   7421:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7422:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7423:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   7424:                 my $courseprivid=$env{'request.course.id'};
                   7425:                 $courseprivid=~s/\_/\//;
                   7426:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   7427:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   7428:                     return $1; 
1.762     raeburn  7429:                 } else {
                   7430:                     if ($env{'request.course.sec'}) {
                   7431:                         $courseprivid.='/'.$env{'request.course.sec'};
                   7432:                     }
                   7433:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   7434:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   7435:                         return $2;
                   7436:                     }
1.714     raeburn  7437:                 }
                   7438:             }
                   7439:         }
                   7440:     }
                   7441: 
1.159     www      7442: # Free bre to public access
                   7443: 
                   7444:     if ($priv eq 'bre') {
1.238     www      7445:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 7446: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      7447:            return 'F'; 
                   7448:         }
1.238     www      7449:         if ($copyright eq 'priv') {
                   7450:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7451: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      7452: 		return '';
                   7453:             }
                   7454:         }
                   7455:         if ($copyright eq 'domain') {
                   7456:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7457: 	    unless (($env{'user.domain'} eq $1) ||
                   7458:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7459: 		return '';
                   7460:             }
1.262     matthew  7461:         }
1.620     albertel 7462:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7463:             # Library role, so allow browsing of resources in this domain.
                   7464:             return 'F';
1.238     www      7465:         }
1.341     www      7466:         if ($copyright eq 'custom') {
                   7467: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7468:         }
1.14      www      7469:     }
1.264     matthew  7470:     # Domain coordinator is trying to create a course
1.620     albertel 7471:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7472:         # uri is the requested domain in this case.
                   7473:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7474:         # a role of dc for the domain in question.
1.620     albertel 7475:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7476:     }
1.29      www      7477: 
1.52      www      7478:     my $thisallowed='';
                   7479:     my $statecond=0;
                   7480:     my $courseprivid='';
                   7481: 
1.1039    raeburn  7482:     my $ownaccess;
1.1043    raeburn  7483:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7484:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7485:         if ($uri eq '') {
                   7486:             $ownaccess = 1;
                   7487:         } else {
                   7488:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7489:                 my $udom = $env{'user.domain'};
                   7490:                 my $uname = $env{'user.name'};
                   7491:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7492:                     $ownaccess = 1;
1.1040    raeburn  7493:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7494:                     unless ($uri =~ m{\.\./}) {
                   7495:                         $ownaccess = 1;
                   7496:                     }
                   7497:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   7498:                     my $now = time;
                   7499:                     if ($uri =~ m{^([^/]+)/?$}) {
                   7500:                         my $adom = $1;
                   7501:                         foreach my $key (keys(%env)) {
1.1042    raeburn  7502:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  7503:                                 my ($start,$end) = split('.',$env{$key});
                   7504:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7505:                                     $ownaccess = 1;
                   7506:                                     last;
                   7507:                                 }
                   7508:                             }
                   7509:                         }
                   7510:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   7511:                         my $adom = $1;
                   7512:                         my $aname = $2;
1.1042    raeburn  7513:                         foreach my $role ('ca','aa') { 
                   7514:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   7515:                                 my ($start,$end) =
                   7516:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   7517:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7518:                                     $ownaccess = 1;
                   7519:                                     last;
                   7520:                                 }
1.1039    raeburn  7521:                             }
                   7522:                         }
                   7523:                     }
                   7524:                 }
                   7525:             }
                   7526:         }
                   7527:     }
                   7528: 
1.52      www      7529: # Course
                   7530: 
1.620     albertel 7531:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7532:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7533:             $thisallowed.=$1;
                   7534:         }
1.52      www      7535:     }
1.29      www      7536: 
1.52      www      7537: # Domain
                   7538: 
1.620     albertel 7539:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 7540:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7541:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7542:             $thisallowed.=$1;
                   7543:         }
1.12      www      7544:     }
1.52      www      7545: 
1.1141    raeburn  7546: # User who is not author or co-author might still be able to edit
                   7547: # resource of an author in the domain (e.g., if Domain Coordinator).
                   7548:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   7549:         (&allowed('mdc',$env{'request.course.id'}))) {
                   7550:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   7551:             $thisallowed.=$1;
                   7552:         }
                   7553:     }
                   7554: 
1.52      www      7555: # Course: uri itself is a course
1.66      www      7556:     my $courseuri=$uri;
                   7557:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      7558:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      7559: 
1.620     albertel 7560:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 7561:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7562:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7563:             $thisallowed.=$1;
                   7564:         }
1.12      www      7565:     }
1.29      www      7566: 
1.665     albertel 7567: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 7568: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 7569:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 7570: 	$thisallowed='';
1.671     raeburn  7571:         my ($match)=&is_on_map($uri);
                   7572:         if ($match) {
                   7573:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   7574:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65  raeburn  7575:                 my $value = $1;
                   7576:                 if ($noblockcheck) {
                   7577:                     $thisallowed.=$value;
1.1162    raeburn  7578:                 } else {
1.1172.2.65  raeburn  7579:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7580:                     if (@blockers > 0) {
                   7581:                         $thisallowed = 'B';
                   7582:                     } else {
                   7583:                         $thisallowed.=$value;
                   7584:                     }
1.1162    raeburn  7585:                 }
1.671     raeburn  7586:             }
                   7587:         } else {
1.705     albertel 7588:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  7589:             if ($refuri) {
                   7590:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  7591:                     $thisallowed='F';
1.671     raeburn  7592:                 } else {
                   7593:                     $refuri=&declutter($refuri);
                   7594:                     my ($match) = &is_on_map($refuri);
                   7595:                     if ($match) {
1.1172.2.65  raeburn  7596:                         if ($noblockcheck) {
1.1162    raeburn  7597:                             $thisallowed='F';
1.1172.2.65  raeburn  7598:                         } else {
                   7599:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7600:                             if (@blockers > 0) {
                   7601:                                 $thisallowed = 'B';
                   7602:                             } else {
                   7603:                                 $thisallowed='F';
                   7604:                             }
1.1162    raeburn  7605:                         }
1.671     raeburn  7606:                     }
1.669     raeburn  7607:                 }
1.671     raeburn  7608:             }
                   7609:         }
1.314     www      7610:     }
1.492     albertel 7611: 
1.766     albertel 7612:     if ($priv eq 'bre'
                   7613: 	&& $thisallowed ne 'F' 
                   7614: 	&& $thisallowed ne '2'
                   7615: 	&& &is_portfolio_url($uri)) {
1.1172.2.77  raeburn  7616: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 7617:     }
                   7618:     
1.52      www      7619: # Full access at system, domain or course-wide level? Exit.
1.29      www      7620:     if ($thisallowed=~/F/) {
                   7621: 	return 'F';
                   7622:     }
                   7623: 
1.52      www      7624: # If this is generating or modifying users, exit with special codes
1.29      www      7625: 
1.643     www      7626:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   7627: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 7628: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      7629: # no author name given, so this just checks on the general right to make a co-author in this domain
                   7630: 	    unless ($auname) { return $thisallowed; }
                   7631: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 7632: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   7633: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   7634: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   7635: 	}
1.52      www      7636: 	return $thisallowed;
                   7637:     }
                   7638: #
1.103     harris41 7639: # Gathered so far: system, domain and course wide privileges
1.52      www      7640: #
                   7641: # Course: See if uri or referer is an individual resource that is part of 
                   7642: # the course
                   7643: 
1.620     albertel 7644:     if ($env{'request.course.id'}) {
1.232     www      7645: 
1.620     albertel 7646:        $courseprivid=$env{'request.course.id'};
                   7647:        if ($env{'request.course.sec'}) {
                   7648:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      7649:        }
                   7650:        $courseprivid=~s/\_/\//;
                   7651:        my $checkreferer=1;
1.232     www      7652:        my ($match,$cond)=&is_on_map($uri);
                   7653:        if ($match) {
                   7654:            $statecond=$cond;
1.620     albertel 7655:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7656:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7657:                my $value = $1;
                   7658:                if ($priv eq 'bre') {
1.1172.2.65  raeburn  7659:                    if ($noblockcheck) {
1.1162    raeburn  7660:                        $thisallowed.=$value;
1.1172.2.65  raeburn  7661:                    } else {
                   7662:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7663:                        if (@blockers > 0) {
                   7664:                            $thisallowed = 'B';
                   7665:                        } else {
                   7666:                            $thisallowed.=$value;
                   7667:                        }
1.1162    raeburn  7668:                    }
                   7669:                } else {
                   7670:                    $thisallowed.=$value;
                   7671:                }
1.52      www      7672:                $checkreferer=0;
                   7673:            }
1.29      www      7674:        }
1.83      www      7675:        
1.148     www      7676:        if ($checkreferer) {
1.620     albertel 7677: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      7678:             unless ($refuri) {
1.800     albertel 7679:                 foreach my $key (keys(%env)) {
                   7680: 		    if ($key=~/^httpref\..*\*/) {
                   7681: 			my $pattern=$key;
1.156     www      7682:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      7683:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   7684:                         $pattern=~s/\//\\\//g;
1.152     www      7685:                         if ($orguri=~/$pattern/) {
1.800     albertel 7686: 			    $refuri=$env{$key};
1.148     www      7687:                         }
                   7688:                     }
1.191     harris41 7689:                 }
1.148     www      7690:             }
1.232     www      7691: 
1.148     www      7692:          if ($refuri) { 
1.152     www      7693: 	  $refuri=&declutter($refuri);
1.232     www      7694:           my ($match,$cond)=&is_on_map($refuri);
                   7695:             if ($match) {
                   7696:               my $refstatecond=$cond;
1.620     albertel 7697:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7698:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7699:                   my $value = $1;
                   7700:                   if ($priv eq 'bre') {
1.1172.2.65  raeburn  7701:                       if ($noblockcheck) {
1.1162    raeburn  7702:                           $thisallowed.=$value;
1.1172.2.65  raeburn  7703:                       } else {
                   7704:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7705:                           if (@blockers > 0) {
                   7706:                               $thisallowed = 'B';
                   7707:                           } else {
                   7708:                               $thisallowed.=$value;
                   7709:                           }
1.1162    raeburn  7710:                       }
                   7711:                   } else {
                   7712:                       $thisallowed.=$value;
                   7713:                   }
1.53      www      7714:                   $uri=$refuri;
                   7715:                   $statecond=$refstatecond;
1.52      www      7716:               }
                   7717:           }
1.148     www      7718:         }
1.29      www      7719:        }
1.52      www      7720:    }
1.29      www      7721: 
1.52      www      7722: #
1.103     harris41 7723: # Gathered now: all privileges that could apply, and condition number
1.52      www      7724: # 
                   7725: #
                   7726: # Full or no access?
                   7727: #
1.29      www      7728: 
1.52      www      7729:     if ($thisallowed=~/F/) {
                   7730: 	return 'F';
                   7731:     }
1.29      www      7732: 
1.52      www      7733:     unless ($thisallowed) {
                   7734:         return '';
                   7735:     }
1.29      www      7736: 
1.52      www      7737: # Restrictions exist, deal with them
                   7738: #
                   7739: #   C:according to course preferences
                   7740: #   R:according to resource settings
                   7741: #   L:unless locked
                   7742: #   X:according to user session state
                   7743: #
                   7744: 
                   7745: # Possibly locked functionality, check all courses
1.54      www      7746: # Locks might take effect only after 10 minutes cache expiration for other
                   7747: # courses, and 2 minutes for current course
1.52      www      7748: 
                   7749:     my $envkey;
                   7750:     if ($thisallowed=~/L/) {
1.1000    raeburn  7751:         foreach $envkey (keys(%env)) {
1.54      www      7752:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   7753:                my $courseid=$2;
                   7754:                my $roleid=$1.'.'.$2;
1.92      www      7755:                $courseid=~s/^\///;
1.54      www      7756:                my $expiretime=600;
1.620     albertel 7757:                if ($env{'request.role'} eq $roleid) {
1.54      www      7758: 		  $expiretime=120;
                   7759:                }
                   7760: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   7761:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 7762:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 7763: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      7764:                }
1.620     albertel 7765:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7766:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   7767: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   7768:                        &log($env{'user.domain'},$env{'user.name'},
                   7769:                             $env{'user.home'},
1.57      www      7770:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      7771:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7772:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7773: 		       return '';
                   7774:                    }
                   7775:                }
1.620     albertel 7776:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7777:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   7778: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   7779:                        &log($env{'user.domain'},$env{'user.name'},
                   7780:                             $env{'user.home'},
1.57      www      7781:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      7782:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7783:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7784: 		       return '';
                   7785:                    }
                   7786:                }
                   7787: 	   }
1.29      www      7788:        }
1.52      www      7789:     }
                   7790:    
                   7791: #
                   7792: # Rest of the restrictions depend on selected course
                   7793: #
                   7794: 
1.620     albertel 7795:     unless ($env{'request.course.id'}) {
1.766     albertel 7796: 	if ($thisallowed eq 'A') {
                   7797: 	    return 'A';
1.814     raeburn  7798:         } elsif ($thisallowed eq 'B') {
                   7799:             return 'B';
1.766     albertel 7800: 	} else {
                   7801: 	    return '1';
                   7802: 	}
1.52      www      7803:     }
1.29      www      7804: 
1.52      www      7805: #
                   7806: # Now user is definitely in a course
                   7807: #
1.53      www      7808: 
                   7809: 
                   7810: # Course preferences
                   7811: 
                   7812:    if ($thisallowed=~/C/) {
1.620     albertel 7813:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   7814:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   7815:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 7816: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  7817: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7818: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7819: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   7820: 			$env{'request.course.id'});
                   7821: 	   }
1.237     www      7822:            return '';
                   7823:        }
                   7824: 
1.620     albertel 7825:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 7826: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  7827: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7828: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   7829: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   7830: 			$env{'request.course.id'});
                   7831: 	   }
1.54      www      7832:            return '';
                   7833:        }
1.53      www      7834:    }
                   7835: 
                   7836: # Resource preferences
                   7837: 
                   7838:    if ($thisallowed=~/R/) {
1.620     albertel 7839:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 7840:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  7841: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7842: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7843: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   7844: 	   }
                   7845: 	   return '';
1.54      www      7846:        }
1.53      www      7847:    }
1.30      www      7848: 
1.246     www      7849: # Restricted by state or randomout?
1.30      www      7850: 
1.52      www      7851:    if ($thisallowed=~/X/) {
1.620     albertel 7852:       if ($env{'acc.randomout'}) {
1.579     albertel 7853: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 7854:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      7855:             return ''; 
                   7856:          }
1.247     www      7857:       }
                   7858:       if (&condval($statecond)) {
1.52      www      7859: 	 return '2';
                   7860:       } else {
                   7861:          return '';
                   7862:       }
                   7863:    }
1.30      www      7864: 
1.766     albertel 7865:     if ($thisallowed eq 'A') {
                   7866: 	return 'A';
1.814     raeburn  7867:     } elsif ($thisallowed eq 'B') {
                   7868:         return 'B';
1.766     albertel 7869:     }
1.52      www      7870:    return 'F';
1.232     www      7871: }
1.1162    raeburn  7872: 
1.1172.2.13  raeburn  7873: # ------------------------------------------- Check construction space access
                   7874: 
                   7875: sub constructaccess {
                   7876:     my ($url,$setpriv)=@_;
                   7877: 
                   7878: # We do not allow editing of previous versions of files
                   7879:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   7880: 
                   7881: # Get username and domain from URL
                   7882:     my ($ownername,$ownerdomain,$ownerhome);
                   7883: 
                   7884:     ($ownerdomain,$ownername) =
1.1172.2.83  raeburn  7885:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13  raeburn  7886: 
                   7887: # The URL does not really point to any authorspace, forget it
                   7888:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   7889: 
                   7890: # Now we need to see if the user has access to the authorspace of
                   7891: # $ownername at $ownerdomain
                   7892: 
                   7893:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   7894: # Real author for this?
                   7895:        $ownerhome = $env{'user.home'};
                   7896:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   7897:           return ($ownername,$ownerdomain,$ownerhome);
                   7898:        }
                   7899:     } else {
                   7900: # Co-author for this?
                   7901:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   7902:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   7903:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   7904:             return ($ownername,$ownerdomain,$ownerhome);
                   7905:         }
                   7906:     }
                   7907: 
                   7908: # We don't have any access right now. If we are not possibly going to do anything about this,
                   7909: # we might as well leave
                   7910:    unless ($setpriv) { return ''; }
                   7911: 
                   7912: # Backdoor access?
                   7913:     my $allowed=&allowed('eco',$ownerdomain);
                   7914: # Nope
                   7915:     unless ($allowed) { return ''; }
                   7916: # Looks like we may have access, but could be locked by the owner of the construction space
                   7917:     if ($allowed eq 'U') {
                   7918:         my %blocked=&get('environment',['domcoord.author'],
                   7919:                          $ownerdomain,$ownername);
                   7920: # Is blocked by owner
                   7921:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   7922:     }
                   7923:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   7924: # Grant temporary access
                   7925:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  7926:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  7927:         if (!$update) { $update = $then; }
                   7928:         my $refresh=$env{'user.refresh.time'};
                   7929:         if (!$refresh) { $refresh = $update; }
                   7930:         my $now = time;
                   7931:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   7932:                            $now,'ca','constructaccess');
                   7933:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   7934:         return($ownername,$ownerdomain,$ownerhome);
                   7935:     }
                   7936: # No business here
                   7937:     return '';
                   7938: }
                   7939: 
1.1172.2.66  raeburn  7940: # ----------------------------------------------------------- Content Blocking
                   7941: 
                   7942: {
                   7943: # Caches for faster Course Contents display where content blocking
                   7944: # is in operation (i.e., interval param set) for timed quiz.
                   7945: #
                   7946: # User for whom data are being temporarily cached.
                   7947: my $cacheduser='';
                   7948: # Cached blockers for this user (a hash of blocking items).
                   7949: my %cachedblockers=();
                   7950: # When the data were last cached.
                   7951: my $cachedlast='';
                   7952: 
                   7953: sub load_all_blockers {
                   7954:     my ($uname,$udom,$blocks)=@_;
                   7955:     if (($uname ne '') && ($udom ne '')) {
                   7956:         if (($cacheduser eq $uname.':'.$udom) &&
                   7957:             (abs($cachedlast-time)<5)) {
                   7958:             return;
                   7959:         }
                   7960:     }
                   7961:     $cachedlast=time;
                   7962:     $cacheduser=$uname.':'.$udom;
                   7963:     %cachedblockers = &get_commblock_resources($blocks);
                   7964: }
                   7965: 
1.1162    raeburn  7966: sub get_comm_blocks {
                   7967:     my ($cdom,$cnum) = @_;
                   7968:     if ($cdom eq '' || $cnum eq '') {
                   7969:         return unless ($env{'request.course.id'});
                   7970:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7971:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7972:     }
                   7973:     my %commblocks;
                   7974:     my $hashid=$cdom.'_'.$cnum;
                   7975:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   7976:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   7977:         %commblocks = %{$blocksref};
                   7978:     } else {
                   7979:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   7980:         my $cachetime = 600;
                   7981:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   7982:     }
                   7983:     return %commblocks;
                   7984: }
                   7985: 
1.1172.2.66  raeburn  7986: sub get_commblock_resources {
                   7987:     my ($blocks) = @_;
                   7988:     my %blockers = ();
                   7989:     return %blockers unless ($env{'request.course.id'});
                   7990:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  7991:     my %commblocks;
                   7992:     if (ref($blocks) eq 'HASH') {
                   7993:         %commblocks = %{$blocks};
                   7994:     } else {
                   7995:         %commblocks = &get_comm_blocks();
                   7996:     }
1.1172.2.66  raeburn  7997:     return %blockers unless (keys(%commblocks) > 0);
1.1163    raeburn  7998:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66  raeburn  7999:     return %blockers unless (ref($navmap));
                   8000:     my $now = time;
1.1162    raeburn  8001:     foreach my $block (keys(%commblocks)) {
                   8002:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8003:             my ($start,$end) = ($1,$2);
                   8004:             if ($start <= $now && $end >= $now) {
                   8005:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8006:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8007:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66  raeburn  8008:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8009:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162    raeburn  8010:                             }
                   8011:                         }
                   8012:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66  raeburn  8013:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8014:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8015:                             }
                   8016:                         }
                   8017:                     }
                   8018:                 }
                   8019:             }
                   8020:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8021:             my $item = $1;
1.1163    raeburn  8022:             my @to_test;
1.1162    raeburn  8023:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8024:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.66  raeburn  8025:                     my @interval;
                   8026:                     my $type = 'map';
                   8027:                     if ($item eq 'course') {
                   8028:                         $type = 'course';
                   8029:                         @interval=&EXT("resource.0.interval");
                   8030:                     } else {
                   8031:                         if ($item =~ /___\d+___/) {
                   8032:                             $type = 'resource';
                   8033:                             @interval=&EXT("resource.0.interval",$item);
                   8034:                             if (ref($navmap)) {
                   8035:                                 my $res = $navmap->getBySymb($item);
                   8036:                                 push(@to_test,$res);
                   8037:                             }
1.1162    raeburn  8038:                         } else {
1.1172.2.66  raeburn  8039:                             my $mapsymb = &symbread($item,1);
                   8040:                             if ($mapsymb) {
                   8041:                                 if (ref($navmap)) {
                   8042:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   8043:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   8044:                                     foreach my $res (@to_test) {
                   8045:                                         my $symb = $res->symb();
                   8046:                                         next if ($symb eq $mapsymb);
                   8047:                                         if ($symb ne '') {
                   8048:                                             @interval=&EXT("resource.0.interval",$symb);
                   8049:                                             if ($interval[1] eq 'map') {
                   8050:                                                 last;
1.1162    raeburn  8051:                                             }
                   8052:                                         }
                   8053:                                     }
                   8054:                                 }
                   8055:                             }
                   8056:                         }
1.1172.2.66  raeburn  8057:                     }
                   8058:                     if ($interval[0] =~ /^\d+$/) {
                   8059:                         my $first_access;
                   8060:                         if ($type eq 'resource') {
                   8061:                             $first_access=&get_first_access($interval[1],$item);
                   8062:                         } elsif ($type eq 'map') {
                   8063:                             $first_access=&get_first_access($interval[1],undef,$item);
                   8064:                         } else {
                   8065:                             $first_access=&get_first_access($interval[1]);
                   8066:                         }
                   8067:                         if ($first_access) {
                   8068:                             my $timesup = $first_access+$interval[0];
                   8069:                             if ($timesup > $now) {
                   8070:                                 my $activeblock;
                   8071:                                 foreach my $res (@to_test) {
                   8072:                                     if ($res->answerable()) {
                   8073:                                         $activeblock = 1;
                   8074:                                         last;
                   8075:                                     }
                   8076:                                 }
                   8077:                                 if ($activeblock) {
                   8078:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   8079:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8080:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   8081:                                          }
                   8082:                                     }
                   8083:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   8084:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8085:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  8086:                                         }
1.1162    raeburn  8087:                                     }
                   8088:                                 }
                   8089:                             }
                   8090:                         }
                   8091:                     }
                   8092:                 }
                   8093:             }
                   8094:         }
                   8095:     }
1.1172.2.66  raeburn  8096:     return %blockers;
1.1162    raeburn  8097: }
                   8098: 
1.1172.2.66  raeburn  8099: sub has_comm_blocking {
                   8100:     my ($priv,$symb,$uri,$blocks) = @_;
                   8101:     my @blockers;
                   8102:     return unless ($env{'request.course.id'});
                   8103:     return unless ($priv eq 'bre');
                   8104:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   8105:     return if ($env{'request.state'} eq 'construct');
                   8106:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   8107:     return unless (keys(%cachedblockers) > 0);
                   8108:     my (%possibles,@symbs);
                   8109:     if (!$symb) {
                   8110:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  8111:     }
1.1172.2.66  raeburn  8112:     if ($symb) {
                   8113:         @symbs = ($symb);
                   8114:     } elsif (keys(%possibles)) {
                   8115:         @symbs = keys(%possibles);
                   8116:     }
                   8117:     my $noblock;
                   8118:     foreach my $symb (@symbs) {
                   8119:         last if ($noblock);
                   8120:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   8121:         foreach my $block (keys(%cachedblockers)) {
                   8122:             if ($block =~ /^firstaccess____(.+)$/) {
                   8123:                 my $item = $1;
                   8124:                 if (($item eq $map) || ($item eq $symb)) {
                   8125:                     $noblock = 1;
                   8126:                     last;
                   8127:                 }
1.1162    raeburn  8128:             }
1.1172.2.66  raeburn  8129:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   8130:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   8131:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   8132:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8133:                             push(@blockers,$block);
                   8134:                         }
                   8135:                     }
                   8136:                 }
                   8137:             }
                   8138:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   8139:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   8140:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   8141:                         push(@blockers,$block);
                   8142:                     }
                   8143:                 }
1.1162    raeburn  8144:             }
                   8145:         }
                   8146:     }
1.1172.2.66  raeburn  8147:     return if ($noblock);
                   8148:     return @blockers;
                   8149: }
1.1162    raeburn  8150: }
                   8151: 
1.1172.2.66  raeburn  8152: # -------------------------------- Deversion and split uri into path an filename
                   8153: 
1.1133    foxr     8154: #
1.1172.2.66  raeburn  8155: #   Removes the version from a URI and
1.1133    foxr     8156: #   splits it in to its filename and path to the filename.
                   8157: #   Seems like File::Basename could have done this more clearly.
                   8158: #   Parameters:
                   8159: #      $uri   - input URI
                   8160: #   Returns:
                   8161: #     Two element list consisting of 
                   8162: #     $pathname  - the URI up to and excluding the trailing /
                   8163: #     $filename  - The part of the URI following the last /
                   8164: #  NOTE:
                   8165: #    Another realization of this is simply:
                   8166: #    use File::Basename;
                   8167: #    ...
                   8168: #    $uri = shift;
                   8169: #    $filename = basename($uri);
                   8170: #    $path     = dirname($uri);
                   8171: #    return ($filename, $path);
                   8172: #
                   8173: #     The implementation below is probably faster however.
                   8174: #
1.710     albertel 8175: sub split_uri_for_cond {
                   8176:     my $uri=&deversion(&declutter(shift));
                   8177:     my @uriparts=split(/\//,$uri);
                   8178:     my $filename=pop(@uriparts);
                   8179:     my $pathname=join('/',@uriparts);
                   8180:     return ($pathname,$filename);
                   8181: }
1.232     www      8182: # --------------------------------------------------- Is a resource on the map?
                   8183: 
                   8184: sub is_on_map {
1.710     albertel 8185:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 8186:     #Trying to find the conditional for the file
1.620     albertel 8187:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 8188: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      8189:     if ($match) {
1.289     bowersj2 8190: 	return (1,$1);
                   8191:     } else {
1.434     www      8192: 	return (0,0);
1.289     bowersj2 8193:     }
1.12      www      8194: }
                   8195: 
1.427     www      8196: # --------------------------------------------------------- Get symb from alias
                   8197: 
                   8198: sub get_symb_from_alias {
                   8199:     my $symb=shift;
                   8200:     my ($map,$resid,$url)=&decode_symb($symb);
                   8201: # Already is a symb
                   8202:     if ($url) { return $symb; }
                   8203: # Must be an alias
                   8204:     my $aliassymb='';
                   8205:     my %bighash;
1.620     albertel 8206:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      8207:                             &GDBM_READER(),0640)) {
                   8208:         my $rid=$bighash{'mapalias_'.$symb};
                   8209: 	if ($rid) {
                   8210: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 8211: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   8212: 				    $resid,$bighash{'src_'.$rid});
1.427     www      8213: 	}
                   8214:         untie %bighash;
                   8215:     }
                   8216:     return $aliassymb;
                   8217: }
                   8218: 
1.12      www      8219: # ----------------------------------------------------------------- Define Role
                   8220: 
                   8221: sub definerole {
                   8222:   if (allowed('mcr','/')) {
1.1172.2.84  raeburn  8223:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 8224:     foreach my $role (split(':',$sysrole)) {
                   8225: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8226:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   8227:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   8228: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8229:                return "refused:s:$crole&$cqual"; 
                   8230:             }
                   8231:         }
1.191     harris41 8232:     }
1.800     albertel 8233:     foreach my $role (split(':',$domrole)) {
                   8234: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8235:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   8236:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   8237: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      8238:                return "refused:d:$crole&$cqual"; 
                   8239:             }
                   8240:         }
1.191     harris41 8241:     }
1.800     albertel 8242:     foreach my $role (split(':',$courole)) {
                   8243: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8244:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   8245:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   8246: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8247:                return "refused:c:$crole&$cqual"; 
                   8248:             }
                   8249:         }
1.191     harris41 8250:     }
1.1172.2.84  raeburn  8251:     my $uhome;
                   8252:     if (($uname ne '') && ($udom ne '')) {
                   8253:         $uhome = &homeserver($uname,$udom);
                   8254:         return $uhome if ($uhome eq 'no_host');
                   8255:     } else {
                   8256:         $uname = $env{'user.name'};
                   8257:         $udom = $env{'user.domain'};
                   8258:         $uhome = $env{'user.home'};
                   8259:     }
1.620     albertel 8260:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84  raeburn  8261:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      8262:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84  raeburn  8263:     return reply($command,$uhome);
1.12      www      8264:   } else {
                   8265:     return 'refused';
                   8266:   }
1.105     harris41 8267: }
                   8268: 
                   8269: # ---------------- Make a metadata query against the network of library servers
                   8270: 
                   8271: sub metadata_query {
1.1172.2.33  raeburn  8272:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 8273:     my %rhash;
1.845     albertel 8274:     my %libserv = &all_library();
1.244     matthew  8275:     my @server_list = (defined($server_array) ? @$server_array
                   8276:                                               : keys(%libserv) );
                   8277:     for my $server (@server_list) {
1.1172.2.33  raeburn  8278:         my $domains = '';
                   8279:         if (ref($domains_hash) eq 'HASH') {
                   8280:             $domains = $domains_hash->{$server};    
                   8281:         }
1.118     harris41 8282: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  8283: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 8284: 	    $rhash{$server}=$reply;
                   8285: 	}
                   8286: 	else {
                   8287: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  8288: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 8289: 			     $server);
                   8290: 	    $rhash{$server}=$reply;
                   8291: 	}
1.112     harris41 8292:     }
1.118     harris41 8293:     return \%rhash;
1.240     www      8294: }
                   8295: 
                   8296: # ----------------------------------------- Send log queries and wait for reply
                   8297: 
                   8298: sub log_query {
                   8299:     my ($uname,$udom,$query,%filters)=@_;
                   8300:     my $uhome=&homeserver($uname,$udom);
                   8301:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 8302:     my $uhost=&hostname($uhome);
1.800     albertel 8303:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      8304:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   8305:                        $uhome);
1.479     albertel 8306:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      8307:     return get_query_reply($queryid);
                   8308: }
                   8309: 
1.818     raeburn  8310: # -------------------------- Update MySQL table for portfolio file
                   8311: 
                   8312: sub update_portfolio_table {
1.821     raeburn  8313:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  8314:     if ($group ne '') {
                   8315:         $file_name =~s /^\Q$group\E//;
                   8316:     }
1.818     raeburn  8317:     my $homeserver = &homeserver($uname,$udom);
                   8318:     my $queryid=
1.821     raeburn  8319:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   8320:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  8321:     my $reply = &get_query_reply($queryid);
                   8322:     return $reply;
                   8323: }
                   8324: 
1.899     raeburn  8325: # -------------------------- Update MySQL allusers table
                   8326: 
                   8327: sub update_allusers_table {
                   8328:     my ($uname,$udom,$names) = @_;
                   8329:     my $homeserver = &homeserver($uname,$udom);
                   8330:     my $queryid=
                   8331:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   8332:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   8333:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   8334:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   8335:                'generation='.&escape($names->{'generation'}).'%%'.
                   8336:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   8337:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  8338:     return;
1.899     raeburn  8339: }
                   8340: 
1.508     raeburn  8341: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  8342: 
                   8343: sub fetch_enrollment_query {
1.511     raeburn  8344:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79  raeburn  8345:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  8346:     my $maxtries = 1;
1.508     raeburn  8347:     if ($context eq 'automated') {
                   8348:         $homeserver = $perlvar{'lonHostID'};
1.1172.2.79  raeburn  8349:         $sleep = 2;
                   8350:         $loopmax = 100;
1.547     raeburn  8351:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  8352:     } else {
                   8353:         $homeserver = &homeserver($cnum,$dom);
                   8354:     }
1.838     albertel 8355:     my $host=&hostname($homeserver);
1.506     raeburn  8356:     my $cmd = '';
1.1000    raeburn  8357:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 8358:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  8359:     }
                   8360:     $cmd =~ s/%%$//;
                   8361:     $cmd = &escape($cmd);
                   8362:     my $query = 'fetchenrollment';
1.620     albertel 8363:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  8364:     unless ($queryid=~/^\Q$host\E\_/) { 
                   8365:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   8366:         return 'error: '.$queryid;
                   8367:     }
1.1172.2.93  raeburn  8368:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8369:     my $tries = 1;
                   8370:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79  raeburn  8371:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8372:         $tries ++;
                   8373:     }
1.526     raeburn  8374:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 8375:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  8376:     } else {
1.901     albertel 8377:         my @responses = split(/:/,$reply);
1.1172.2.82  raeburn  8378:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 8379:             foreach my $line (@responses) {
                   8380:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  8381:                 $$replyref{$key} = $value;
                   8382:             }
                   8383:         } else {
1.1117    foxr     8384:             my $pathname = LONCAPA::tempdir();
1.800     albertel 8385:             foreach my $line (@responses) {
                   8386:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  8387:                 $$replyref{$key} = $value;
                   8388:                 if ($value > 0) {
1.800     albertel 8389:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   8390:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  8391:                         my $destname = $pathname.'/'.$filename;
                   8392:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  8393:                         if ($xml_classlist =~ /^error/) {
                   8394:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   8395:                         } else {
1.1172.2.96  raeburn  8396:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  8397:                                 print FILE &unescape($xml_classlist);
                   8398:                                 close(FILE);
1.526     raeburn  8399:                             } else {
                   8400:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  8401:                             }
                   8402:                         }
                   8403:                     }
                   8404:                 }
                   8405:             }
                   8406:         }
                   8407:         return 'ok';
                   8408:     }
                   8409:     return 'error';
                   8410: }
                   8411: 
1.242     www      8412: sub get_query_reply {
1.1172.2.79  raeburn  8413:     my ($queryid,$sleep,$loopmax) = @_;
                   8414:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   8415:         $sleep = 0.2;
                   8416:     }
                   8417:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   8418:         $loopmax = 100;
                   8419:     }
1.1117    foxr     8420:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      8421:     my $reply='';
1.1172.2.79  raeburn  8422:     for (1..$loopmax) {
                   8423: 	sleep($sleep);
1.240     www      8424:         if (-e $replyfile.'.end') {
1.1172.2.96  raeburn  8425: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 8426: 		$reply = join('',<$fh>);
                   8427: 		close($fh);
1.240     www      8428: 	   } else { return 'error: reply_file_error'; }
1.242     www      8429:            return &unescape($reply);
                   8430: 	}
1.240     www      8431:     }
1.242     www      8432:     return 'timeout:'.$queryid;
1.240     www      8433: }
                   8434: 
                   8435: sub courselog_query {
1.241     www      8436: #
                   8437: # possible filters:
                   8438: # url: url or symb
                   8439: # username
                   8440: # domain
                   8441: # action: view, submit, grade
                   8442: # start: timestamp
                   8443: # end: timestamp
                   8444: #
1.240     www      8445:     my (%filters)=@_;
1.620     albertel 8446:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      8447:     if ($filters{'url'}) {
                   8448: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   8449:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   8450:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   8451:     }
1.620     albertel 8452:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8453:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      8454:     return &log_query($cname,$cdom,'courselog',%filters);
                   8455: }
                   8456: 
                   8457: sub userlog_query {
1.858     raeburn  8458: #
                   8459: # possible filters:
                   8460: # action: log check role
                   8461: # start: timestamp
                   8462: # end: timestamp
                   8463: #
1.240     www      8464:     my ($uname,$udom,%filters)=@_;
                   8465:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      8466: }
                   8467: 
1.506     raeburn  8468: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   8469: 
                   8470: sub auto_run {
1.508     raeburn  8471:     my ($cnum,$cdom) = @_;
1.876     raeburn  8472:     my $response = 0;
                   8473:     my $settings;
                   8474:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   8475:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   8476:         $settings = $domconfig{'autoenroll'};
                   8477:         if ($settings->{'run'} eq '1') {
                   8478:             $response = 1;
                   8479:         }
                   8480:     } else {
1.934     raeburn  8481:         my $homeserver;
                   8482:         if (&is_course($cdom,$cnum)) {
                   8483:             $homeserver = &homeserver($cnum,$cdom);
                   8484:         } else {
                   8485:             $homeserver = &domain($cdom,'primary');
                   8486:         }
                   8487:         if ($homeserver ne 'no_host') {
                   8488:             $response = &reply('autorun:'.$cdom,$homeserver);
                   8489:         }
1.876     raeburn  8490:     }
1.506     raeburn  8491:     return $response;
                   8492: }
1.776     albertel 8493: 
1.506     raeburn  8494: sub auto_get_sections {
1.508     raeburn  8495:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  8496:     my $homeserver;
                   8497:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   8498:         $homeserver = &homeserver($cnum,$cdom);
                   8499:     }
                   8500:     if (!defined($homeserver)) { 
                   8501:         if ($cdom =~ /^$match_domain$/) {
                   8502:             $homeserver = &domain($cdom,'primary');
                   8503:         }
                   8504:     }
                   8505:     my @secs;
                   8506:     if (defined($homeserver)) {
                   8507:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   8508:         unless ($response eq 'refused') {
                   8509:             @secs = split(/:/,$response);
                   8510:         }
1.506     raeburn  8511:     }
                   8512:     return @secs;
                   8513: }
1.776     albertel 8514: 
1.506     raeburn  8515: sub auto_new_course {
1.1099    raeburn  8516:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  8517:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  8518:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  8519:     return $response;
                   8520: }
1.776     albertel 8521: 
1.506     raeburn  8522: sub auto_validate_courseID {
1.508     raeburn  8523:     my ($cnum,$cdom,$inst_course_id) = @_;
                   8524:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  8525:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  8526:     return $response;
                   8527: }
1.776     albertel 8528: 
1.1007    raeburn  8529: sub auto_validate_instcode {
1.1020    raeburn  8530:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  8531:     my ($homeserver,$response);
                   8532:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8533:         $homeserver = &homeserver($cnum,$cdom);
                   8534:     }
                   8535:     if (!defined($homeserver)) {
                   8536:         if ($cdom =~ /^$match_domain$/) {
                   8537:             $homeserver = &domain($cdom,'primary');
                   8538:         }
                   8539:     }
1.1065    raeburn  8540:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   8541:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  8542:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   8543:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  8544: }
                   8545: 
1.506     raeburn  8546: sub auto_create_password {
1.873     raeburn  8547:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   8548:     my ($homeserver,$response);
1.506     raeburn  8549:     my $create_passwd = 0;
                   8550:     my $authchk = '';
1.873     raeburn  8551:     if ($udom =~ /^$match_domain$/) {
                   8552:         $homeserver = &domain($udom,'primary');
                   8553:     }
                   8554:     if ($homeserver eq '') {
                   8555:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8556:             $homeserver = &homeserver($cnum,$cdom);
                   8557:         }
                   8558:     }
                   8559:     if ($homeserver eq '') {
                   8560:         $authchk = 'nodomain';
1.506     raeburn  8561:     } else {
1.873     raeburn  8562:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   8563:         if ($response eq 'refused') {
                   8564:             $authchk = 'refused';
                   8565:         } else {
1.901     albertel 8566:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  8567:         }
1.506     raeburn  8568:     }
                   8569:     return ($authparam,$create_passwd,$authchk);
                   8570: }
                   8571: 
1.706     raeburn  8572: sub auto_photo_permission {
                   8573:     my ($cnum,$cdom,$students) = @_;
                   8574:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 8575:     my ($outcome,$perm_reqd,$conditions) = 
                   8576: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 8577:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8578: 	return (undef,undef);
                   8579:     }
1.706     raeburn  8580:     return ($outcome,$perm_reqd,$conditions);
                   8581: }
                   8582: 
                   8583: sub auto_checkphotos {
                   8584:     my ($uname,$udom,$pid) = @_;
                   8585:     my $homeserver = &homeserver($uname,$udom);
                   8586:     my ($result,$resulttype);
                   8587:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 8588: 				   &escape($uname).':'.&escape($pid),
                   8589: 				   $homeserver));
1.709     albertel 8590:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8591: 	return (undef,undef);
                   8592:     }
1.706     raeburn  8593:     if ($outcome) {
                   8594:         ($result,$resulttype) = split(/:/,$outcome);
                   8595:     } 
                   8596:     return ($result,$resulttype);
                   8597: }
                   8598: 
                   8599: sub auto_photochoice {
                   8600:     my ($cnum,$cdom) = @_;
                   8601:     my $homeserver = &homeserver($cnum,$cdom);
                   8602:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 8603: 						       &escape($cdom),
                   8604: 						       $homeserver)));
1.709     albertel 8605:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8606: 	return (undef,undef);
                   8607:     }
1.706     raeburn  8608:     return ($update,$comment);
                   8609: }
                   8610: 
                   8611: sub auto_photoupdate {
                   8612:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   8613:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 8614:     my $host=&hostname($homeserver);
1.706     raeburn  8615:     my $cmd = '';
                   8616:     my $maxtries = 1;
1.800     albertel 8617:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   8618:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  8619:     }
                   8620:     $cmd =~ s/%%$//;
                   8621:     $cmd = &escape($cmd);
                   8622:     my $query = 'institutionalphotos';
                   8623:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   8624:     unless ($queryid=~/^\Q$host\E\_/) {
                   8625:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   8626:         return 'error: '.$queryid;
                   8627:     }
                   8628:     my $reply = &get_query_reply($queryid);
                   8629:     my $tries = 1;
                   8630:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   8631:         $reply = &get_query_reply($queryid);
                   8632:         $tries ++;
                   8633:     }
                   8634:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   8635:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   8636:     } else {
                   8637:         my @responses = split(/:/,$reply);
                   8638:         my $outcome = shift(@responses); 
                   8639:         foreach my $item (@responses) {
                   8640:             my ($key,$value) = split(/=/,$item);
                   8641:             $$photo{$key} = $value;
                   8642:         }
                   8643:         return $outcome;
                   8644:     }
                   8645:     return 'error';
                   8646: }
                   8647: 
1.521     raeburn  8648: sub auto_instcode_format {
1.793     albertel 8649:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   8650: 	$cat_order) = @_;
1.521     raeburn  8651:     my $courses = '';
1.772     raeburn  8652:     my @homeservers;
1.521     raeburn  8653:     if ($caller eq 'global') {
1.841     albertel 8654: 	my %servers = &get_servers($codedom,'library');
                   8655: 	foreach my $tryserver (keys(%servers)) {
                   8656: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8657: 		push(@homeservers,$tryserver);
                   8658: 	    }
1.584     raeburn  8659:         }
1.1022    raeburn  8660:     } elsif ($caller eq 'requests') {
                   8661:         if ($codedom =~ /^$match_domain$/) {
                   8662:             my $chome = &domain($codedom,'primary');
                   8663:             unless ($chome eq 'no_host') {
                   8664:                 push(@homeservers,$chome);
                   8665:             }
                   8666:         }
1.521     raeburn  8667:     } else {
1.772     raeburn  8668:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  8669:     }
1.793     albertel 8670:     foreach my $code (keys(%{$instcodes})) {
                   8671:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  8672:     }
                   8673:     chop($courses);
1.772     raeburn  8674:     my $ok_response = 0;
                   8675:     my $response;
                   8676:     while (@homeservers > 0 && $ok_response == 0) {
                   8677:         my $server = shift(@homeservers); 
                   8678:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   8679:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   8680:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 8681: 		split(/:/,$response);
1.772     raeburn  8682:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   8683:             push(@{$codetitles},&str2array($codetitles_str));
                   8684:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   8685:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   8686:             $ok_response = 1;
                   8687:         }
                   8688:     }
                   8689:     if ($ok_response) {
1.521     raeburn  8690:         return 'ok';
1.772     raeburn  8691:     } else {
                   8692:         return $response;
1.521     raeburn  8693:     }
                   8694: }
                   8695: 
1.792     raeburn  8696: sub auto_instcode_defaults {
                   8697:     my ($domain,$returnhash,$code_order) = @_;
                   8698:     my @homeservers;
1.841     albertel 8699: 
                   8700:     my %servers = &get_servers($domain,'library');
                   8701:     foreach my $tryserver (keys(%servers)) {
                   8702: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8703: 	    push(@homeservers,$tryserver);
                   8704: 	}
1.792     raeburn  8705:     }
1.841     albertel 8706: 
1.792     raeburn  8707:     my $response;
1.841     albertel 8708:     foreach my $server (@homeservers) {
1.792     raeburn  8709:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 8710:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   8711: 	
                   8712: 	foreach my $pair (split(/\&/,$response)) {
                   8713: 	    my ($name,$value)=split(/\=/,$pair);
                   8714: 	    if ($name eq 'code_order') {
                   8715: 		@{$code_order} = split(/\&/,&unescape($value));
                   8716: 	    } else {
                   8717: 		$returnhash->{&unescape($name)}=&unescape($value);
                   8718: 	    }
                   8719: 	}
                   8720: 	return 'ok';
1.792     raeburn  8721:     }
1.841     albertel 8722: 
                   8723:     return $response;
1.1003    raeburn  8724: }
                   8725: 
                   8726: sub auto_possible_instcodes {
1.1007    raeburn  8727:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   8728:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   8729:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8730:         return;
                   8731:     }
1.1003    raeburn  8732:     my (@homeservers,$uhome);
                   8733:     if (defined(&domain($domain,'primary'))) {
                   8734:         $uhome=&domain($domain,'primary');
                   8735:         push(@homeservers,&domain($domain,'primary'));
                   8736:     } else {
                   8737:         my %servers = &get_servers($domain,'library');
                   8738:         foreach my $tryserver (keys(%servers)) {
                   8739:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8740:                 push(@homeservers,$tryserver);
                   8741:             }
                   8742:         }
                   8743:     }
                   8744:     my $response;
                   8745:     foreach my $server (@homeservers) {
                   8746:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   8747:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  8748:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   8749:             split(':',$response);
                   8750:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   8751:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  8752:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  8753:             my ($name,$value)=split('=',$item);
                   8754:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8755:         }
                   8756:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  8757:             my ($name,$value)=split('=',$item);
                   8758:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8759:         }
                   8760:         return 'ok';
                   8761:     }
                   8762:     return $response;
                   8763: }
1.792     raeburn  8764: 
1.1010    raeburn  8765: sub auto_courserequest_checks {
                   8766:     my ($dom) = @_;
1.1020    raeburn  8767:     my ($homeserver,%validations);
                   8768:     if ($dom =~ /^$match_domain$/) {
                   8769:         $homeserver = &domain($dom,'primary');
                   8770:     }
                   8771:     unless ($homeserver eq 'no_host') {
                   8772:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   8773:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8774:             my @items = split(/&/,$response);
                   8775:             foreach my $item (@items) {
                   8776:                 my ($key,$value) = split('=',$item);
                   8777:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   8778:             }
                   8779:         }
                   8780:     }
1.1010    raeburn  8781:     return %validations; 
                   8782: }
                   8783: 
1.1020    raeburn  8784: sub auto_courserequest_validation {
1.1172.2.43  raeburn  8785:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  8786:     my ($homeserver,$response);
                   8787:     if ($dom =~ /^$match_domain$/) {
                   8788:         $homeserver = &domain($dom,'primary');
                   8789:     }
1.1172.2.43  raeburn  8790:     unless ($homeserver eq 'no_host') {
                   8791:         my $customdata;
                   8792:         if (ref($custominfo) eq 'HASH') {
                   8793:             $customdata = &freeze_escape($custominfo);
                   8794:         }
1.1020    raeburn  8795:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  8796:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43  raeburn  8797:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   8798:                                     $customdata,$homeserver));
1.1020    raeburn  8799:     }
                   8800:     return $response;
                   8801: }
                   8802: 
1.777     albertel 8803: sub auto_validate_class_sec {
1.918     raeburn  8804:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  8805:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  8806:     my $ownerlist;
                   8807:     if (ref($owners) eq 'ARRAY') {
                   8808:         $ownerlist = join(',',@{$owners});
                   8809:     } else {
                   8810:         $ownerlist = $owners;
                   8811:     }
1.773     raeburn  8812:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  8813:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  8814:     return $response;
                   8815: }
                   8816: 
1.1172.2.94  raeburn  8817: sub auto_validate_instclasses {
                   8818:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   8819:     my ($homeserver,%validations);
                   8820:     $homeserver = &homeserver($cnum,$cdom);
                   8821:     unless ($homeserver eq 'no_host') {
                   8822:         my $ownerlist;
                   8823:         if (ref($owners) eq 'ARRAY') {
                   8824:             $ownerlist = join(',',@{$owners});
                   8825:         } else {
                   8826:             $ownerlist = $owners;
                   8827:         }
                   8828:         if (ref($classesref) eq 'HASH') {
                   8829:             my $classes = &freeze_escape($classesref);
                   8830:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   8831:                                 ':'.$cdom.':'.$classes,$homeserver);
                   8832:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8833:                 my @items = split(/&/,$response);
                   8834:                 foreach my $item (@items) {
                   8835:                     my ($key,$value) = split('=',$item);
                   8836:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   8837:                 }
                   8838:             }
                   8839:         }
                   8840:     }
                   8841:     return %validations;
                   8842: }
                   8843: 
1.1172.2.38  raeburn  8844: sub auto_crsreq_update {
                   8845:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45  raeburn  8846:         $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38  raeburn  8847:     my ($homeserver,%crsreqresponse);
                   8848:     if ($cdom =~ /^$match_domain$/) {
                   8849:         $homeserver = &domain($cdom,'primary');
                   8850:     }
                   8851:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8852:         my $info;
                   8853:         if (ref($inbound) eq 'HASH') {
                   8854:             $info = &freeze_escape($inbound);
                   8855:         }
                   8856:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   8857:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   8858:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45  raeburn  8859:                             &escape($title).':'.&escape($code).':'.
                   8860:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38  raeburn  8861:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8862:             my @items = split(/&/,$response);
                   8863:             foreach my $item (@items) {
                   8864:                 my ($key,$value) = split('=',$item);
                   8865:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   8866:             }
                   8867:         }
                   8868:     }
                   8869:     return \%crsreqresponse;
                   8870: }
                   8871: 
1.1172.2.78  raeburn  8872: sub auto_export_grades {
                   8873:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   8874:     my ($homeserver,%exportresponse);
                   8875:     if ($cdom =~ /^$match_domain$/) {
                   8876:         $homeserver = &domain($cdom,'primary');
                   8877:     }
                   8878:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8879:         my $info;
                   8880:         if (ref($inforef) eq 'HASH') {
                   8881:             $info = &freeze_escape($inforef);
                   8882:         }
                   8883:         if (ref($gradesref) eq 'HASH') {
                   8884:             my $grades = &freeze_escape($gradesref);
                   8885:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   8886:                                 $info.':'.$grades,$homeserver);
                   8887:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   8888:                 my @items = split(/&/,$response);
                   8889:                 foreach my $item (@items) {
                   8890:                     my ($key,$value) = split('=',$item);
                   8891:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   8892:                 }
                   8893:             }
                   8894:         }
                   8895:     }
                   8896:     return \%exportresponse;
                   8897: }
                   8898: 
1.1172.2.68  raeburn  8899: sub check_instcode_cloning {
                   8900:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   8901:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8902:         return;
                   8903:     }
                   8904:     my $canclone;
                   8905:     if (@{$code_order} > 0) {
                   8906:         my $instcoderegexp ='^';
                   8907:         my @clonecodes = split(/\&/,$cloner);
                   8908:         foreach my $item (@{$code_order}) {
                   8909:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   8910:                 foreach my $pair (@clonecodes) {
                   8911:                     my ($key,$val) = split(/\=/,$pair,2);
                   8912:                     $val = &unescape($val);
                   8913:                     if ($key eq $item) {
                   8914:                         $instcoderegexp .= '('.$val.')';
                   8915:                         last;
                   8916:                     }
                   8917:                 }
                   8918:             } else {
                   8919:                 $instcoderegexp .= $codedefaults->{$item};
                   8920:             }
                   8921:         }
                   8922:         $instcoderegexp .= '$';
                   8923:         my (@from,@to);
                   8924:         eval {
                   8925:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8926:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8927:         };
                   8928:         if ((@from > 0) && (@to > 0)) {
                   8929:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8930:             if (!@diffs) {
                   8931:                 $canclone = 1;
                   8932:             }
                   8933:         }
                   8934:     }
                   8935:     return $canclone;
                   8936: }
                   8937: 
                   8938: sub default_instcode_cloning {
                   8939:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   8940:     my (%codedefaults,@code_order,$canclone);
                   8941:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   8942:         %codedefaults = %{$codedefaultsref};
                   8943:         @code_order = @{$codeorderref};
                   8944:     } elsif ($clonedom) {
                   8945:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   8946:     }
                   8947:     if (($domdefclone) && (@code_order)) {
                   8948:         my @clonecodes = split(/\+/,$domdefclone);
                   8949:         my $instcoderegexp ='^';
                   8950:         foreach my $item (@code_order) {
                   8951:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   8952:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   8953:             } else {
                   8954:                 $instcoderegexp .= $codedefaults{$item};
                   8955:             }
                   8956:         }
                   8957:         $instcoderegexp .= '$';
                   8958:         my (@from,@to);
                   8959:         eval {
                   8960:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8961:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8962:         };
                   8963:         if ((@from > 0) && (@to > 0)) {
                   8964:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8965:             if (!@diffs) {
                   8966:                 $canclone = 1;
                   8967:             }
                   8968:         }
                   8969:     }
                   8970:     return $canclone;
                   8971: }
                   8972: 
1.679     raeburn  8973: # ------------------------------------------------------- Course Group routines
                   8974: 
                   8975: sub get_coursegroups {
1.809     raeburn  8976:     my ($cdom,$cnum,$group,$namespace) = @_;
                   8977:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  8978: }
                   8979: 
1.679     raeburn  8980: sub modify_coursegroup {
                   8981:     my ($cdom,$cnum,$groupsettings) = @_;
                   8982:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   8983: }
                   8984: 
1.809     raeburn  8985: sub toggle_coursegroup_status {
                   8986:     my ($cdom,$cnum,$group,$action) = @_;
                   8987:     my ($from_namespace,$to_namespace);
                   8988:     if ($action eq 'delete') {
                   8989:         $from_namespace = 'coursegroups';
                   8990:         $to_namespace = 'deleted_groups';
                   8991:     } else {
                   8992:         $from_namespace = 'deleted_groups';
                   8993:         $to_namespace = 'coursegroups';
                   8994:     }
                   8995:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  8996:     if (my $tmp = &error(%curr_group)) {
                   8997:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   8998:         return ('read error',$tmp);
                   8999:     } else {
                   9000:         my %savedsettings = %curr_group; 
1.809     raeburn  9001:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  9002:         my $deloutcome;
                   9003:         if ($result eq 'ok') {
1.809     raeburn  9004:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  9005:         } else {
                   9006:             return ('write error',$result);
                   9007:         }
                   9008:         if ($deloutcome eq 'ok') {
                   9009:             return 'ok';
                   9010:         } else {
                   9011:             return ('delete error',$deloutcome);
                   9012:         }
                   9013:     }
                   9014: }
                   9015: 
1.679     raeburn  9016: sub modify_group_roles {
1.957     raeburn  9017:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  9018:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   9019:     my $role = 'gr/'.&escape($userprivs);
                   9020:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  9021:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  9022:     if ($result eq 'ok') {
                   9023:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   9024:     }
1.679     raeburn  9025:     return $result;
                   9026: }
                   9027: 
                   9028: sub modify_coursegroup_membership {
                   9029:     my ($cdom,$cnum,$membership) = @_;
                   9030:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   9031:     return $result;
                   9032: }
                   9033: 
1.682     raeburn  9034: sub get_active_groups {
                   9035:     my ($udom,$uname,$cdom,$cnum) = @_;
                   9036:     my $now = time;
                   9037:     my %groups = ();
                   9038:     foreach my $key (keys(%env)) {
1.811     albertel 9039:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  9040:             my ($start,$end) = split(/\./,$env{$key});
                   9041:             if (($end!=0) && ($end<$now)) { next; }
                   9042:             if (($start!=0) && ($start>$now)) { next; }
                   9043:             if ($1 eq $cdom && $2 eq $cnum) {
                   9044:                 $groups{$3} = $env{$key} ;
                   9045:             }
                   9046:         }
                   9047:     }
                   9048:     return %groups;
                   9049: }
                   9050: 
1.683     raeburn  9051: sub get_group_membership {
                   9052:     my ($cdom,$cnum,$group) = @_;
                   9053:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   9054: }
                   9055: 
                   9056: sub get_users_groups {
                   9057:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  9058:     my @usersgroups;
1.683     raeburn  9059:     my $cachetime=1800;
                   9060: 
                   9061:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  9062:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   9063:     if (defined($cached)) {
1.734     albertel 9064:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  9065:     } else {  
                   9066:         $grouplist = '';
1.816     raeburn  9067:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  9068:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  9069:         my $access_end = $env{'course.'.$courseid.
                   9070:                               '.default_enrollment_end_date'};
                   9071:         my $now = time;
                   9072:         foreach my $key (keys(%roleshash)) {
                   9073:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   9074:                 my $group = $1;
                   9075:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   9076:                     my $start = $2;
                   9077:                     my $end = $1;
                   9078:                     if ($start == -1) { next; } # deleted from group
                   9079:                     if (($start!=0) && ($start>$now)) { next; }
                   9080:                     if (($end!=0) && ($end<$now)) {
                   9081:                         if ($access_end && $access_end < $now) {
                   9082:                             if ($access_end - $end < 86400) {
                   9083:                                 push(@usersgroups,$group);
1.733     raeburn  9084:                             }
                   9085:                         }
1.817     raeburn  9086:                         next;
1.733     raeburn  9087:                     }
1.817     raeburn  9088:                     push(@usersgroups,$group);
1.683     raeburn  9089:                 }
                   9090:             }
                   9091:         }
1.817     raeburn  9092:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   9093:         $grouplist = join(':',@usersgroups);
                   9094:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  9095:     }
1.733     raeburn  9096:     return @usersgroups;
1.683     raeburn  9097: }
                   9098: 
                   9099: sub devalidate_getgroups_cache {
                   9100:     my ($udom,$uname,$cdom,$cnum)=@_;
                   9101:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 9102: 
1.683     raeburn  9103:     my $hashid="$udom:$uname:$courseid";
                   9104:     &devalidate_cache_new('getgroups',$hashid);
                   9105: }
                   9106: 
1.12      www      9107: # ------------------------------------------------------------------ Plain Text
                   9108: 
                   9109: sub plaintext {
1.988     raeburn  9110:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  9111:     if ($short =~ m{^cr/}) {
1.758     albertel 9112: 	return (split('/',$short))[-1];
                   9113:     }
1.742     raeburn  9114:     if (!defined($cid)) {
                   9115:         $cid = $env{'request.course.id'};
                   9116:     }
                   9117:     my %rolenames = (
1.1008    raeburn  9118:                       Course    => 'std',
                   9119:                       Community => 'alt1',
1.742     raeburn  9120:                     );
1.1037    raeburn  9121:     if ($cid ne '') {
                   9122:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   9123:             unless ($forcedefault) {
                   9124:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   9125:                 &Apache::lonlocal::mt_escape(\$roletext);
                   9126:                 return &Apache::lonlocal::mt($roletext);
                   9127:             }
                   9128:         }
                   9129:     }
                   9130:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   9131:         (defined($rolenames{$type})) && 
                   9132:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  9133:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  9134:     } elsif ($cid ne '') {
                   9135:         my $crstype = $env{'course.'.$cid.'.type'};
                   9136:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   9137:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   9138:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   9139:         }
1.742     raeburn  9140:     }
1.1037    raeburn  9141:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      9142: }
                   9143: 
                   9144: # ----------------------------------------------------------------- Assign Role
                   9145: 
                   9146: sub assignrole {
1.957     raeburn  9147:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   9148:         $context)=@_;
1.21      www      9149:     my $mrole;
                   9150:     if ($role =~ /^cr\//) {
1.393     www      9151:         my $cwosec=$url;
1.811     albertel 9152:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      9153: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  9154:            my $refused = 1;
                   9155:            if ($context eq 'requestcourses') {
                   9156:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   9157:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   9158:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   9159:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9160:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9161:                            if ($crsenv{'internal.courseowner'} eq
                   9162:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   9163:                                $refused = '';
                   9164:                            }
                   9165:                        }
                   9166:                    }
                   9167:                }
                   9168:            }
                   9169:            if ($refused) {
                   9170:                &logthis('Refused custom assignrole: '.
                   9171:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   9172:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   9173:                return 'refused';
                   9174:            }
1.104     www      9175:         }
1.21      www      9176:         $mrole='cr';
1.678     raeburn  9177:     } elsif ($role =~ /^gr\//) {
                   9178:         my $cwogrp=$url;
1.811     albertel 9179:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  9180:         unless (&allowed('mdg',$cwogrp)) {
                   9181:             &logthis('Refused group assignrole: '.
                   9182:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   9183:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   9184:             return 'refused';
                   9185:         }
                   9186:         $mrole='gr';
1.21      www      9187:     } else {
1.82      www      9188:         my $cwosec=$url;
1.811     albertel 9189:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  9190:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   9191:             my $refused;
                   9192:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   9193:                 if (!(&allowed('c'.$role,$url))) {
                   9194:                     $refused = 1;
                   9195:                 }
                   9196:             } else {
                   9197:                 $refused = 1;
                   9198:             }
1.947     raeburn  9199:             if ($refused) {
1.1045    raeburn  9200:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9201:                 if (!$selfenroll && $context eq 'course') {
                   9202:                     my %crsenv;
                   9203:                     if ($role eq 'cc' || $role eq 'co') {
                   9204:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9205:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   9206:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   9207:                                 if ($crsenv{'internal.courseowner'} eq 
                   9208:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9209:                                     $refused = '';
                   9210:                                 }
                   9211:                             }
                   9212:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   9213:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   9214:                                 if ($crsenv{'internal.courseowner'} eq 
                   9215:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9216:                                     $refused = '';
                   9217:                                 }
                   9218:                             }
                   9219:                         }
                   9220:                     }
                   9221:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  9222:                     $refused = '';
1.1017    raeburn  9223:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  9224:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  9225:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  9226:                         my $wrongcc;
                   9227:                         if ($cnum =~ /^$match_community$/) {
                   9228:                             $wrongcc = 1 if ($role eq 'cc');
                   9229:                         } else {
                   9230:                             $wrongcc = 1 if ($role eq 'co');
                   9231:                         }
                   9232:                         unless ($wrongcc) {
                   9233:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9234:                             if ($crsenv{'internal.courseowner'} eq 
                   9235:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   9236:                                 $refused = '';
                   9237:                             }
1.1017    raeburn  9238:                         }
                   9239:                     }
1.1172.2.9  raeburn  9240:                 } elsif ($context eq 'requestauthor') {
                   9241:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   9242:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   9243:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   9244:                             $refused = '';
                   9245:                         } else {
                   9246:                             my %domdefaults = &get_domain_defaults($udom);
                   9247:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   9248:                                 my $checkbystatus;
                   9249:                                 if ($env{'user.adv'}) {
                   9250:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   9251:                                     if ($disposition eq 'automatic') {
                   9252:                                         $refused = '';
                   9253:                                     } elsif ($disposition eq '') {
                   9254:                                         $checkbystatus = 1;
                   9255:                                     }
                   9256:                                 } else {
                   9257:                                     $checkbystatus = 1;
                   9258:                                 }
                   9259:                                 if ($checkbystatus) {
                   9260:                                     if ($env{'environment.inststatus'}) {
                   9261:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   9262:                                         foreach my $type (@inststatuses) {
                   9263:                                             if (($type ne '') &&
                   9264:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   9265:                                                 $refused = '';
                   9266:                                             }
                   9267:                                         }
                   9268:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   9269:                                         $refused = '';
                   9270:                                     }
                   9271:                                 }
                   9272:                             }
                   9273:                         }
                   9274:                     }
1.1017    raeburn  9275:                 }
                   9276:                 if ($refused) {
1.947     raeburn  9277:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   9278:                              ' '.$role.' '.$end.' '.$start.' by '.
                   9279: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   9280:                     return 'refused';
                   9281:                 }
1.932     raeburn  9282:             }
1.1131    raeburn  9283:         } elsif ($role eq 'au') {
                   9284:             if ($url ne '/'.$udom.'/') {
                   9285:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   9286:                          ' to assign author role for '.$uname.':'.$udom.
                   9287:                          ' in domain: '.$url.' refused (wrong domain).');
                   9288:                 return 'refused';
                   9289:             }
1.104     www      9290:         }
1.21      www      9291:         $mrole=$role;
                   9292:     }
1.620     albertel 9293:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      9294:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      9295:     if ($end) { $command.='_'.$end; }
1.21      www      9296:     if ($start) {
                   9297: 	if ($end) { 
1.81      www      9298:            $command.='_'.$start; 
1.21      www      9299:         } else {
1.81      www      9300:            $command.='_0_'.$start;
1.21      www      9301:         }
                   9302:     }
1.739     raeburn  9303:     my $origstart = $start;
                   9304:     my $origend = $end;
1.957     raeburn  9305:     my $delflag;
1.357     www      9306: # actually delete
                   9307:     if ($deleteflag) {
1.373     www      9308: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      9309: # modify command to delete the role
1.620     albertel 9310:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      9311:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 9312: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      9313: # set start and finish to negative values for userrolelog
                   9314:            $start=-1;
                   9315:            $end=-1;
1.957     raeburn  9316:            $delflag = 1;
1.357     www      9317:         }
                   9318:     }
                   9319: # send command
1.349     www      9320:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      9321: # log new user role if status is ok
1.349     www      9322:     if ($answer eq 'ok') {
1.663     raeburn  9323: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  9324:         if (($role eq 'cc') || ($role eq 'in') ||
                   9325:             ($role eq 'ep') || ($role eq 'ad') ||
                   9326:             ($role eq 'ta') || ($role eq 'st') ||
                   9327:             ($role=~/^cr/) || ($role eq 'gr') ||
                   9328:             ($role eq 'co')) {
1.1172.2.13  raeburn  9329: # for course roles, perform group memberships changes triggered by role change.
                   9330:             unless ($role =~ /^gr/) {
                   9331:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   9332:                                                  $origstart,$selfenroll,$context);
                   9333:             }
1.1172.2.9  raeburn  9334:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9335:                            $selfenroll,$context);
                   9336:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90  raeburn  9337:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   9338:                  ($role eq 'da')) {
1.1172.2.9  raeburn  9339:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9340:                            $context);
                   9341:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   9342:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9343:                              $context);
                   9344:         }
1.1053    raeburn  9345:         if ($role eq 'cc') {
                   9346:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   9347:         }
1.349     www      9348:     }
                   9349:     return $answer;
1.169     harris41 9350: }
                   9351: 
1.1053    raeburn  9352: sub autoupdate_coowners {
                   9353:     my ($url,$end,$start,$uname,$udom) = @_;
                   9354:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   9355:     if (($cdom ne '') && ($cnum ne '')) {
                   9356:         my $now = time;
                   9357:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   9358:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   9359:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   9360:             my $instcode = $coursehash{'internal.coursecode'};
                   9361:             if ($instcode ne '') {
1.1056    raeburn  9362:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   9363:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  9364:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  9365:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   9366:                         if ($result eq 'valid') {
                   9367:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  9368:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9369:                                     push(@newcoowners,$coowner);
                   9370:                                 }
                   9371:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   9372:                                     push(@newcoowners,$uname.':'.$udom);
                   9373:                                 }
                   9374:                                 @newcoowners = sort(@newcoowners);
                   9375:                             } else {
                   9376:                                 push(@newcoowners,$uname.':'.$udom);
                   9377:                             }
                   9378:                         } else {
                   9379:                             if ($coursehash{'internal.co-owners'}) {
                   9380:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9381:                                     unless ($coowner eq $uname.':'.$udom) {
                   9382:                                         push(@newcoowners,$coowner);
                   9383:                                     }
                   9384:                                 }
                   9385:                                 unless (@newcoowners > 0) {
                   9386:                                     $delcoowners = 1;
                   9387:                                     $coowners = '';
                   9388:                                 }
                   9389:                             }
                   9390:                         }
                   9391:                         if (@newcoowners || $delcoowners) {
                   9392:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   9393:                                             $delcoowners,@newcoowners);
                   9394:                         }
                   9395:                     }
                   9396:                 }
                   9397:             }
                   9398:         }
                   9399:     }
                   9400: }
                   9401: 
                   9402: sub store_coowners {
                   9403:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   9404:     my $cid = $cdom.'_'.$cnum;
                   9405:     my ($coowners,$delresult,$putresult);
                   9406:     if (@newcoowners) {
                   9407:         $coowners = join(',',@newcoowners);
                   9408:         my %coownershash = (
                   9409:                             'internal.co-owners' => $coowners,
                   9410:                            );
                   9411:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   9412:         if ($putresult eq 'ok') {
                   9413:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   9414:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   9415:             }
                   9416:         }
                   9417:     }
                   9418:     if ($delcoowners) {
                   9419:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   9420:         if ($delresult eq 'ok') {
                   9421:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   9422:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   9423:             }
                   9424:         }
                   9425:     }
                   9426:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   9427:         my %crsinfo =
                   9428:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   9429:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   9430:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   9431:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   9432:         }
                   9433:     }
                   9434: }
                   9435: 
1.169     harris41 9436: # -------------------------------------------------- Modify user authentication
1.197     www      9437: # Overrides without validation
                   9438: 
1.169     harris41 9439: sub modifyuserauth {
                   9440:     my ($udom,$uname,$umode,$upass)=@_;
                   9441:     my $uhome=&homeserver($uname,$udom);
1.197     www      9442:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   9443:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 9444:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9445:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 9446:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   9447: 		     &escape($upass),$uhome);
1.620     albertel 9448:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      9449:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   9450:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   9451:     &log($udom,,$uname,$uhome,
1.620     albertel 9452:         'Authentication changed by '.$env{'user.domain'}.', '.
                   9453:                                      $env{'user.name'}.', '.$umode.
1.197     www      9454:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 9455:     unless ($reply eq 'ok') {
1.197     www      9456:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 9457: 	return 'error: '.$reply;
                   9458:     }   
1.170     harris41 9459:     return 'ok';
1.80      www      9460: }
                   9461: 
1.81      www      9462: # --------------------------------------------------------------- Modify a user
1.80      www      9463: 
1.81      www      9464: sub modifyuser {
1.206     matthew  9465:     my ($udom,    $uname, $uid,
                   9466:         $umode,   $upass, $first,
                   9467:         $middle,  $last,  $gene,
1.1058    raeburn  9468:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 9469:     $udom= &LONCAPA::clean_domain($udom);
                   9470:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  9471:     my $showcandelete = 'none';
                   9472:     if (ref($candelete) eq 'ARRAY') {
                   9473:         if (@{$candelete} > 0) {
                   9474:             $showcandelete = join(', ',@{$candelete});
                   9475:         }
                   9476:     }
1.81      www      9477:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      9478:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  9479: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  9480:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   9481:                                      ' desiredhome not specified'). 
1.620     albertel 9482:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9483:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 9484:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  9485:     my $newuser;
                   9486:     if ($uhome eq 'no_host') {
                   9487:         $newuser = 1;
                   9488:     }
1.80      www      9489: # ----------------------------------------------------------------- Create User
1.406     albertel 9490:     if (($uhome eq 'no_host') && 
                   9491: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      9492:         my $unhome='';
1.844     albertel 9493:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  9494:             $unhome = $desiredhome;
1.620     albertel 9495: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   9496: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  9497:         } else { # load balancing routine for determining $unhome
1.81      www      9498:             my $loadm=10000000;
1.841     albertel 9499: 	    my %servers = &get_servers($udom,'library');
                   9500: 	    foreach my $tryserver (keys(%servers)) {
                   9501: 		my $answer=reply('load',$tryserver);
                   9502: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   9503: 		    $loadm=$answer;
                   9504: 		    $unhome=$tryserver;
                   9505: 		}
1.80      www      9506: 	    }
                   9507:         }
                   9508:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  9509: 	    return 'error: unable to find a home server for '.$uname.
                   9510:                    ' in domain '.$udom;
1.80      www      9511:         }
                   9512:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   9513:                          &escape($upass),$unhome);
                   9514: 	unless ($reply eq 'ok') {
                   9515:             return 'error: '.$reply;
                   9516:         }   
1.230     stredwic 9517:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      9518:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  9519: 	    return 'error: unable verify users home machine.';
1.80      www      9520:         }
1.209     matthew  9521:     }   # End of creation of new user
1.80      www      9522: # ---------------------------------------------------------------------- Add ID
                   9523:     if ($uid) {
                   9524:        $uid=~tr/A-Z/a-z/;
                   9525:        my %uidhash=&idrget($udom,$uname);
1.196     www      9526:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   9527:          && (!$forceid)) {
1.80      www      9528: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  9529: 	      return 'error: user id "'.$uid.'" does not match '.
                   9530:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      9531:           }
                   9532:        } else {
                   9533: 	  &idput($udom,($uname => $uid));
                   9534:        }
                   9535:     }
                   9536: # -------------------------------------------------------------- Add names, etc
1.313     matthew  9537:     my @tmp=&get('environment',
1.899     raeburn  9538: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  9539:                     'permanentemail','inststatus'],
1.134     albertel 9540: 		   $udom,$uname);
1.1075    raeburn  9541:     my (%names,%oldnames);
1.313     matthew  9542:     if ($tmp[0] =~ m/^error:.*/) { 
                   9543:         %names=(); 
                   9544:     } else {
                   9545:         %names = @tmp;
1.1075    raeburn  9546:         %oldnames = %names;
1.313     matthew  9547:     }
1.388     www      9548: #
1.1058    raeburn  9549: # If name, email and/or uid are blank (e.g., because an uploaded file
                   9550: # of users did not contain them), do not overwrite existing values
                   9551: # unless field is in $candelete array ref.  
                   9552: #
                   9553: 
                   9554:     my @fields = ('firstname','middlename','lastname','generation',
                   9555:                   'permanentemail','id');
                   9556:     my %newvalues;
                   9557:     if (ref($candelete) eq 'ARRAY') {
                   9558:         foreach my $field (@fields) {
                   9559:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   9560:                 if ($field eq 'firstname') {
                   9561:                     $names{$field} = $first;
                   9562:                 } elsif ($field eq 'middlename') {
                   9563:                     $names{$field} = $middle;
                   9564:                 } elsif ($field eq 'lastname') {
                   9565:                     $names{$field} = $last;
                   9566:                 } elsif ($field eq 'generation') { 
                   9567:                     $names{$field} = $gene;
                   9568:                 } elsif ($field eq 'permanentemail') {
                   9569:                     $names{$field} = $email;
                   9570:                 } elsif ($field eq 'id') {
                   9571:                     $names{$field}  = $uid;
                   9572:                 }
                   9573:             }
                   9574:         }
                   9575:     }
1.388     www      9576:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  9577:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      9578:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  9579:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      9580:     if ($email) {
                   9581:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  9582:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      9583:     }
1.899     raeburn  9584:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  9585:     if (defined($inststatus)) {
                   9586:         $names{'inststatus'} = '';
                   9587:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   9588:         if (ref($usertypes) eq 'HASH') {
                   9589:             my @okstatuses; 
                   9590:             foreach my $item (split(/:/,$inststatus)) {
                   9591:                 if (defined($usertypes->{$item})) {
                   9592:                     push(@okstatuses,$item);  
                   9593:                 }
                   9594:             }
                   9595:             if (@okstatuses) {
                   9596:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   9597:             }
                   9598:         }
                   9599:     }
1.1075    raeburn  9600:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  9601:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  9602:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  9603:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   9604:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   9605:     } else {
                   9606:         $logmsg .= ' during self creation';
                   9607:     }
1.1075    raeburn  9608:     my $changed;
                   9609:     if ($newuser) {
                   9610:         $changed = 1;
                   9611:     } else {
                   9612:         foreach my $field (@fields) {
                   9613:             if ($names{$field} ne $oldnames{$field}) {
                   9614:                 $changed = 1;
                   9615:                 last;
                   9616:             }
                   9617:         }
                   9618:     }
                   9619:     unless ($changed) {
                   9620:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   9621:         &logthis($logmsg);
                   9622:         return 'ok';
                   9623:     }
                   9624:     my $reply = &put('environment', \%names, $udom,$uname);
                   9625:     if ($reply ne 'ok') { 
                   9626:         return 'error: '.$reply;
                   9627:     }
1.1087    raeburn  9628:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   9629:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   9630:     }
1.1075    raeburn  9631:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   9632:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   9633:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  9634:     &logthis($logmsg);
1.134     albertel 9635:     return 'ok';
1.80      www      9636: }
                   9637: 
1.81      www      9638: # -------------------------------------------------------------- Modify student
1.80      www      9639: 
1.81      www      9640: sub modifystudent {
                   9641:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  9642:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76  raeburn  9643:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 9644:     if (!$cid) {
1.620     albertel 9645: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9646: 	    return 'not_in_class';
                   9647: 	}
1.80      www      9648:     }
                   9649: # --------------------------------------------------------------- Make the user
1.81      www      9650:     my $reply=&modifyuser
1.209     matthew  9651: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  9652:          $desiredhome,$email,$inststatus);
1.80      www      9653:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  9654:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  9655:     # student's environment
1.297     matthew  9656:     $uid = undef if (!$forceid);
1.455     albertel 9657:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  9658: 					$gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76  raeburn  9659:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  9660:     return $reply;
                   9661: }
                   9662: 
                   9663: sub modify_student_enrollment {
1.1172.2.23  raeburn  9664:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76  raeburn  9665:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 9666:     my ($cdom,$cnum,$chome);
                   9667:     if (!$cid) {
1.620     albertel 9668: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9669: 	    return 'not_in_class';
                   9670: 	}
1.620     albertel 9671: 	$cdom=$env{'course.'.$cid.'.domain'};
                   9672: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 9673:     } else {
                   9674: 	($cdom,$cnum)=split(/_/,$cid);
                   9675:     }
1.620     albertel 9676:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 9677:     if (!$chome) {
1.457     raeburn  9678: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  9679:     }
1.455     albertel 9680:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  9681:     # Make sure the user exists
1.81      www      9682:     my $uhome=&homeserver($uname,$udom);
                   9683:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9684: 	return 'error: no such user';
                   9685:     }
1.297     matthew  9686:     # Get student data if we were not given enough information
                   9687:     if (!defined($first)  || $first  eq '' || 
                   9688:         !defined($last)   || $last   eq '' || 
                   9689:         !defined($uid)    || $uid    eq '' || 
                   9690:         !defined($middle) || $middle eq '' || 
                   9691:         !defined($gene)   || $gene   eq '') {
1.294     matthew  9692:         # They did not supply us with enough data to enroll the student, so
                   9693:         # we need to pick up more information.
1.297     matthew  9694:         my %tmp = &get('environment',
1.294     matthew  9695:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  9696:                        ,$udom,$uname);
                   9697: 
1.800     albertel 9698:         #foreach my $key (keys(%tmp)) {
                   9699:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 9700:         #}
1.294     matthew  9701:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   9702:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   9703:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  9704:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  9705:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   9706:     }
1.556     albertel 9707:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  9708:     my $user = "$uname:$udom";
                   9709:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 9710:     my $reply=cput('classlist',
1.1148    raeburn  9711: 		   {$user => 
1.1172.2.76  raeburn  9712: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 9713: 		   $cdom,$cnum);
1.1148    raeburn  9714:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   9715:         &devalidate_getsection_cache($udom,$uname,$cid);
                   9716:     } else { 
1.81      www      9717: 	return 'error: '.$reply;
                   9718:     }
1.297     matthew  9719:     # Add student role to user
1.83      www      9720:     my $uurl='/'.$cid;
1.81      www      9721:     $uurl=~s/\_/\//g;
                   9722:     if ($usec) {
                   9723: 	$uurl.='/'.$usec;
                   9724:     }
1.1148    raeburn  9725:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   9726:                              $selfenroll,$context);
                   9727:     if ($result ne 'ok') {
                   9728:         if ($old_entry{$user} ne '') {
                   9729:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   9730:         } else {
                   9731:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   9732:         }
                   9733:     }
                   9734:     return $result; 
1.21      www      9735: }
                   9736: 
1.556     albertel 9737: sub format_name {
                   9738:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   9739:     my $name;
                   9740:     if ($first ne 'lastname') {
                   9741: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   9742:     } else {
                   9743: 	if ($lastname=~/\S/) {
                   9744: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   9745: 	    $name=~s/\s+,/,/;
                   9746: 	} else {
                   9747: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   9748: 	}
                   9749:     }
                   9750:     $name=~s/^\s+//;
                   9751:     $name=~s/\s+$//;
                   9752:     $name=~s/\s+/ /g;
                   9753:     return $name;
                   9754: }
                   9755: 
1.84      www      9756: # ------------------------------------------------- Write to course preferences
                   9757: 
                   9758: sub writecoursepref {
                   9759:     my ($courseid,%prefs)=@_;
                   9760:     $courseid=~s/^\///;
                   9761:     $courseid=~s/\_/\//g;
                   9762:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   9763:     my $chome=homeserver($cnum,$cdomain);
                   9764:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   9765: 	return 'error: no such course';
                   9766:     }
                   9767:     my $cstring='';
1.800     albertel 9768:     foreach my $pref (keys(%prefs)) {
                   9769: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 9770:     }
1.84      www      9771:     $cstring=~s/\&$//;
                   9772:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   9773: }
                   9774: 
                   9775: # ---------------------------------------------------------- Make/modify course
                   9776: 
                   9777: sub createcourse {
1.741     raeburn  9778:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  9779:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      9780:     $url=&declutter($url);
                   9781:     my $cid='';
1.1028    raeburn  9782:     if ($context eq 'requestcourses') {
                   9783:         my $can_create = 0;
                   9784:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   9785:         if ($udom eq $ownerdom) {
                   9786:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   9787:                                   $context)) {
                   9788:                 $can_create = 1;
                   9789:             }
                   9790:         } else {
                   9791:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   9792:                                            $category);
                   9793:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   9794:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   9795:                 if (@curr > 0) {
                   9796:                     my @options = qw(approval validate autolimit);
                   9797:                     my $optregex = join('|',@options);
                   9798:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   9799:                         $can_create = 1;
                   9800:                     }
                   9801:                 }
                   9802:             }
                   9803:         }
                   9804:         if ($can_create) {
                   9805:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   9806:                 unless (&allowed('ccc',$udom)) {
                   9807:                     return 'refused'; 
                   9808:                 }
1.1017    raeburn  9809:             }
                   9810:         } else {
                   9811:             return 'refused';
                   9812:         }
1.1028    raeburn  9813:     } elsif (!&allowed('ccc',$udom)) {
                   9814:         return 'refused';
1.84      www      9815:     }
1.1011    raeburn  9816: # --------------------------------------------------------------- Get Unique ID
                   9817:     my $uname;
                   9818:     if ($cnum =~ /^$match_courseid$/) {
                   9819:         my $chome=&homeserver($cnum,$udom,'true');
                   9820:         if (($chome eq '') || ($chome eq 'no_host')) {
                   9821:             $uname = $cnum;
                   9822:         } else {
1.1038    raeburn  9823:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9824:         }
                   9825:     } else {
1.1038    raeburn  9826:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9827:     }
                   9828:     return $uname if ($uname =~ /^error/);
                   9829: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  9830:     if (!defined($course_server)) {
                   9831:         if (defined(&domain($udom,'primary'))) {
                   9832:             $course_server = &domain($udom,'primary');
                   9833:         } else {
                   9834:             $course_server = $env{'user.home'}; 
                   9835:         }
                   9836:     }
                   9837:     my %host_servers =
                   9838:         &Apache::lonnet::get_servers($udom,'library');
                   9839:     unless ($host_servers{$course_server}) {
                   9840:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  9841:     }
1.84      www      9842: # ------------------------------------------------------------- Make the course
                   9843:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  9844:                       $course_server);
1.84      www      9845:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  9846:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      9847:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9848: 	return 'error: no such course';
                   9849:     }
1.271     www      9850: # ----------------------------------------------------------------- Course made
1.516     raeburn  9851: # log existence
1.1029    raeburn  9852:     my $now = time;
1.918     raeburn  9853:     my $newcourse = {
                   9854:                     $udom.'_'.$uname => {
1.921     raeburn  9855:                                      description => $description,
                   9856:                                      inst_code   => $inst_code,
                   9857:                                      owner       => $course_owner,
                   9858:                                      type        => $crstype,
1.1029    raeburn  9859:                                      creator     => $env{'user.name'}.':'.
                   9860:                                                     $env{'user.domain'},
                   9861:                                      created     => $now,
                   9862:                                      context     => $context,
1.918     raeburn  9863:                                                 },
                   9864:                     };
1.921     raeburn  9865:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      9866: # set toplevel url
1.271     www      9867:     my $topurl=$url;
                   9868:     unless ($nonstandard) {
                   9869: # ------------------------------------------ For standard courses, make top url
                   9870:         my $mapurl=&clutter($url);
1.278     www      9871:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 9872:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      9873: <map>
                   9874: <resource id="1" type="start"></resource>
                   9875: <resource id="2" src="$mapurl"></resource>
                   9876: <resource id="3" type="finish"></resource>
                   9877: <link index="1" from="1" to="2"></link>
                   9878: <link index="2" from="2" to="3"></link>
                   9879: </map>
                   9880: ENDINITMAP
                   9881:         $topurl=&declutter(
1.638     albertel 9882:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      9883:                           );
                   9884:     }
                   9885: # ----------------------------------------------------------- Write preferences
1.84      www      9886:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  9887:                      ('description'              => $description,
                   9888:                       'url'                      => $topurl,
                   9889:                       'internal.creator'         => $env{'user.name'}.':'.
                   9890:                                                     $env{'user.domain'},
                   9891:                       'internal.created'         => $now,
                   9892:                       'internal.creationcontext' => $context)
                   9893:                     );
1.84      www      9894:     return '/'.$udom.'/'.$uname;
                   9895: }
                   9896: 
1.1011    raeburn  9897: # ------------------------------------------------------------------- Create ID
                   9898: sub generate_coursenum {
1.1038    raeburn  9899:     my ($udom,$crstype) = @_;
1.1011    raeburn  9900:     my $domdesc = &domain($udom);
                   9901:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  9902:     my $first;
                   9903:     if ($crstype eq 'Community') {
                   9904:         $first = '0';
                   9905:     } else {
                   9906:         $first = int(1+rand(9)); 
                   9907:     } 
                   9908:     my $uname=$first.
1.1011    raeburn  9909:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9910:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9911:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9912: # ----------------------------------------------- Make sure that does not exist
                   9913:     my $uhome=&homeserver($uname,$udom,'true');
                   9914:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  9915:         if ($crstype eq 'Community') {
                   9916:             $first = '0';
                   9917:         } else {
                   9918:             $first = int(1+rand(9));
                   9919:         }
                   9920:         $uname=$first.
1.1011    raeburn  9921:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9922:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9923:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9924:         $uhome=&homeserver($uname,$udom,'true');
                   9925:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   9926:             return 'error: unable to generate unique course-ID';
                   9927:         }
                   9928:     }
                   9929:     return $uname;
                   9930: }
                   9931: 
1.813     albertel 9932: sub is_course {
1.1167    droeschl 9933:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   9934:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
1.1172.2.95  raeburn  9935:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   9936:     my $uhome=&homeserver($cnum,$cdom);
                   9937:     my $iscourse;
                   9938:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   9939:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
                   9940:     } else {
                   9941:         my $hashid = $cdom.':'.$cnum;
                   9942:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   9943:         unless (defined($cached)) {
                   9944:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   9945:                                         $cnum,undef,undef,'.');
                   9946:             $iscourse = 0;
                   9947:             if (exists($courses{$cdom.'_'.$cnum})) {
                   9948:                 $iscourse = 1;
                   9949:             }
                   9950:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   9951:         }
                   9952:     }
                   9953:     return unless($iscourse);
1.1167    droeschl 9954:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 9955: }
                   9956: 
1.1015    raeburn  9957: sub store_userdata {
                   9958:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  9959:     my $result;
1.1016    raeburn  9960:     if ($datakey ne '') {
1.1013    raeburn  9961:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  9962:             if ($udom eq '' || $uname eq '') {
                   9963:                 $udom = $env{'user.domain'};
                   9964:                 $uname = $env{'user.name'};
                   9965:             }
                   9966:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  9967:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   9968:                 $result = 'error: no_host';
                   9969:             } else {
                   9970:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   9971:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   9972: 
                   9973:                 my $namevalue='';
                   9974:                 foreach my $key (keys(%{$storehash})) {
                   9975:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   9976:                 }
                   9977:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  9978:                 unless ($namespace eq 'courserequests') {
                   9979:                     $datakey = &escape($datakey);
                   9980:                 }
1.1105    raeburn  9981:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   9982:                                   $namevalue,$uhome);
1.1013    raeburn  9983:             }
                   9984:         } else {
                   9985:             $result = 'error: data to store was not a hash reference'; 
                   9986:         }
                   9987:     } else {
                   9988:         $result= 'error: invalid requestkey'; 
                   9989:     }
                   9990:     return $result;
                   9991: }
                   9992: 
1.21      www      9993: # ---------------------------------------------------------- Assign Custom Role
                   9994: 
                   9995: sub assigncustomrole {
1.957     raeburn  9996:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9997:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  9998:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      9999: }
                   10000: 
                   10001: # ----------------------------------------------------------------- Revoke Role
                   10002: 
                   10003: sub revokerole {
1.957     raeburn  10004:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10005:     my $now=time;
1.965     raeburn  10006:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      10007: }
                   10008: 
                   10009: # ---------------------------------------------------------- Revoke Custom Role
                   10010: 
                   10011: sub revokecustomrole {
1.957     raeburn  10012:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10013:     my $now=time;
1.357     www      10014:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  10015:            $deleteflag,$selfenroll,$context);
1.17      www      10016: }
                   10017: 
1.533     banghart 10018: # ------------------------------------------------------------ Disk usage
1.535     albertel 10019: sub diskusage {
1.955     raeburn  10020:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   10021:     $directorypath =~ s/\/$//;
                   10022:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   10023:                        .&escape($getpropath).':'.&escape($uname).':'
                   10024:                        .&escape($udom),homeserver($uname,$udom));
                   10025:     if ($listing eq 'unknown_cmd') {
                   10026:         if ($getpropath) {
                   10027:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   10028:         }
                   10029:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   10030:     }
1.514     albertel 10031:     return $listing;
1.512     banghart 10032: }
                   10033: 
1.566     banghart 10034: sub is_locked {
1.1096    raeburn  10035:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 10036:     my @check;
                   10037:     my $is_locked;
1.1093    raeburn  10038:     push (@check,$file_name);
1.613     albertel 10039:     my %locked = &get('file_permissions',\@check,
1.620     albertel 10040: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 10041:     my ($tmp)=keys(%locked);
                   10042:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  10043:     
1.566     banghart 10044:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  10045:         $is_locked = 'false';
                   10046:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  10047:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  10048:                $is_locked = 'true';
1.1096    raeburn  10049:                if (ref($which) eq 'ARRAY') {
                   10050:                    push(@{$which},$entry);
                   10051:                } else {
                   10052:                    last;
                   10053:                }
1.745     raeburn  10054:            }
                   10055:        }
1.566     banghart 10056:     } else {
                   10057:         $is_locked = 'false';
                   10058:     }
1.1093    raeburn  10059:     return $is_locked;
1.566     banghart 10060: }
                   10061: 
1.759     albertel 10062: sub declutter_portfile {
                   10063:     my ($file) = @_;
1.833     albertel 10064:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 10065:     return $file;
                   10066: }
                   10067: 
1.559     banghart 10068: # ------------------------------------------------------------- Mark as Read Only
                   10069: 
                   10070: sub mark_as_readonly {
                   10071:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 10072:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10073:     my ($tmp)=keys(%current_permissions);
                   10074:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 10075:     foreach my $file (@{$files}) {
1.759     albertel 10076: 	$file = &declutter_portfile($file);
1.561     banghart 10077:         push(@{$current_permissions{$file}},$what);
1.559     banghart 10078:     }
1.613     albertel 10079:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10080:     return;
                   10081: }
                   10082: 
1.572     banghart 10083: # ------------------------------------------------------------Save Selected Files
                   10084: 
                   10085: sub save_selected_files {
                   10086:     my ($user, $path, @files) = @_;
                   10087:     my $filename = $user."savedfiles";
1.573     banghart 10088:     my @other_files = &files_not_in_path($user, $path);
1.1172.2.96  raeburn  10089:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 10090:     foreach my $file (@files) {
1.620     albertel 10091:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 10092:     }
                   10093:     foreach my $file (@other_files) {
1.574     banghart 10094:         print (OUT $file."\n");
1.572     banghart 10095:     }
1.574     banghart 10096:     close (OUT);
1.572     banghart 10097:     return 'ok';
                   10098: }
                   10099: 
1.574     banghart 10100: sub clear_selected_files {
                   10101:     my ($user) = @_;
                   10102:     my $filename = $user."savedfiles";
1.1172.2.96  raeburn  10103:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 10104:     print (OUT undef);
                   10105:     close (OUT);
                   10106:     return ("ok");    
                   10107: }
                   10108: 
1.572     banghart 10109: sub files_in_path {
                   10110:     my ($user, $path) = @_;
                   10111:     my $filename = $user."savedfiles";
                   10112:     my %return_files;
1.1172.2.96  raeburn  10113:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 10114:     while (my $line_in = <IN>) {
1.574     banghart 10115:         chomp ($line_in);
                   10116:         my @paths_and_file = split (m!/!, $line_in);
                   10117:         my $file_part = pop (@paths_and_file);
                   10118:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 10119:         $path_part.='/';
                   10120:         my $path_and_file = $path_part.$file_part;
                   10121:         if ($path_part eq $path) {
                   10122:             $return_files{$file_part}= 'selected';
                   10123:         }
                   10124:     }
1.574     banghart 10125:     close (IN);
                   10126:     return (\%return_files);
1.572     banghart 10127: }
                   10128: 
                   10129: # called in portfolio select mode, to show files selected NOT in current directory
                   10130: sub files_not_in_path {
                   10131:     my ($user, $path) = @_;
                   10132:     my $filename = $user."savedfiles";
                   10133:     my @return_files;
                   10134:     my $path_part;
1.1172.2.96  raeburn  10135:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 10136:     while (my $line = <IN>) {
1.572     banghart 10137:         #ok, I know it's clunky, but I want it to work
1.800     albertel 10138:         my @paths_and_file = split(m|/|, $line);
                   10139:         my $file_part = pop(@paths_and_file);
                   10140:         chomp($file_part);
                   10141:         my $path_part = join('/', @paths_and_file);
1.572     banghart 10142:         $path_part .= '/';
                   10143:         my $path_and_file = $path_part.$file_part;
                   10144:         if ($path_part ne $path) {
1.800     albertel 10145:             push(@return_files, ($path_and_file));
1.572     banghart 10146:         }
                   10147:     }
1.800     albertel 10148:     close(OUT);
1.574     banghart 10149:     return (@return_files);
1.572     banghart 10150: }
                   10151: 
1.745     raeburn  10152: #----------------------------------------------Get portfolio file permissions
1.629     banghart 10153: 
1.745     raeburn  10154: sub get_portfile_permissions {
                   10155:     my ($domain,$user) = @_;
1.613     albertel 10156:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10157:     my ($tmp)=keys(%current_permissions);
                   10158:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10159:     return \%current_permissions;
                   10160: }
                   10161: 
                   10162: #---------------------------------------------Get portfolio file access controls
                   10163: 
1.749     raeburn  10164: sub get_access_controls {
1.745     raeburn  10165:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 10166:     my %access;
                   10167:     my $real_file = $file;
                   10168:     $file =~ s/\.meta$//;
1.745     raeburn  10169:     if (defined($file)) {
1.749     raeburn  10170:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   10171:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 10172:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  10173:             }
                   10174:         }
1.745     raeburn  10175:     } else {
1.749     raeburn  10176:         foreach my $key (keys(%{$current_permissions})) {
                   10177:             if ($key =~ /\0accesscontrol$/) {
                   10178:                 if (defined($group)) {
                   10179:                     if ($key !~ m-^\Q$group\E/-) {
                   10180:                         next;
                   10181:                     }
                   10182:                 }
                   10183:                 my ($fullpath) = split(/\0/,$key);
                   10184:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   10185:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   10186:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   10187:                     }
                   10188:                 }
                   10189:             }
                   10190:         }
                   10191:     }
                   10192:     return %access;
                   10193: }
                   10194: 
                   10195: sub modify_access_controls {
                   10196:     my ($file_name,$changes,$domain,$user)=@_;
                   10197:     my ($outcome,$deloutcome);
                   10198:     my %store_permissions;
                   10199:     my %new_values;
                   10200:     my %new_control;
                   10201:     my %translation;
                   10202:     my @deletions = ();
                   10203:     my $now = time;
                   10204:     if (exists($$changes{'activate'})) {
                   10205:         if (ref($$changes{'activate'}) eq 'HASH') {
                   10206:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   10207:             my $numnew = scalar(@newitems);
                   10208:             for (my $i=0; $i<$numnew; $i++) {
                   10209:                 my $newkey = $newitems[$i];
                   10210:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  10211:                 if ($newkey =~ /^\d+:/) { 
                   10212:                     $newkey =~ s/^(\d+)/$newid/;
                   10213:                     $translation{$1} = $newid;
                   10214:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   10215:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   10216:                     $translation{$1} = $newid;
                   10217:                 }
1.749     raeburn  10218:                 $new_values{$file_name."\0".$newkey} = 
                   10219:                                           $$changes{'activate'}{$newitems[$i]};
                   10220:                 $new_control{$newkey} = $now;
                   10221:             }
                   10222:         }
                   10223:     }
                   10224:     my %todelete;
                   10225:     my %changed_items;
                   10226:     foreach my $action ('delete','update') {
                   10227:         if (exists($$changes{$action})) {
                   10228:             if (ref($$changes{$action}) eq 'HASH') {
                   10229:                 foreach my $key (keys(%{$$changes{$action}})) {
                   10230:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   10231:                     if ($action eq 'delete') { 
                   10232:                         $todelete{$itemnum} = 1;
                   10233:                     } else {
                   10234:                         $changed_items{$itemnum} = $key;
                   10235:                     }
                   10236:                 }
1.745     raeburn  10237:             }
                   10238:         }
1.749     raeburn  10239:     }
                   10240:     # get lock on access controls for file.
                   10241:     my $lockhash = {
                   10242:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   10243:                                                        ':'.$env{'user.domain'},
                   10244:                    }; 
                   10245:     my $tries = 0;
                   10246:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10247:    
1.1172.2.79  raeburn  10248:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  10249:         $tries ++;
1.1172.2.79  raeburn  10250:         sleep(0.1);
1.749     raeburn  10251:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10252:     }
                   10253:     if ($gotlock eq 'ok') {
                   10254:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   10255:         my ($tmp)=keys(%curr_permissions);
                   10256:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   10257:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   10258:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   10259:             if (ref($curr_controls) eq 'HASH') {
                   10260:                 foreach my $control_item (keys(%{$curr_controls})) {
                   10261:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   10262:                     if (defined($todelete{$itemnum})) {
                   10263:                         push(@deletions,$file_name."\0".$control_item);
                   10264:                     } else {
                   10265:                         if (defined($changed_items{$itemnum})) {
                   10266:                             $new_control{$changed_items{$itemnum}} = $now;
                   10267:                             push(@deletions,$file_name."\0".$control_item);
                   10268:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   10269:                         } else {
                   10270:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   10271:                         }
                   10272:                     }
1.745     raeburn  10273:                 }
                   10274:             }
                   10275:         }
1.970     raeburn  10276:         my ($group);
                   10277:         if (&is_course($domain,$user)) {
                   10278:             ($group,my $file) = split(/\//,$file_name,2);
                   10279:         }
1.749     raeburn  10280:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   10281:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   10282:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   10283:         #  remove lock
                   10284:         my @del_lock = ($file_name."\0".'locked_access_records');
                   10285:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  10286:         my $sqlresult =
1.970     raeburn  10287:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  10288:                                     $group);
1.749     raeburn  10289:     } else {
                   10290:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  10291:     }
1.749     raeburn  10292:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  10293: }
                   10294: 
1.827     raeburn  10295: sub make_public_indefinitely {
                   10296:     my ($requrl) = @_;
                   10297:     my $now = time;
                   10298:     my $action = 'activate';
                   10299:     my $aclnum = 0;
                   10300:     if (&is_portfolio_url($requrl)) {
                   10301:         my (undef,$udom,$unum,$file_name,$group) =
                   10302:             &parse_portfolio_url($requrl);
                   10303:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   10304:         my %access_controls = &get_access_controls($current_perms,
                   10305:                                                    $group,$file_name);
                   10306:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   10307:             my ($num,$scope,$end,$start) = 
                   10308:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   10309:             if ($scope eq 'public') {
                   10310:                 if ($start <= $now && $end == 0) {
                   10311:                     $action = 'none';
                   10312:                 } else {
                   10313:                     $action = 'update';
                   10314:                     $aclnum = $num;
                   10315:                 }
                   10316:                 last;
                   10317:             }
                   10318:         }
                   10319:         if ($action eq 'none') {
                   10320:              return 'ok';
                   10321:         } else {
                   10322:             my %changes;
                   10323:             my $newend = 0;
                   10324:             my $newstart = $now;
                   10325:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   10326:             $changes{$action}{$newkey} = {
                   10327:                 type => 'public',
                   10328:                 time => {
                   10329:                     start => $newstart,
                   10330:                     end   => $newend,
                   10331:                 },
                   10332:             };
                   10333:             my ($outcome,$deloutcome,$new_values,$translation) =
                   10334:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   10335:             return $outcome;
                   10336:         }
                   10337:     } else {
                   10338:         return 'invalid';
                   10339:     }
                   10340: }
                   10341: 
1.745     raeburn  10342: #------------------------------------------------------Get Marked as Read Only
                   10343: 
                   10344: sub get_marked_as_readonly {
                   10345:     my ($domain,$user,$what,$group) = @_;
                   10346:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 10347:     my @readonly_files;
1.629     banghart 10348:     my $cmp1=$what;
                   10349:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  10350:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10351:         if (defined($group)) {
                   10352:             if ($file_name !~ m-^\Q$group\E/-) {
                   10353:                 next;
                   10354:             }
                   10355:         }
1.561     banghart 10356:         if (ref($value) eq "ARRAY"){
                   10357:             foreach my $stored_what (@{$value}) {
1.629     banghart 10358:                 my $cmp2=$stored_what;
1.759     albertel 10359:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  10360:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  10361:                 }
1.629     banghart 10362:                 if ($cmp1 eq $cmp2) {
1.561     banghart 10363:                     push(@readonly_files, $file_name);
1.745     raeburn  10364:                     last;
1.563     banghart 10365:                 } elsif (!defined($what)) {
                   10366:                     push(@readonly_files, $file_name);
1.745     raeburn  10367:                     last;
1.561     banghart 10368:                 }
                   10369:             }
1.745     raeburn  10370:         }
1.561     banghart 10371:     }
                   10372:     return @readonly_files;
                   10373: }
1.577     banghart 10374: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 10375: 
1.577     banghart 10376: sub get_marked_as_readonly_hash {
1.745     raeburn  10377:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 10378:     my %readonly_files;
1.745     raeburn  10379:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10380:         if (defined($group)) {
                   10381:             if ($file_name !~ m-^\Q$group\E/-) {
                   10382:                 next;
                   10383:             }
                   10384:         }
1.577     banghart 10385:         if (ref($value) eq "ARRAY"){
                   10386:             foreach my $stored_what (@{$value}) {
1.745     raeburn  10387:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 10388:                     foreach my $lock_descriptor(@{$stored_what}) {
                   10389:                         if ($lock_descriptor eq 'graded') {
                   10390:                             $readonly_files{$file_name} = 'graded';
                   10391:                         } elsif ($lock_descriptor eq 'handback') {
                   10392:                             $readonly_files{$file_name} = 'handback';
                   10393:                         } else {
                   10394:                             if (!exists($readonly_files{$file_name})) {
                   10395:                                 $readonly_files{$file_name} = 'locked';
                   10396:                             }
                   10397:                         }
1.745     raeburn  10398:                     }
1.750     banghart 10399:                 } 
1.577     banghart 10400:             }
                   10401:         } 
                   10402:     }
                   10403:     return %readonly_files;
                   10404: }
1.559     banghart 10405: # ------------------------------------------------------------ Unmark as Read Only
                   10406: 
                   10407: sub unmark_as_readonly {
1.629     banghart 10408:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   10409:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  10410:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 10411:     $file_name = &declutter_portfile($file_name);
1.634     albertel 10412:     my $symb_crs = $what;
                   10413:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  10414:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 10415:     my ($tmp)=keys(%current_permissions);
                   10416:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10417:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 10418:     foreach my $file (@readonly_files) {
1.759     albertel 10419: 	my $clean_file = &declutter_portfile($file);
                   10420: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 10421: 	my $current_locks = $current_permissions{$file};
1.563     banghart 10422:         my @new_locks;
                   10423:         my @del_keys;
                   10424:         if (ref($current_locks) eq "ARRAY"){
                   10425:             foreach my $locker (@{$current_locks}) {
1.632     albertel 10426:                 my $compare=$locker;
1.749     raeburn  10427:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  10428:                     $compare=join('',@{$locker});
1.746     raeburn  10429:                     if ($compare ne $symb_crs) {
                   10430:                         push(@new_locks, $locker);
                   10431:                     }
1.563     banghart 10432:                 }
                   10433:             }
1.650     albertel 10434:             if (scalar(@new_locks) > 0) {
1.563     banghart 10435:                 $current_permissions{$file} = \@new_locks;
                   10436:             } else {
                   10437:                 push(@del_keys, $file);
1.613     albertel 10438:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 10439:                 delete($current_permissions{$file});
1.563     banghart 10440:             }
                   10441:         }
1.561     banghart 10442:     }
1.613     albertel 10443:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10444:     return;
                   10445: }
1.512     banghart 10446: 
1.17      www      10447: # ------------------------------------------------------------ Directory lister
                   10448: 
                   10449: sub dirlist {
1.955     raeburn  10450:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      10451:     $uri=~s/^\///;
                   10452:     $uri=~s/\/$//;
1.253     stredwic 10453:     my ($udom, $uname);
1.955     raeburn  10454:     if ($getuserdir) {
1.253     stredwic 10455:         $udom = $userdomain;
                   10456:         $uname = $username;
1.955     raeburn  10457:     } else {
                   10458:         (undef,$udom,$uname)=split(/\//,$uri);
                   10459:         if(defined($userdomain)) {
                   10460:             $udom = $userdomain;
                   10461:         }
                   10462:         if(defined($username)) {
                   10463:             $uname = $username;
                   10464:         }
1.253     stredwic 10465:     }
1.955     raeburn  10466:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 10467: 
1.955     raeburn  10468:     $dirRoot = $perlvar{'lonDocRoot'};
                   10469:     if (defined($getpropath)) {
                   10470:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 10471:         $dirRoot =~ s/\/$//;
1.955     raeburn  10472:     } elsif (defined($getuserdir)) {
                   10473:         my $subdir=$uname.'__';
                   10474:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   10475:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   10476:                    ."/$udom/$subdir/$uname";
                   10477:     } elsif (defined($alternateRoot)) {
                   10478:         $dirRoot = $alternateRoot;
1.751     banghart 10479:     }
1.253     stredwic 10480: 
                   10481:     if($udom) {
                   10482:         if($uname) {
1.1135    raeburn  10483:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  10484:             if ($uhome eq 'no_host') {
                   10485:                 return ([],'no_host');
                   10486:             }
1.955     raeburn  10487:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  10488:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  10489:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  10490:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10491:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  10492:             } else {
                   10493:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10494:             }
1.605     matthew  10495:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10496:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  10497:                 @listing_results = split(/:/,$listing);
                   10498:             } else {
                   10499:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10500:             }
1.1135    raeburn  10501:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  10502:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10503:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10504:                 return ([],$listing);
                   10505:             } else {
                   10506:                 return (\@listing_results);
1.1135    raeburn  10507:             }
1.955     raeburn  10508:         } elsif(!$alternateRoot) {
1.1136    raeburn  10509:             my (%allusers,%listerror);
1.841     albertel 10510: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  10511:  	    foreach my $tryserver (keys(%servers)) {
                   10512:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   10513:                                   &escape($udom),$tryserver);
                   10514:                 if ($listing eq 'unknown_cmd') {
                   10515: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10516: 				      $udom, $tryserver);
                   10517:                 } else {
                   10518:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10519:                 }
1.841     albertel 10520: 		if ($listing eq 'unknown_cmd') {
                   10521: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10522: 				      $udom, $tryserver);
                   10523: 		    @listing_results = split(/:/,$listing);
                   10524: 		} else {
                   10525: 		    @listing_results =
                   10526: 			map { &unescape($_); } split(/:/,$listing);
                   10527: 		}
1.1136    raeburn  10528:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   10529:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10530:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10531:                     $listerror{$tryserver} = $listing;
                   10532:                 } else {
1.841     albertel 10533: 		    foreach my $line (@listing_results) {
                   10534: 			my ($entry) = split(/&/,$line,2);
                   10535: 			$allusers{$entry} = 1;
                   10536: 		    }
                   10537: 		}
1.253     stredwic 10538:             }
1.1136    raeburn  10539:             my @alluserslist=();
1.800     albertel 10540:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  10541:                 push(@alluserslist,$user.'&user');
1.253     stredwic 10542:             }
1.1172.2.80  raeburn  10543:             if (!%listerror) {
                   10544:                 # no errors
                   10545:                 return (\@alluserslist);
                   10546:             } elsif (scalar(keys(%servers)) == 1) {
                   10547:                 # one library server, one error
                   10548:                 my ($key) = keys(%listerror);
                   10549:                 return (\@alluserslist, $listerror{$key});
                   10550:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   10551:                 # con_lost indicates that we might miss data from at least one
                   10552:                 # library server
                   10553:                 return (\@alluserslist, 'con_lost');
                   10554:             } else {
                   10555:                 # multiple library servers and no con_lost -> data should be
                   10556:                 # complete.
                   10557:                 return (\@alluserslist);
                   10558:             }
                   10559: 
1.253     stredwic 10560:         } else {
1.1136    raeburn  10561:             return ([],'missing username');
1.253     stredwic 10562:         }
1.955     raeburn  10563:     } elsif(!defined($getpropath)) {
1.1136    raeburn  10564:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   10565:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   10566:         return (\@all_domains);
1.955     raeburn  10567:     } else {
1.1136    raeburn  10568:         return ([],'missing domain');
1.275     stredwic 10569:     }
                   10570: }
                   10571: 
                   10572: # --------------------------------------------- GetFileTimestamp
                   10573: # This function utilizes dirlist and returns the date stamp for
                   10574: # when it was last modified.  It will also return an error of -1
                   10575: # if an error occurs
                   10576: 
                   10577: sub GetFileTimestamp {
1.955     raeburn  10578:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 10579:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   10580:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  10581:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   10582:                                     undef,$getuserdir);
                   10583:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10584:         return -1;
                   10585:     }
                   10586:     if (ref($fileref) eq 'ARRAY') {
                   10587:         my @stats = split('&',$fileref->[0]);
1.375     matthew  10588:         # @stats contains first the filename, then the stat output
                   10589:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 10590:     } else {
                   10591:         return -1;
1.253     stredwic 10592:     }
1.26      www      10593: }
                   10594: 
1.712     albertel 10595: sub stat_file {
                   10596:     my ($uri) = @_;
1.787     albertel 10597:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 10598: 
1.955     raeburn  10599:     my ($udom,$uname,$file);
1.712     albertel 10600:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   10601: 	($udom,$uname,$file) =
1.811     albertel 10602: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 10603: 	$file = 'userfiles/'.$file;
                   10604:     }
                   10605:     if ($uri =~ m-^/res/-) {
                   10606: 	($udom,$uname) = 
1.807     albertel 10607: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 10608: 	$file = $uri;
                   10609:     }
                   10610: 
                   10611:     if (!$udom || !$uname || !$file) {
                   10612: 	# unable to handle the uri
                   10613: 	return ();
                   10614:     }
1.956     raeburn  10615:     my $getpropath;
                   10616:     if ($file =~ /^userfiles\//) {
                   10617:         $getpropath = 1;
                   10618:     }
1.1136    raeburn  10619:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   10620:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10621:         return ();
                   10622:     } else {
                   10623:         if (ref($listref) eq 'ARRAY') {
                   10624:             my @stats = split('&',$listref->[0]);
                   10625: 	    shift(@stats); #filename is first
                   10626: 	    return @stats;
                   10627:         }
1.712     albertel 10628:     }
                   10629:     return ();
                   10630: }
                   10631: 
1.26      www      10632: # -------------------------------------------------------- Value of a Condition
                   10633: 
1.713     albertel 10634: # gets the value of a specific preevaluated condition
                   10635: #    stored in the string  $env{user.state.<cid>}
                   10636: # or looks up a condition reference in the bighash and if if hasn't
                   10637: # already been evaluated recurses into docondval to get the value of
                   10638: # the condition, then memoizing it to 
                   10639: #   $env{user.state.<cid>.<condition>}
1.40      www      10640: sub directcondval {
                   10641:     my $number=shift;
1.620     albertel 10642:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 10643: 	&Apache::lonuserstate::evalstate();
                   10644:     }
1.713     albertel 10645:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   10646: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   10647:     } elsif ($number =~ /^_/) {
                   10648: 	my $sub_condition;
                   10649: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10650: 		&GDBM_READER(),0640)) {
                   10651: 	    $sub_condition=$bighash{'conditions'.$number};
                   10652: 	    untie(%bighash);
                   10653: 	}
                   10654: 	my $value = &docondval($sub_condition);
1.949     raeburn  10655: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 10656: 	return $value;
                   10657:     }
1.620     albertel 10658:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   10659:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      10660:     } else {
                   10661:        return 2;
                   10662:     }
                   10663: }
                   10664: 
1.713     albertel 10665: # get the collection of conditions for this resource
1.26      www      10666: sub condval {
                   10667:     my $condidx=shift;
1.54      www      10668:     my $allpathcond='';
1.713     albertel 10669:     foreach my $cond (split(/\|/,$condidx)) {
                   10670: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   10671: 	    $allpathcond.=
                   10672: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   10673: 	}
1.191     harris41 10674:     }
1.54      www      10675:     $allpathcond=~s/\|$//;
1.713     albertel 10676:     return &docondval($allpathcond);
                   10677: }
                   10678: 
                   10679: #evaluates an expression of conditions
                   10680: sub docondval {
                   10681:     my ($allpathcond) = @_;
                   10682:     my $result=0;
                   10683:     if ($env{'request.course.id'}
                   10684: 	&& defined($allpathcond)) {
                   10685: 	my $operand='|';
                   10686: 	my @stack;
                   10687: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   10688: 	    if ($chunk eq '(') {
                   10689: 		push @stack,($operand,$result);
                   10690: 	    } elsif ($chunk eq ')') {
                   10691: 		my $before=pop @stack;
                   10692: 		if (pop @stack eq '&') {
                   10693: 		    $result=$result>$before?$before:$result;
                   10694: 		} else {
                   10695: 		    $result=$result>$before?$result:$before;
                   10696: 		}
                   10697: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   10698: 		$operand=$chunk;
                   10699: 	    } else {
                   10700: 		my $new=directcondval($chunk);
                   10701: 		if ($operand eq '&') {
                   10702: 		    $result=$result>$new?$new:$result;
                   10703: 		} else {
                   10704: 		    $result=$result>$new?$result:$new;
                   10705: 		}
                   10706: 	    }
                   10707: 	}
1.26      www      10708:     }
                   10709:     return $result;
1.421     albertel 10710: }
                   10711: 
                   10712: # ---------------------------------------------------- Devalidate courseresdata
                   10713: 
                   10714: sub devalidatecourseresdata {
                   10715:     my ($coursenum,$coursedomain)=@_;
                   10716:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10717:     &devalidate_cache_new('courseres',$hashid);
1.28      www      10718: }
                   10719: 
1.763     www      10720: 
1.200     www      10721: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     10722: #
                   10723: #  Parameters:
                   10724: #      $coursenum    - Number of the course.
                   10725: #      $coursedomain - Domain at which the course was created.
                   10726: #  Returns:
                   10727: #     A hash of the course parameters along (I think) with timestamps
                   10728: #     and version info.
1.877     foxr     10729: 
1.624     albertel 10730: sub get_courseresdata {
                   10731:     my ($coursenum,$coursedomain)=@_;
1.200     www      10732:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   10733:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10734:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 10735:     my %dumpreply;
1.417     albertel 10736:     unless (defined($cached)) {
1.624     albertel 10737: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 10738: 	$result=\%dumpreply;
1.251     albertel 10739: 	my ($tmp) = keys(%dumpreply);
                   10740: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 10741: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 10742: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   10743: 	    return $tmp;
1.416     albertel 10744: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 10745: 	    $result=undef;
1.599     albertel 10746: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 10747: 	}
                   10748:     }
1.624     albertel 10749:     return $result;
                   10750: }
                   10751: 
1.633     albertel 10752: sub devalidateuserresdata {
                   10753:     my ($uname,$udom)=@_;
                   10754:     my $hashid="$udom:$uname";
                   10755:     &devalidate_cache_new('userres',$hashid);
                   10756: }
                   10757: 
1.624     albertel 10758: sub get_userresdata {
                   10759:     my ($uname,$udom)=@_;
                   10760:     #most student don\'t have any data set, check if there is some data
                   10761:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   10762: 
                   10763:     my $hashid="$udom:$uname";
                   10764:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   10765:     if (!defined($cached)) {
                   10766: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   10767: 	$result=\%resourcedata;
                   10768: 	&do_cache_new('userres',$hashid,$result,600);
                   10769:     }
                   10770:     my ($tmp)=keys(%$result);
                   10771:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   10772: 	return $result;
                   10773:     }
                   10774:     #error 2 occurs when the .db doesn't exist
                   10775:     if ($tmp!~/error: 2 /) {
1.1172.2.71  raeburn  10776:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   10777: 	    &logthis("<font color=\"blue\">WARNING:".
                   10778: 		     " Trying to get resource data for ".
                   10779: 		     $uname." at ".$udom.": ".
                   10780: 		     $tmp."</font>");
                   10781:         }
1.624     albertel 10782:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 10783: 	#&EXT_cache_set($udom,$uname);
                   10784: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 10785: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 10786:     }
                   10787:     return $tmp;
                   10788: }
1.879     foxr     10789: #----------------------------------------------- resdata - return resource data
                   10790: #  Purpose:
                   10791: #    Return resource data for either users or for a course.
                   10792: #  Parameters:
                   10793: #     $name      - Course/user name.
                   10794: #     $domain    - Name of the domain the user/course is registered on.
                   10795: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   10796: #     @which     - Array of names of resources desired.
                   10797: #  Returns:
                   10798: #     The value of the first reasource in @which that is found in the
                   10799: #     resource hash.
                   10800: #  Exceptional Conditions:
                   10801: #     If the $type passed in is not valid (not the string 'course' or 
                   10802: #     'user', an undefined  reference is returned.
                   10803: #     If none of the resources are found, an undef is returned
1.624     albertel 10804: sub resdata {
                   10805:     my ($name,$domain,$type,@which)=@_;
                   10806:     my $result;
                   10807:     if ($type eq 'course') {
                   10808: 	$result=&get_courseresdata($name,$domain);
                   10809:     } elsif ($type eq 'user') {
                   10810: 	$result=&get_userresdata($name,$domain);
                   10811:     }
                   10812:     if (!ref($result)) { return $result; }    
1.251     albertel 10813:     foreach my $item (@which) {
1.927     albertel 10814: 	if (defined($result->{$item->[0]})) {
                   10815: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 10816: 	}
1.250     albertel 10817:     }
1.291     albertel 10818:     return undef;
1.200     www      10819: }
                   10820: 
1.1172.2.31  raeburn  10821: sub get_numsuppfiles {
                   10822:     my ($cnum,$cdom,$ignorecache)=@_;
                   10823:     my $hashid=$cnum.':'.$cdom;
                   10824:     my ($suppcount,$cached);
                   10825:     unless ($ignorecache) {
                   10826:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   10827:     }
                   10828:     unless (defined($cached)) {
                   10829:         my $chome=&homeserver($cnum,$cdom);
                   10830:         unless ($chome eq 'no_host') {
                   10831:             ($suppcount,my $errors) = (0,0);
                   10832:             my $suppmap = 'supplemental.sequence';
                   10833:             ($suppcount,$errors) =
                   10834:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   10835:         }
                   10836:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   10837:     }
                   10838:     return $suppcount;
                   10839: }
                   10840: 
1.379     matthew  10841: #
                   10842: # EXT resource caching routines
                   10843: #
                   10844: 
                   10845: sub clear_EXT_cache_status {
1.383     albertel 10846:     &delenv('cache.EXT.');
1.379     matthew  10847: }
                   10848: 
                   10849: sub EXT_cache_status {
                   10850:     my ($target_domain,$target_user) = @_;
1.383     albertel 10851:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 10852:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  10853:         # We know already the user has no data
                   10854:         return 1;
                   10855:     } else {
                   10856:         return 0;
                   10857:     }
                   10858: }
                   10859: 
                   10860: sub EXT_cache_set {
                   10861:     my ($target_domain,$target_user) = @_;
1.383     albertel 10862:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  10863:     #&appenv({$cachename => time});
1.379     matthew  10864: }
                   10865: 
1.28      www      10866: # --------------------------------------------------------- Value of a Variable
1.58      www      10867: sub EXT {
1.715     albertel 10868: 
1.1172.2.28  raeburn  10869:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      10870:     unless ($varname) { return ''; }
1.218     albertel 10871:     #get real user name/domain, courseid and symb
                   10872:     my $courseid;
1.359     albertel 10873:     my $publicuser;
1.427     www      10874:     if ($symbparm) {
                   10875: 	$symbparm=&get_symb_from_alias($symbparm);
                   10876:     }
1.218     albertel 10877:     if (!($uname && $udom)) {
1.790     albertel 10878:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 10879:       if (!$symbparm) {	$symbparm=$cursymb; }
                   10880:     } else {
1.620     albertel 10881: 	$courseid=$env{'request.course.id'};
1.218     albertel 10882:     }
1.48      www      10883:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   10884:     my $rest;
1.320     albertel 10885:     if (defined($therest[0])) {
1.48      www      10886:        $rest=join('.',@therest);
                   10887:     } else {
                   10888:        $rest='';
                   10889:     }
1.320     albertel 10890: 
1.57      www      10891:     my $qualifierrest=$qualifier;
                   10892:     if ($rest) { $qualifierrest.='.'.$rest; }
                   10893:     my $spacequalifierrest=$space;
                   10894:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      10895:     if ($realm eq 'user') {
1.48      www      10896: # --------------------------------------------------------------- user.resource
                   10897: 	if ($space eq 'resource') {
1.651     albertel 10898: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   10899: 		  || defined($Apache::lonhomework::parsing_a_task))
                   10900: 		 &&
1.744     albertel 10901: 		 ($symbparm eq &symbread()) ) {	
                   10902: 		# if we are in the middle of processing the resource the
                   10903: 		# get the value we are planning on committing
                   10904:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   10905:                     return $Apache::lonhomework::results{$qualifierrest};
                   10906:                 } else {
                   10907:                     return $Apache::lonhomework::history{$qualifierrest};
                   10908:                 }
1.335     albertel 10909: 	    } else {
1.359     albertel 10910: 		my %restored;
1.620     albertel 10911: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 10912: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   10913: 		} else {
                   10914: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   10915: 		}
1.335     albertel 10916: 		return $restored{$qualifierrest};
                   10917: 	    }
1.48      www      10918: # ----------------------------------------------------------------- user.access
                   10919:         } elsif ($space eq 'access') {
1.218     albertel 10920: 	    # FIXME - not supporting calls for a specific user
1.48      www      10921:             return &allowed($qualifier,$rest);
                   10922: # ------------------------------------------ user.preferences, user.environment
                   10923:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 10924: 	    if (($uname eq $env{'user.name'}) &&
                   10925: 		($udom eq $env{'user.domain'})) {
                   10926: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 10927: 	    } else {
1.359     albertel 10928: 		my %returnhash;
                   10929: 		if (!$publicuser) {
                   10930: 		    %returnhash=&userenvironment($udom,$uname,
                   10931: 						 $qualifierrest);
                   10932: 		}
1.218     albertel 10933: 		return $returnhash{$qualifierrest};
                   10934: 	    }
1.48      www      10935: # ----------------------------------------------------------------- user.course
                   10936:         } elsif ($space eq 'course') {
1.218     albertel 10937: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10938:             return $env{join('.',('request.course',$qualifier))};
1.48      www      10939: # ------------------------------------------------------------------- user.role
                   10940:         } elsif ($space eq 'role') {
1.218     albertel 10941: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10942:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      10943:             if ($qualifier eq 'value') {
                   10944: 		return $role;
                   10945:             } elsif ($qualifier eq 'extent') {
                   10946:                 return $where;
                   10947:             }
                   10948: # ----------------------------------------------------------------- user.domain
                   10949:         } elsif ($space eq 'domain') {
1.218     albertel 10950:             return $udom;
1.48      www      10951: # ------------------------------------------------------------------- user.name
                   10952:         } elsif ($space eq 'name') {
1.218     albertel 10953:             return $uname;
1.48      www      10954: # ---------------------------------------------------- Any other user namespace
1.29      www      10955:         } else {
1.359     albertel 10956: 	    my %reply;
                   10957: 	    if (!$publicuser) {
                   10958: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   10959: 	    }
                   10960: 	    return $reply{$qualifierrest};
1.48      www      10961:         }
1.236     www      10962:     } elsif ($realm eq 'query') {
                   10963: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 10964:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   10965: 						[$spacequalifierrest]);
1.620     albertel 10966: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      10967:    } elsif ($realm eq 'request') {
1.48      www      10968: # ------------------------------------------------------------- request.browser
                   10969:         if ($space eq 'browser') {
1.1145    bisitz   10970:             return $env{'browser.'.$qualifier};
1.57      www      10971: # ------------------------------------------------------------ request.filename
                   10972:         } else {
1.620     albertel 10973:             return $env{'request.'.$spacequalifierrest};
1.29      www      10974:         }
1.28      www      10975:     } elsif ($realm eq 'course') {
1.48      www      10976: # ---------------------------------------------------------- course.description
1.620     albertel 10977:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      10978:     } elsif ($realm eq 'resource') {
1.165     www      10979: 
1.620     albertel 10980: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 10981: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   10982: 	}
1.693     albertel 10983: 
1.1172.2.30  raeburn  10984:         if ($qualifier eq '') {
                   10985: 	    if ($space eq 'title') {
                   10986: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   10987: 	        return &gettitle($symbparm);
                   10988: 	    }
1.693     albertel 10989: 	
1.1172.2.30  raeburn  10990: 	    if ($space eq 'map') {
                   10991: 	        my ($map) = &decode_symb($symbparm);
                   10992: 	        return &symbread($map);
                   10993: 	    }
                   10994:             if ($space eq 'maptitle') {
                   10995:                 my ($map) = &decode_symb($symbparm);
                   10996:                 return &gettitle($map);
                   10997:             }
                   10998: 	    if ($space eq 'filename') {
                   10999: 	        if ($symbparm) {
                   11000: 		    return &clutter((&decode_symb($symbparm))[2]);
                   11001: 	        }
                   11002: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 11003: 	    }
1.1172.2.30  raeburn  11004: 
                   11005:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   11006:                 if ($space eq 'visibleparts') {
                   11007:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   11008:                     my $item;
                   11009:                     if (ref($navmap)) {
                   11010:                         my $res = $navmap->getBySymb($symbparm);
                   11011:                         my $parts = $res->parts();
                   11012:                         if (ref($parts) eq 'ARRAY') {
                   11013:                             $item = join(',',@{$parts});
                   11014:                         }
                   11015:                         undef($navmap);
                   11016:                     }
                   11017:                     return $item;
                   11018:                 }
                   11019:             }
                   11020:         }
1.693     albertel 11021: 
                   11022: 	my ($section, $group, @groups);
1.593     albertel 11023: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  11024:         if (($courseid eq '') && ($cid)) {
                   11025:             $courseid = $cid;
                   11026:         }
                   11027: 	if (($symbparm && $courseid) && 
                   11028: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      11029: 
1.218     albertel 11030: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      11031: 
1.60      www      11032: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 11033: 	    my $symbp=$symbparm;
1.735     albertel 11034: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 11035: 
                   11036: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   11037: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   11038: 
1.620     albertel 11039: 	    if (($env{'user.name'} eq $uname) &&
                   11040: 		($env{'user.domain'} eq $udom)) {
                   11041: 		$section=$env{'request.course.sec'};
1.733     raeburn  11042:                 @groups = split(/:/,$env{'request.course.groups'});  
                   11043:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 11044: 	    } else {
1.539     albertel 11045: 		if (! defined($usection)) {
1.551     albertel 11046: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 11047: 		} else {
                   11048: 		    $section = $usection;
                   11049: 		}
1.733     raeburn  11050:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 11051: 	    }
                   11052: 
                   11053: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   11054: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   11055: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   11056: 
1.593     albertel 11057: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 11058: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 11059: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      11060: 
1.60      www      11061: # ----------------------------------------------------------- first, check user
1.624     albertel 11062: 
                   11063: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 11064: 				       ([$courselevelr,'resource'],
                   11065: 					[$courselevelm,'map'     ],
                   11066: 					[$courselevel, 'course'  ]));
1.931     albertel 11067: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      11068: 
1.594     albertel 11069: # ------------------------------------------------ second, check some of course
1.684     raeburn  11070:             my $coursereply;
1.691     raeburn  11071:             if (@groups > 0) {
                   11072:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   11073:                                        $mapparm,$spacequalifierrest);
1.927     albertel 11074:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  11075:             }
1.96      www      11076: 
1.684     raeburn  11077: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 11078: 				  $env{'course.'.$courseid.'.domain'},
                   11079: 				  'course',
                   11080: 				  ([$seclevelr,   'resource'],
                   11081: 				   [$seclevelm,   'map'     ],
                   11082: 				   [$seclevel,    'course'  ],
                   11083: 				   [$courselevelr,'resource']));
                   11084: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      11085: 
1.60      www      11086: # ------------------------------------------------------ third, check map parms
1.218     albertel 11087: 	    my %parmhash=();
                   11088: 	    my $thisparm='';
                   11089: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 11090: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 11091: 		    &GDBM_READER(),0640)) {
1.218     albertel 11092: 		$thisparm=$parmhash{$symbparm};
                   11093: 		untie(%parmhash);
                   11094: 	    }
1.927     albertel 11095: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 11096: 	}
1.594     albertel 11097: # ------------------------------------------ fourth, look in resource metadata
1.71      www      11098: 
1.218     albertel 11099: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 11100: 	my $filename;
                   11101: 	if (!$symbparm) { $symbparm=&symbread(); }
                   11102: 	if ($symbparm) {
1.409     www      11103: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 11104: 	} else {
1.620     albertel 11105: 	    $filename=$env{'request.filename'};
1.282     albertel 11106: 	}
                   11107: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 11108: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 11109: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 11110: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      11111: 
1.927     albertel 11112: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 11113: 	if ($symbparm && defined($courseid) && 
1.620     albertel 11114: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 11115: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   11116: 				     $env{'course.'.$courseid.'.domain'},
                   11117: 				     'course',
1.927     albertel 11118: 				     ([$courselevelm,'map'   ],
                   11119: 				      [$courselevel, 'course']));
                   11120: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 11121: 	}
1.145     www      11122: # ------------------------------------------------------------------ Cascade up
1.218     albertel 11123: 	unless ($space eq '0') {
1.336     albertel 11124: 	    my @parts=split(/_/,$space);
                   11125: 	    my $id=pop(@parts);
                   11126: 	    my $part=join('_',@parts);
                   11127: 	    if ($part eq '') { $part='0'; }
1.927     albertel 11128: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 11129: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  11130: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 11131: 	}
1.395     albertel 11132: 	if ($recurse) { return undef; }
                   11133: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 11134: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      11135: # ---------------------------------------------------- Any other user namespace
                   11136:     } elsif ($realm eq 'environment') {
                   11137: # ----------------------------------------------------------------- environment
1.620     albertel 11138: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   11139: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 11140: 	} else {
1.770     albertel 11141: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   11142: 		return '';
                   11143: 	    }
1.219     albertel 11144: 	    my %returnhash=&userenvironment($udom,$uname,
                   11145: 					    $spacequalifierrest);
                   11146: 	    return $returnhash{$spacequalifierrest};
                   11147: 	}
1.28      www      11148:     } elsif ($realm eq 'system') {
1.48      www      11149: # ----------------------------------------------------------------- system.time
                   11150: 	if ($space eq 'time') {
                   11151: 	    return time;
                   11152:         }
1.696     albertel 11153:     } elsif ($realm eq 'server') {
                   11154: # ----------------------------------------------------------------- system.time
                   11155: 	if ($space eq 'name') {
                   11156: 	    return $ENV{'SERVER_NAME'};
                   11157:         }
1.28      www      11158:     }
1.48      www      11159:     return '';
1.61      www      11160: }
                   11161: 
1.927     albertel 11162: sub get_reply {
                   11163:     my ($reply_value) = @_;
1.940     raeburn  11164:     if (ref($reply_value) eq 'ARRAY') {
                   11165:         if (wantarray) {
                   11166: 	    return @$reply_value;
                   11167:         }
                   11168:         return $reply_value->[0];
                   11169:     } else {
                   11170:         return $reply_value;
1.927     albertel 11171:     }
                   11172: }
                   11173: 
1.691     raeburn  11174: sub check_group_parms {
                   11175:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   11176:     my @groupitems = ();
                   11177:     my $resultitem;
1.927     albertel 11178:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  11179:     foreach my $group (@{$groups}) {
                   11180:         foreach my $level (@levels) {
1.927     albertel 11181:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   11182:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  11183:         }
                   11184:     }
                   11185:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   11186:                             $env{'course.'.$courseid.'.domain'},
                   11187:                                      'course',@groupitems);
                   11188:     return $coursereply;
                   11189: }
                   11190: 
                   11191: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  11192:     my ($courseid,@groups) = @_;
                   11193:     @groups = sort(@groups);
1.691     raeburn  11194:     return @groups;
                   11195: }
                   11196: 
1.395     albertel 11197: sub packages_tab_default {
                   11198:     my ($uri,$varname)=@_;
                   11199:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 11200: 
                   11201:     my (@extension,@specifics,$do_default);
                   11202:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 11203: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 11204: 	if ($pack_type eq 'default') {
                   11205: 	    $do_default=1;
                   11206: 	} elsif ($pack_type eq 'extension') {
                   11207: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 11208: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 11209: 	    # only look at packages defaults for packages that this id is
1.738     albertel 11210: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   11211: 	}
                   11212:     }
                   11213:     # first look for a package that matches the requested part id
                   11214:     foreach my $package (@specifics) {
                   11215: 	my (undef,$pack_type,$pack_part)=@{$package};
                   11216: 	next if ($pack_part ne $part);
                   11217: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11218: 	    return $packagetab{"$pack_type&$name&default"};
                   11219: 	}
                   11220:     }
                   11221:     # look for any possible matching non extension_ package
                   11222:     foreach my $package (@specifics) {
                   11223: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 11224: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11225: 	    return $packagetab{"$pack_type&$name&default"};
                   11226: 	}
1.585     albertel 11227: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 11228: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   11229: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 11230: 	}
                   11231:     }
1.738     albertel 11232:     # look for any posible extension_ match
                   11233:     foreach my $package (@extension) {
                   11234: 	my ($package,$pack_type)=@{$package};
                   11235: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11236: 	    return $packagetab{"$pack_type&$name&default"};
                   11237: 	}
                   11238: 	if (defined($packagetab{$package."&$name&default"})) {
                   11239: 	    return $packagetab{$package."&$name&default"};
                   11240: 	}
                   11241:     }
                   11242:     # look for a global default setting
                   11243:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11244: 	return $packagetab{"default&$name&default"};
                   11245:     }
1.395     albertel 11246:     return undef;
                   11247: }
                   11248: 
1.334     albertel 11249: sub add_prefix_and_part {
                   11250:     my ($prefix,$part)=@_;
                   11251:     my $keyroot;
                   11252:     if (defined($prefix) && $prefix !~ /^__/) {
                   11253: 	# prefix that has a part already
                   11254: 	$keyroot=$prefix;
                   11255:     } elsif (defined($prefix)) {
                   11256: 	# prefix that is missing a part
                   11257: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11258:     } else {
                   11259: 	# no prefix at all
                   11260: 	if (defined($part)) { $keyroot='_'.$part; }
                   11261:     }
                   11262:     return $keyroot;
                   11263: }
                   11264: 
1.71      www      11265: # ---------------------------------------------------------------- Get metadata
                   11266: 
1.599     albertel 11267: my %metaentry;
1.1070    www      11268: my %importedpartids;
1.1172.2.99  raeburn  11269: my %importedrespids;
1.71      www      11270: sub metadata {
1.176     www      11271:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      11272:     $uri=&declutter($uri);
1.288     albertel 11273:     # if it is a non metadata possible uri return quickly
1.529     albertel 11274:     if (($uri eq '') || 
                   11275: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.20  raeburn  11276: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108    raeburn  11277:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11278: 	return undef;
                   11279:     }
1.1172.2.49  raeburn  11280:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11281: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11282: 	return undef;
1.288     albertel 11283:     }
1.73      www      11284:     my $filename=$uri;
                   11285:     $uri=~s/\.meta$//;
1.172     www      11286: #
                   11287: # Is the metadata already cached?
1.177     www      11288: # Look at timestamp of caching
1.172     www      11289: # Everything is cached by the main uri, libraries are never directly cached
                   11290: #
1.428     albertel 11291:     if (!defined($liburi)) {
1.599     albertel 11292: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11293: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11294:     }
                   11295:     {
1.1069    www      11296: # Imported parts would go here
1.1172.2.99  raeburn  11297:         my @origfiletagids=();
1.1069    www      11298:         my $importedparts=0;
1.1172.2.99  raeburn  11299: 
                   11300: # Imported responseids would go here
                   11301:         my $importedresponses=0;
1.172     www      11302: #
                   11303: # Is this a recursive call for a library?
                   11304: #
1.599     albertel 11305: #	if (! exists($metacache{$uri})) {
                   11306: #	    $metacache{$uri}={};
                   11307: #	}
1.924     albertel 11308: 	my $cachetime = 60*60;
1.171     www      11309:         if ($liburi) {
                   11310: 	    $liburi=&declutter($liburi);
                   11311:             $filename=$liburi;
1.401     bowersj2 11312:         } else {
1.599     albertel 11313: 	    &devalidate_cache_new('meta',$uri);
                   11314: 	    undef(%metaentry);
1.401     bowersj2 11315: 	}
1.140     www      11316:         my %metathesekeys=();
1.73      www      11317:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 11318: 	my $metastring;
1.1140    www      11319: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 11320: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 11321: 	    $metastring = 
1.929     albertel 11322: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 11323: 					  ('grade_target' => 'meta'));
                   11324: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  11325: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   11326:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 11327: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 11328: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 11329: 	    $metastring=&getfile($file);
1.489     albertel 11330: 	}
1.208     albertel 11331:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      11332:         my $token;
1.140     www      11333:         undef %metathesekeys;
1.71      www      11334:         while ($token=$parser->get_token) {
1.339     albertel 11335: 	    if ($token->[0] eq 'S') {
                   11336: 		if (defined($token->[2]->{'package'})) {
1.172     www      11337: #
                   11338: # This is a package - get package info
                   11339: #
1.339     albertel 11340: 		    my $package=$token->[2]->{'package'};
                   11341: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11342: 		    if (defined($token->[2]->{'id'})) { 
                   11343: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   11344: 		    }
1.599     albertel 11345: 		    if ($metaentry{':packages'}) {
                   11346: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 11347: 		    } else {
1.599     albertel 11348: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 11349: 		    }
1.736     albertel 11350: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 11351: 			my $part=$keyroot;
                   11352: 			$part=~s/^\_//;
1.736     albertel 11353: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   11354: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   11355: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 11356: 			    # ignore package.tab specified default values
                   11357:                             # here &package_tab_default() will fetch those
                   11358: 			    if ($subp eq 'default') { next; }
1.736     albertel 11359: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 11360: 			    my $unikey;
                   11361: 			    if ($pack =~ /_0$/) {
                   11362: 				$unikey='parameter_0_'.$name;
                   11363: 				$part=0;
                   11364: 			    } else {
                   11365: 				$unikey='parameter'.$keyroot.'_'.$name;
                   11366: 			    }
1.339     albertel 11367: 			    if ($subp eq 'display') {
                   11368: 				$value.=' [Part: '.$part.']';
                   11369: 			    }
1.599     albertel 11370: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 11371: 			    $metathesekeys{$unikey}=1;
1.599     albertel 11372: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11373: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 11374: 			    }
1.599     albertel 11375: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   11376: 				$metaentry{':'.$unikey}=
                   11377: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 11378: 			    }
1.339     albertel 11379: 			}
                   11380: 		    }
                   11381: 		} else {
1.172     www      11382: #
                   11383: # This is not a package - some other kind of start tag
1.339     albertel 11384: #
                   11385: 		    my $entry=$token->[1];
1.1068    www      11386: 		    my $unikey='';
1.175     www      11387: 
1.339     albertel 11388: 		    if ($entry eq 'import') {
1.175     www      11389: #
                   11390: # Importing a library here
1.339     albertel 11391: #
1.1067    www      11392:                         my $location=$parser->get_text('/import');
                   11393:                         my $dir=$filename;
                   11394:                         $dir=~s|[^/]*$||;
                   11395:                         $location=&filelocation($dir,$location);
1.1172.2.99  raeburn  11396: 
                   11397:                         my $importid=$token->[2]->{'id'};
1.1068    www      11398:                         my $importmode=$token->[2]->{'importmode'};
1.1172.2.99  raeburn  11399: #
                   11400: # Check metadata for imported file to
                   11401: # see if it contained response items
                   11402: #
                   11403:                         my %currmetaentry = %metaentry;
                   11404:                         my $libresponseorder = &metadata($location,'responseorder');
                   11405:                         my $origfile;
                   11406:                         if ($libresponseorder ne '') {
                   11407:                             if ($#origfiletagids<0) {
                   11408:                                 undef(%importedrespids);
                   11409:                                 undef(%importedpartids);
                   11410:                             }
                   11411:                             @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
                   11412:                             if (@{$importedrespids{$importid}} > 0) {
                   11413:                                 $importedresponses = 1;
                   11414: # We need to get the original file and the imported file to get the response order correct
                   11415: # Load and inspect original file
                   11416:                                 if ($#origfiletagids<0) {
                   11417:                                     my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11418:                                     $origfile=&getfile($origfilelocation);
                   11419:                                     @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11420:                                 }
                   11421:                             }
                   11422:                         }
                   11423: # Do not overwrite contents of %metaentry hash for resource itself with 
                   11424: # hash populated for imported library file
                   11425:                         %metaentry = %currmetaentry;
                   11426:                         undef(%currmetaentry);
1.1068    www      11427:                         if ($importmode eq 'problem') {
1.1069    www      11428: # Import as problem/response
1.1068    www      11429:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11430:                         } elsif ($importmode eq 'part') {
                   11431: # Import as part(s)
1.1069    www      11432:                            $importedparts=1;
                   11433: # We need to get the original file and the imported file to get the part order correct
                   11434: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.99  raeburn  11435: # Load and inspect original file if we didn't do that already
                   11436:                            if ($#origfiletagids<0) {
                   11437:                                undef(%importedrespids);
                   11438:                                undef(%importedpartids);
                   11439:                                if ($origfile eq '') {
                   11440:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11441:                                    $origfile=&getfile($origfilelocation);
                   11442:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11443:                                }
1.1070    www      11444:                            }
                   11445: 
1.1069    www      11446: # Load and inspect imported file
                   11447:                            my $impfile=&getfile($location);
                   11448:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11449:                            if ($#impfilepartids>=0) {
                   11450: # This problem had parts
1.1070    www      11451:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      11452:                            } else {
                   11453: # Importing by turning a single problem into a problem part
                   11454: # It gets the import-tags ID as part-ID
                   11455:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      11456:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      11457:                            }
1.1068    www      11458:                         } else {
                   11459: # Normal import
                   11460:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11461:                            if (defined($token->[2]->{'id'})) {
                   11462:                               $unikey.='_'.$token->[2]->{'id'};
                   11463:                            }
1.1067    www      11464:                         }
                   11465: 
1.339     albertel 11466: 			if ($depthcount<20) {
1.736     albertel 11467: 			    my $metadata = 
                   11468: 				&metadata($uri,'keys', $location,$unikey,
                   11469: 					  $depthcount+1);
                   11470: 			    foreach my $meta (split(',',$metadata)) {
                   11471: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   11472: 				$metathesekeys{$meta}=1;
1.339     albertel 11473: 			    }
1.1068    www      11474: 			
                   11475:                         }
1.1067    www      11476: 		    } else {
                   11477: #
                   11478: # Not importing, some other kind of non-package, non-library start tag
                   11479: # 
                   11480:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11481:                         if (defined($token->[2]->{'id'})) {
                   11482:                             $unikey.='_'.$token->[2]->{'id'};
                   11483:                         }
1.339     albertel 11484: 			if (defined($token->[2]->{'name'})) { 
                   11485: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   11486: 			}
                   11487: 			$metathesekeys{$unikey}=1;
1.736     albertel 11488: 			foreach my $param (@{$token->[3]}) {
                   11489: 			    $metaentry{':'.$unikey.'.'.$param} =
                   11490: 				$token->[2]->{$param};
1.339     albertel 11491: 			}
                   11492: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 11493: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 11494: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   11495: 		 # only ws inside the tag, and not in default, so use default
                   11496: 		 # as value
1.599     albertel 11497: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 11498: 			} elsif ( $internaltext =~ /\S/ ) {
                   11499: 		  # something interesting inside the tag
                   11500: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 11501: 			} else {
1.908     albertel 11502: 		  # no interesting values, don't set a default
1.339     albertel 11503: 			}
1.172     www      11504: # end of not-a-package not-a-library import
1.339     albertel 11505: 		    }
1.172     www      11506: # end of not-a-package start tag
1.339     albertel 11507: 		}
1.172     www      11508: # the next is the end of "start tag"
1.339     albertel 11509: 	    }
                   11510: 	}
1.483     albertel 11511: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 11512: 	$extension = lc($extension);
                   11513: 	if ($extension eq 'htm') { $extension='html'; }
                   11514: 
1.737     albertel 11515: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 11516: 	    #no specific packages #how's our extension
                   11517: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 11518: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 11519: 					 \%metathesekeys);
                   11520: 	}
1.883     albertel 11521: 
                   11522: 	if (!exists($metaentry{':packages'})
                   11523: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 11524: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 11525: 		#no specific packages well let's get default then
                   11526: 		if ($key!~/^default&/) { next; }
1.488     albertel 11527: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 11528: 					     \%metathesekeys);
                   11529: 	    }
                   11530: 	}
1.338     www      11531: # are there custom rights to evaluate
1.599     albertel 11532: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 11533: 
1.338     www      11534:     #
                   11535:     # Importing a rights file here
1.339     albertel 11536:     #
                   11537: 	    unless ($depthcount) {
1.599     albertel 11538: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 11539: 		my $dir=$filename;
                   11540: 		$dir=~s|[^/]*$||;
                   11541: 		$location=&filelocation($dir,$location);
1.736     albertel 11542: 		my $rights_metadata =
                   11543: 		    &metadata($uri,'keys',$location,'_rights',
                   11544: 			      $depthcount+1);
                   11545: 		foreach my $rights (split(',',$rights_metadata)) {
                   11546: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   11547: 		    $metathesekeys{$rights}=1;
1.339     albertel 11548: 		}
                   11549: 	    }
                   11550: 	}
1.737     albertel 11551: 	# uniqifiy package listing
                   11552: 	my %seen;
                   11553: 	my @uniq_packages =
                   11554: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   11555: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   11556: 
1.1172.2.99  raeburn  11557:         if (($importedresponses) || ($importedparts)) {
                   11558:             if ($importedparts) {
1.1070    www      11559: # We had imported parts and need to rebuild partorder
1.1172.2.99  raeburn  11560:                 $metaentry{':partorder'}='';
                   11561:                 $metathesekeys{'partorder'}=1;
                   11562:             }
                   11563:             if ($importedresponses) {
                   11564: # We had imported responses and need to rebuild responseorder
                   11565:                 $metaentry{':responseorder'}='';
                   11566:                 $metathesekeys{'responseorder'}=1;
                   11567:             }
                   11568:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   11569:                 my $origid = $origfiletagids[$index+1];
                   11570:                 if ($origfiletagids[$index] eq 'part') {
                   11571: # Original part, part of the problem
                   11572:                     if ($importedparts) {
                   11573:                         $metaentry{':partorder'}.=','.$origid;
                   11574:                     }
                   11575:                 } elsif ($origfiletagids[$index] eq 'import') {
                   11576:                     if ($importedparts) {
                   11577: # We have imported parts at this position
                   11578:                         $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   11579:                     }
                   11580:                     if ($importedresponses) {
                   11581: # We have imported responses at this position
                   11582:                         if (ref($importedrespids{$origid}) eq 'ARRAY') {
                   11583:                             $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
                   11584:                         }
                   11585:                     }
                   11586:                 } else {
                   11587: # Original response item, part of the problem
                   11588:                     if ($importedresponses) {
                   11589:                         $metaentry{':responseorder'}.=','.$origid;
                   11590:                     }
                   11591:                 }
                   11592:             }
                   11593:             if ($importedparts) {
                   11594:                 $metaentry{':partorder'}=~s/^\,//;
                   11595:             }
                   11596:             if ($importedresponses) {
                   11597:                 $metaentry{':responseorder'}=~s/^\,//;
                   11598:             }
1.1070    www      11599:         }
                   11600: 
1.737     albertel 11601: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 11602: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58  raeburn  11603: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 11604: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      11605: # this is the end of "was not already recently cached
1.71      www      11606:     }
1.599     albertel 11607:     return $metaentry{':'.$what};
1.261     albertel 11608: }
                   11609: 
1.488     albertel 11610: sub metadata_create_package_def {
1.483     albertel 11611:     my ($uri,$key,$package,$metathesekeys)=@_;
                   11612:     my ($pack,$name,$subp)=split(/\&/,$key);
                   11613:     if ($subp eq 'default') { next; }
                   11614:     
1.599     albertel 11615:     if (defined($metaentry{':packages'})) {
                   11616: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 11617:     } else {
1.599     albertel 11618: 	$metaentry{':packages'}=$package;
1.483     albertel 11619:     }
                   11620:     my $value=$packagetab{$key};
                   11621:     my $unikey;
                   11622:     $unikey='parameter_0_'.$name;
1.599     albertel 11623:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 11624:     $$metathesekeys{$unikey}=1;
1.599     albertel 11625:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11626: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 11627:     }
1.599     albertel 11628:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   11629: 	$metaentry{':'.$unikey}=
                   11630: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 11631:     }
                   11632: }
                   11633: 
1.261     albertel 11634: sub metadata_generate_part0 {
                   11635:     my ($metadata,$metacache,$uri) = @_;
                   11636:     my %allnames;
1.737     albertel 11637:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 11638: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 11639: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   11640: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 11641: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 11642: 	    $allnames{$name}=$part;
                   11643: 	  }
                   11644: 	}
                   11645:     }
                   11646:     foreach my $name (keys(%allnames)) {
                   11647:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 11648:       my $key=":parameter_0_$name";
1.261     albertel 11649:       $$metacache{"$key.part"}='0';
                   11650:       $$metacache{"$key.name"}=$name;
1.428     albertel 11651:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 11652: 					   $allnames{$name}.'_'.$name.
                   11653: 					   '.type'};
1.428     albertel 11654:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 11655: 			     '.display'};
1.644     www      11656:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 11657:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 11658:       $$metacache{"$key.display"}=$olddis;
                   11659:     }
1.71      www      11660: }
                   11661: 
1.764     albertel 11662: # ------------------------------------------------------ Devalidate title cache
                   11663: 
                   11664: sub devalidate_title_cache {
                   11665:     my ($url)=@_;
                   11666:     if (!$env{'request.course.id'}) { return; }
                   11667:     my $symb=&symbread($url);
                   11668:     if (!$symb) { return; }
                   11669:     my $key=$env{'request.course.id'}."\0".$symb;
                   11670:     &devalidate_cache_new('title',$key);
                   11671: }
                   11672: 
1.1014    droeschl 11673: # ------------------------------------------------- Get the title of a course
                   11674: 
                   11675: sub current_course_title {
                   11676:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   11677: }
1.301     www      11678: # ------------------------------------------------- Get the title of a resource
                   11679: 
                   11680: sub gettitle {
                   11681:     my $urlsymb=shift;
                   11682:     my $symb=&symbread($urlsymb);
1.534     albertel 11683:     if ($symb) {
1.620     albertel 11684: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 11685: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 11686: 	if (defined($cached)) { 
                   11687: 	    return $result;
                   11688: 	}
1.534     albertel 11689: 	my ($map,$resid,$url)=&decode_symb($symb);
                   11690: 	my $title='';
1.907     albertel 11691: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   11692: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   11693: 	} else {
                   11694: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11695: 		    &GDBM_READER(),0640)) {
                   11696: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   11697: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   11698: 		untie(%bighash);
                   11699: 	    }
1.534     albertel 11700: 	}
                   11701: 	$title=~s/\&colon\;/\:/gs;
                   11702: 	if ($title) {
1.1159    www      11703: # Remember both $symb and $title for dynamic metadata
                   11704:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      11705:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      11706: # Cache this title and then return it
1.599     albertel 11707: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 11708: 	}
                   11709: 	$urlsymb=$url;
                   11710:     }
                   11711:     my $title=&metadata($urlsymb,'title');
                   11712:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   11713:     return $title;
1.301     www      11714: }
1.613     albertel 11715: 
1.614     albertel 11716: sub get_slot {
                   11717:     my ($which,$cnum,$cdom)=@_;
                   11718:     if (!$cnum || !$cdom) {
1.790     albertel 11719: 	(undef,my $courseid)=&whichuser();
1.620     albertel 11720: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   11721: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 11722:     }
1.703     albertel 11723:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   11724:     my %slotinfo;
                   11725:     if (exists($remembered{$key})) {
                   11726: 	$slotinfo{$which} = $remembered{$key};
                   11727:     } else {
                   11728: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   11729: 	&Apache::lonhomework::showhash(%slotinfo);
                   11730: 	my ($tmp)=keys(%slotinfo);
                   11731: 	if ($tmp=~/^error:/) { return (); }
                   11732: 	$remembered{$key} = $slotinfo{$which};
                   11733:     }
1.616     albertel 11734:     if (ref($slotinfo{$which}) eq 'HASH') {
                   11735: 	return %{$slotinfo{$which}};
                   11736:     }
                   11737:     return $slotinfo{$which};
1.614     albertel 11738: }
1.1150    raeburn  11739: 
                   11740: sub get_reservable_slots {
                   11741:     my ($cnum,$cdom,$uname,$udom) = @_;
                   11742:     my $now = time;
                   11743:     my $reservable_info;
                   11744:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   11745:     if (exists($remembered{$key})) {
                   11746:         $reservable_info = $remembered{$key};
                   11747:     } else {
                   11748:         my %resv;
                   11749:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   11750:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   11751:         $reservable_info = \%resv;
                   11752:         $remembered{$key} = $reservable_info;
                   11753:     }
                   11754:     return $reservable_info;
                   11755: }
                   11756: 
                   11757: sub get_course_slots {
                   11758:     my ($cnum,$cdom) = @_;
                   11759:     my $hashid=$cnum.':'.$cdom;
                   11760:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   11761:     if (defined($cached)) {
                   11762:         if (ref($result) eq 'HASH') {
                   11763:             return %{$result};
                   11764:         }
                   11765:     } else {
                   11766:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   11767:         my ($tmp) = keys(%slots);
                   11768:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  11769:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  11770:             return %slots;
                   11771:         }
                   11772:     }
                   11773:     return;
                   11774: }
                   11775: 
                   11776: sub devalidate_slots_cache {
                   11777:     my ($cnum,$cdom)=@_;
                   11778:     my $hashid=$cnum.':'.$cdom;
                   11779:     &devalidate_cache_new('allslots',$hashid);
                   11780: }
                   11781: 
1.1172.2.8  raeburn  11782: sub get_coursechange {
                   11783:     my ($cdom,$cnum) = @_;
                   11784:     if ($cdom eq '' || $cnum eq '') {
                   11785:         return unless ($env{'request.course.id'});
                   11786:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   11787:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   11788:     }
                   11789:     my $hashid=$cdom.'_'.$cnum;
                   11790:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   11791:     if ((defined($cached)) && ($change ne '')) {
                   11792:         return $change;
                   11793:     } else {
                   11794:         my %crshash;
                   11795:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   11796:         if ($crshash{'internal.contentchange'} eq '') {
                   11797:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   11798:             if ($change eq '') {
                   11799:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   11800:                 $change = $crshash{'internal.created'};
                   11801:             }
                   11802:         } else {
                   11803:             $change = $crshash{'internal.contentchange'};
                   11804:         }
                   11805:         my $cachetime = 600;
                   11806:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   11807:     }
                   11808:     return $change;
                   11809: }
                   11810: 
                   11811: sub devalidate_coursechange_cache {
                   11812:     my ($cnum,$cdom)=@_;
                   11813:     my $hashid=$cnum.':'.$cdom;
                   11814:     &devalidate_cache_new('crschange',$hashid);
                   11815: }
                   11816: 
1.31      www      11817: # ------------------------------------------------- Update symbolic store links
                   11818: 
                   11819: sub symblist {
                   11820:     my ($mapname,%newhash)=@_;
1.438     www      11821:     $mapname=&deversion(&declutter($mapname));
1.31      www      11822:     my %hash;
1.620     albertel 11823:     if (($env{'request.course.fn'}) && (%newhash)) {
                   11824:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11825:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  11826: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 11827: 		next if ($url eq 'last_known'
                   11828: 			 && $env{'form.no_update_last_known'});
                   11829: 		$hash{declutter($url)}=&encode_symb($mapname,
                   11830: 						    $newhash{$url}->[1],
                   11831: 						    $newhash{$url}->[0]);
1.191     harris41 11832:             }
1.31      www      11833:             if (untie(%hash)) {
                   11834: 		return 'ok';
                   11835:             }
                   11836:         }
                   11837:     }
                   11838:     return 'error';
1.212     www      11839: }
                   11840: 
                   11841: # --------------------------------------------------------------- Verify a symb
                   11842: 
                   11843: sub symbverify {
1.1172.2.11  raeburn  11844:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      11845:     my $thisfn=$thisurl;
1.439     www      11846:     $thisfn=&declutter($thisfn);
1.215     www      11847: # direct jump to resource in page or to a sequence - will construct own symbs
                   11848:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   11849: # check URL part
1.409     www      11850:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      11851: 
1.431     www      11852:     unless ($url eq $thisfn) { return 0; }
1.213     www      11853: 
1.216     www      11854:     $symb=&symbclean($symb);
1.510     www      11855:     $thisurl=&deversion($thisurl);
1.439     www      11856:     $thisfn=&deversion($thisfn);
1.213     www      11857: 
                   11858:     my %bighash;
                   11859:     my $okay=0;
1.431     www      11860: 
1.620     albertel 11861:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11862:                             &GDBM_READER(),0640)) {
1.1172.2.13  raeburn  11863:         my $noclutter;
1.1032    raeburn  11864:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   11865:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  11866:             if ($map =~ m{^uploaded/.+\.page$}) {
                   11867:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   11868:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   11869:                 $noclutter = 1;
                   11870:             }
                   11871:         }
                   11872:         my $ids;
                   11873:         if ($noclutter) {
                   11874:             $ids=$bighash{'ids_'.$thisurl};
                   11875:         } else {
                   11876:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  11877:         }
1.1102    raeburn  11878:         unless ($ids) {
1.1172.2.13  raeburn  11879:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  11880:             $ids=$bighash{$idkey};
1.216     www      11881:         }
                   11882:         if ($ids) {
                   11883: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  11884:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   11885:                 $symb =~ s/\?.+$//;
                   11886:             }
1.800     albertel 11887: 	    foreach my $id (split(/\,/,$ids)) {
                   11888: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      11889:                if (
                   11890:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  11891:    eq $symb) {
1.1172.2.11  raeburn  11892:                    if (ref($encstate)) {
                   11893:                        $$encstate = $bighash{'encrypted_'.$id};
                   11894:                    }
1.1172.2.13  raeburn  11895:                    if (($env{'request.role.adv'}) ||
                   11896:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  11897:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  11898:                        $okay=1;
                   11899:                        last;
                   11900:                    }
                   11901:                }
                   11902:            }
1.216     www      11903:         }
1.213     www      11904: 	untie(%bighash);
                   11905:     }
                   11906:     return $okay;
1.31      www      11907: }
                   11908: 
1.210     www      11909: # --------------------------------------------------------------- Clean-up symb
                   11910: 
                   11911: sub symbclean {
                   11912:     my $symb=shift;
1.568     albertel 11913:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      11914: # remove version from map
                   11915:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      11916: 
1.210     www      11917: # remove version from URL
                   11918:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      11919: 
1.507     www      11920: # remove wrapper
                   11921: 
1.510     www      11922:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 11923:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      11924:     return $symb;
1.409     www      11925: }
                   11926: 
                   11927: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 11928: 
                   11929: sub encode_symb {
                   11930:     my ($map,$resid,$url)=@_;
                   11931:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   11932: }
1.409     www      11933: 
                   11934: sub decode_symb {
1.568     albertel 11935:     my $symb=shift;
                   11936:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   11937:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      11938:     return (&fixversion($map),$resid,&fixversion($url));
                   11939: }
                   11940: 
                   11941: sub fixversion {
                   11942:     my $fn=shift;
1.609     banghart 11943:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      11944:     my %bighash;
                   11945:     my $uri=&clutter($fn);
1.620     albertel 11946:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      11947: # is this cached?
1.599     albertel 11948:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      11949:     if (defined($cached)) { return $result; }
                   11950: # unfortunately not cached, or expired
1.620     albertel 11951:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      11952: 	    &GDBM_READER(),0640)) {
                   11953:  	if ($bighash{'version_'.$uri}) {
                   11954:  	    my $version=$bighash{'version_'.$uri};
1.444     www      11955:  	    unless (($version eq 'mostrecent') || 
                   11956: 		    ($version==&getversion($uri))) {
1.440     www      11957:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   11958:  	    }
                   11959:  	}
                   11960:  	untie %bighash;
1.413     www      11961:     }
1.599     albertel 11962:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      11963: }
                   11964: 
                   11965: sub deversion {
                   11966:     my $url=shift;
                   11967:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   11968:     return $url;
1.210     www      11969: }
                   11970: 
1.31      www      11971: # ------------------------------------------------------ Return symb list entry
                   11972: 
                   11973: sub symbread {
1.1172.2.66  raeburn  11974:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1172.2.54  raeburn  11975:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.66  raeburn  11976:     if (defined($env{$cache_str})) {
                   11977:         if ($ignorecachednull) {
                   11978:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   11979:         } else {
                   11980:             return $env{$cache_str};
                   11981:         }
                   11982:     }
1.242     www      11983: # no filename provided? try from environment
1.1172.2.54  raeburn  11984:     unless ($thisfn) {
1.620     albertel 11985:         if ($env{'request.symb'}) {
1.1172.2.13  raeburn  11986:             return $env{$cache_str}=&symbclean($env{'request.symb'});
                   11987:         }
                   11988:         $thisfn=$env{'request.filename'};
1.44      www      11989:     }
1.569     albertel 11990:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      11991: # is that filename actually a symb? Verify, clean, and return
                   11992:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 11993: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 11994: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 11995: 	}
1.242     www      11996:     }
1.44      www      11997:     $thisfn=declutter($thisfn);
1.31      www      11998:     my %hash;
1.37      www      11999:     my %bighash;
                   12000:     my $syval='';
1.620     albertel 12001:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  12002:         my $targetfn = $thisfn;
1.609     banghart 12003:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  12004:             $targetfn = 'adm/wrapper/'.$thisfn;
                   12005:         }
1.687     albertel 12006: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   12007: 	    $targetfn=$1;
                   12008: 	}
1.620     albertel 12009:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12010:                       &GDBM_READER(),0640)) {
1.481     raeburn  12011: 	    $syval=$hash{$targetfn};
1.37      www      12012:             untie(%hash);
                   12013:         }
                   12014: # ---------------------------------------------------------- There was an entry
                   12015:         if ($syval) {
1.601     albertel 12016: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 12017: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  12018: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12019: 		    #return $env{$cache_str}='';
1.601     albertel 12020: 		#}    
                   12021: 		#$syval.=$1;
                   12022: 	    #}
1.37      www      12023:         } else {
                   12024: # ------------------------------------------------------- Was not in symb table
1.620     albertel 12025:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12026:                             &GDBM_READER(),0640)) {
1.37      www      12027: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      12028:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      12029:               unless ($ids) { 
                   12030:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      12031:               }
                   12032:               unless ($ids) {
                   12033: # alias?
                   12034: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      12035:               }
1.37      www      12036:               if ($ids) {
                   12037: # ------------------------------------------------------------------- Has ID(s)
                   12038:                  my @possibilities=split(/\,/,$ids);
1.39      www      12039:                  if ($#possibilities==0) {
                   12040: # ----------------------------------------------- There is only one possibility
1.37      www      12041: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 12042: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12043: 						    $resid,$thisfn);
1.1172.2.66  raeburn  12044:                      if (ref($possibles) eq 'HASH') {
                   12045:                          $possibles->{$syval} = 1;
                   12046:                      }
                   12047:                      if ($checkforblock) {
                   12048:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   12049:                          if (@blockers) {
                   12050:                              $syval = '';
                   12051:                              return;
                   12052:                          }
                   12053:                      }
                   12054:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39      www      12055: # ------------------------------------------ There is more than one possibility
                   12056:                      my $realpossible=0;
1.800     albertel 12057:                      foreach my $id (@possibilities) {
                   12058: 			 my $file=$bighash{'src_'.$id};
1.1172.2.66  raeburn  12059:                          my $canaccess;
                   12060:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   12061:                              $canaccess = 1;
                   12062:                          } else {
                   12063:                              $canaccess = &allowed('bre',$file);
                   12064:                          }
                   12065:                          if ($canaccess) {
                   12066:          		     my ($mapid,$resid)=split(/\./,$id);
                   12067:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   12068:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12069:                                                              $resid,$thisfn);
                   12070:                                  if (ref($possibles) eq 'HASH') {
                   12071:                                      $possibles->{$syval} = 1;
                   12072:                                  }
                   12073:                                  if ($checkforblock) {
                   12074:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   12075:                                      unless (@blockers > 0) {
                   12076:                                          $syval = $poss_syval;
                   12077:                                          $realpossible++;
                   12078:                                      }
                   12079:                                  } else {
                   12080:                                      $syval = $poss_syval;
                   12081:                                      $realpossible++;
                   12082:                                  }
                   12083:                              }
1.39      www      12084: 			 }
1.191     harris41 12085:                      }
1.39      www      12086: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      12087:                  } else {
                   12088:                      $syval='';
1.37      www      12089:                  }
                   12090: 	      }
1.1172.2.66  raeburn  12091:               untie(%bighash);
1.481     raeburn  12092:            }
1.31      www      12093:         }
1.62      www      12094:         if ($syval) {
1.620     albertel 12095: 	    return $env{$cache_str}=$syval;
1.62      www      12096:         }
1.31      www      12097:     }
1.949     raeburn  12098:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12099:     return $env{$cache_str}='';
1.31      www      12100: }
                   12101: 
                   12102: # ---------------------------------------------------------- Return random seed
                   12103: 
1.32      www      12104: sub numval {
                   12105:     my $txt=shift;
                   12106:     $txt=~tr/A-J/0-9/;
                   12107:     $txt=~tr/a-j/0-9/;
                   12108:     $txt=~tr/K-T/0-9/;
                   12109:     $txt=~tr/k-t/0-9/;
                   12110:     $txt=~tr/U-Z/0-5/;
                   12111:     $txt=~tr/u-z/0-5/;
                   12112:     $txt=~s/\D//g;
1.564     albertel 12113:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      12114:     return int($txt);
1.368     albertel 12115: }
                   12116: 
1.484     albertel 12117: sub numval2 {
                   12118:     my $txt=shift;
                   12119:     $txt=~tr/A-J/0-9/;
                   12120:     $txt=~tr/a-j/0-9/;
                   12121:     $txt=~tr/K-T/0-9/;
                   12122:     $txt=~tr/k-t/0-9/;
                   12123:     $txt=~tr/U-Z/0-5/;
                   12124:     $txt=~tr/u-z/0-5/;
                   12125:     $txt=~s/\D//g;
                   12126:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12127:     my $total;
                   12128:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 12129:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 12130:     return int($total);
                   12131: }
                   12132: 
1.575     albertel 12133: sub numval3 {
                   12134:     use integer;
                   12135:     my $txt=shift;
                   12136:     $txt=~tr/A-J/0-9/;
                   12137:     $txt=~tr/a-j/0-9/;
                   12138:     $txt=~tr/K-T/0-9/;
                   12139:     $txt=~tr/k-t/0-9/;
                   12140:     $txt=~tr/U-Z/0-5/;
                   12141:     $txt=~tr/u-z/0-5/;
                   12142:     $txt=~s/\D//g;
                   12143:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12144:     my $total;
                   12145:     foreach my $val (@txts) { $total+=$val; }
                   12146:     if ($_64bit) { $total=(($total<<32)>>32); }
                   12147:     return $total;
                   12148: }
                   12149: 
1.675     albertel 12150: sub digest {
                   12151:     my ($data)=@_;
                   12152:     my $digest=&Digest::MD5::md5($data);
                   12153:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   12154:     my ($e,$f);
                   12155:     {
                   12156:         use integer;
                   12157:         $e=($a+$b);
                   12158:         $f=($c+$d);
                   12159:         if ($_64bit) {
                   12160:             $e=(($e<<32)>>32);
                   12161:             $f=(($f<<32)>>32);
                   12162:         }
                   12163:     }
                   12164:     if (wantarray) {
                   12165: 	return ($e,$f);
                   12166:     } else {
                   12167: 	my $g;
                   12168: 	{
                   12169: 	    use integer;
                   12170: 	    $g=($e+$f);
                   12171: 	    if ($_64bit) {
                   12172: 		$g=(($g<<32)>>32);
                   12173: 	    }
                   12174: 	}
                   12175: 	return $g;
                   12176:     }
                   12177: }
                   12178: 
1.368     albertel 12179: sub latest_rnd_algorithm_id {
1.675     albertel 12180:     return '64bit5';
1.366     albertel 12181: }
1.32      www      12182: 
1.503     albertel 12183: sub get_rand_alg {
                   12184:     my ($courseid)=@_;
1.790     albertel 12185:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 12186:     if ($courseid) {
1.620     albertel 12187: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 12188:     }
                   12189:     return &latest_rnd_algorithm_id();
                   12190: }
                   12191: 
1.562     albertel 12192: sub validCODE {
                   12193:     my ($CODE)=@_;
                   12194:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   12195:     return 0;
                   12196: }
                   12197: 
1.491     albertel 12198: sub getCODE {
1.620     albertel 12199:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 12200:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   12201: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   12202: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 12203: 	return $Apache::lonhomework::history{'resource.CODE'};
                   12204:     }
                   12205:     return undef;
                   12206: }
1.1133    foxr     12207: #
                   12208: #  Determines the random seed for a specific context:
                   12209: #
                   12210: # parameters:
                   12211: #   symb      - in course context the symb for the seed.
                   12212: #   course_id - The course id of the form domain_coursenum.
                   12213: #   domain    - Domain for the user.
                   12214: #   course    - Course for the user.
                   12215: #   cenv      - environment of the course.
                   12216: #
                   12217: # NOTE:
                   12218: #   All parameters are picked out of the environment if missing
                   12219: #   or not defined.
                   12220: #   If a symb cannot be determined the current time is used instead.
                   12221: #
                   12222: #  For a given well defined symb, courside, domain, username,
                   12223: #  and course environment, the seed is reproducible.
                   12224: #
1.31      www      12225: sub rndseed {
1.1133    foxr     12226:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 12227:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 12228:     if (!defined($symb)) {
1.366     albertel 12229: 	unless ($symb=$wsymb) { return time; }
                   12230:     }
1.1146    foxr     12231:     if (!defined $courseid) { 
                   12232: 	$courseid=$wcourseid; 
                   12233:     }
                   12234:     if (!defined $domain) { $domain=$wdomain; }
                   12235:     if (!defined $username) { $username=$wusername }
1.1133    foxr     12236: 
                   12237:     my $which;
                   12238:     if (defined($cenv->{'rndseed'})) {
                   12239: 	$which = $cenv->{'rndseed'};
                   12240:     } else {
                   12241: 	$which =&get_rand_alg($courseid);
                   12242:     }
1.491     albertel 12243:     if (defined(&getCODE())) {
1.675     albertel 12244: 	if ($which eq '64bit5') {
                   12245: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   12246: 	} elsif ($which eq '64bit4') {
1.575     albertel 12247: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   12248: 	} else {
                   12249: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   12250: 	}
1.675     albertel 12251:     } elsif ($which eq '64bit5') {
                   12252: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 12253:     } elsif ($which eq '64bit4') {
                   12254: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 12255:     } elsif ($which eq '64bit3') {
                   12256: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 12257:     } elsif ($which eq '64bit2') {
                   12258: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 12259:     } elsif ($which eq '64bit') {
                   12260: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   12261:     }
                   12262:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   12263: }
                   12264: 
                   12265: sub rndseed_32bit {
                   12266:     my ($symb,$courseid,$domain,$username)=@_;
                   12267:     {
                   12268: 	use integer;
                   12269: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   12270: 	my $symbseed=numval($symb) << 22;
                   12271: 	my $namechck=unpack("%32C*",$username) << 17;
                   12272: 	my $nameseed=numval($username) << 12;
                   12273: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   12274: 	my $courseseed=unpack("%32C*",$courseid);
                   12275: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 12276: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12277: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12278: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 12279: 	return $num;
                   12280:     }
                   12281: }
                   12282: 
                   12283: sub rndseed_64bit {
                   12284:     my ($symb,$courseid,$domain,$username)=@_;
                   12285:     {
                   12286: 	use integer;
                   12287: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   12288: 	my $symbseed=numval($symb) << 10;
                   12289: 	my $namechck=unpack("%32S*",$username);
                   12290: 	
                   12291: 	my $nameseed=numval($username) << 21;
                   12292: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   12293: 	my $courseseed=unpack("%32S*",$courseid);
                   12294: 	
                   12295: 	my $num1=$symbchck+$symbseed+$namechck;
                   12296: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12297: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12298: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12299: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 12300: 	return "$num1,$num2";
1.155     albertel 12301:     }
1.366     albertel 12302: }
                   12303: 
1.443     albertel 12304: sub rndseed_64bit2 {
                   12305:     my ($symb,$courseid,$domain,$username)=@_;
                   12306:     {
                   12307: 	use integer;
                   12308: 	# strings need to be an even # of cahracters long, it it is odd the
                   12309:         # last characters gets thrown away
                   12310: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12311: 	my $symbseed=numval($symb) << 10;
                   12312: 	my $namechck=unpack("%32S*",$username.' ');
                   12313: 	
                   12314: 	my $nameseed=numval($username) << 21;
1.501     albertel 12315: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12316: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12317: 	
                   12318: 	my $num1=$symbchck+$symbseed+$namechck;
                   12319: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12320: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12321: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 12322: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 12323: 	return "$num1,$num2";
                   12324:     }
                   12325: }
                   12326: 
                   12327: sub rndseed_64bit3 {
                   12328:     my ($symb,$courseid,$domain,$username)=@_;
                   12329:     {
                   12330: 	use integer;
                   12331: 	# strings need to be an even # of cahracters long, it it is odd the
                   12332:         # last characters gets thrown away
                   12333: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12334: 	my $symbseed=numval2($symb) << 10;
                   12335: 	my $namechck=unpack("%32S*",$username.' ');
                   12336: 	
                   12337: 	my $nameseed=numval2($username) << 21;
1.443     albertel 12338: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12339: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12340: 	
                   12341: 	my $num1=$symbchck+$symbseed+$namechck;
                   12342: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12343: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12344: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 12345: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12346: 	
1.503     albertel 12347: 	return "$num1:$num2";
1.443     albertel 12348:     }
                   12349: }
                   12350: 
1.575     albertel 12351: sub rndseed_64bit4 {
                   12352:     my ($symb,$courseid,$domain,$username)=@_;
                   12353:     {
                   12354: 	use integer;
                   12355: 	# strings need to be an even # of cahracters long, it it is odd the
                   12356:         # last characters gets thrown away
                   12357: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12358: 	my $symbseed=numval3($symb) << 10;
                   12359: 	my $namechck=unpack("%32S*",$username.' ');
                   12360: 	
                   12361: 	my $nameseed=numval3($username) << 21;
                   12362: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12363: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12364: 	
                   12365: 	my $num1=$symbchck+$symbseed+$namechck;
                   12366: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12367: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12368: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 12369: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12370: 	
1.575     albertel 12371: 	return "$num1:$num2";
                   12372:     }
                   12373: }
                   12374: 
1.675     albertel 12375: sub rndseed_64bit5 {
                   12376:     my ($symb,$courseid,$domain,$username)=@_;
                   12377:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   12378:     return "$num1:$num2";
                   12379: }
                   12380: 
1.366     albertel 12381: sub rndseed_CODE_64bit {
                   12382:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 12383:     {
1.366     albertel 12384: 	use integer;
1.443     albertel 12385: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 12386: 	my $symbseed=numval2($symb);
1.491     albertel 12387: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12388: 	my $CODEseed=numval(&getCODE());
1.443     albertel 12389: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 12390: 	my $num1=$symbseed+$CODEchck;
                   12391: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12392: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12393: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 12394: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12395: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 12396: 	return "$num1:$num2";
1.366     albertel 12397:     }
                   12398: }
                   12399: 
1.575     albertel 12400: sub rndseed_CODE_64bit4 {
                   12401:     my ($symb,$courseid,$domain,$username)=@_;
                   12402:     {
                   12403: 	use integer;
                   12404: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   12405: 	my $symbseed=numval3($symb);
                   12406: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12407: 	my $CODEseed=numval3(&getCODE());
                   12408: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12409: 	my $num1=$symbseed+$CODEchck;
                   12410: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12411: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12412: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 12413: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12414: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   12415: 	return "$num1:$num2";
                   12416:     }
                   12417: }
                   12418: 
1.675     albertel 12419: sub rndseed_CODE_64bit5 {
                   12420:     my ($symb,$courseid,$domain,$username)=@_;
                   12421:     my $code = &getCODE();
                   12422:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   12423:     return "$num1:$num2";
                   12424: }
                   12425: 
1.366     albertel 12426: sub setup_random_from_rndseed {
                   12427:     my ($rndseed)=@_;
1.503     albertel 12428:     if ($rndseed =~/([,:])/) {
1.1172.2.51  raeburn  12429: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   12430:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   12431:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   12432:         } else {
                   12433:             &Math::Random::random_set_seed($num1,$num2);
                   12434:         }
1.366     albertel 12435:     } else {
                   12436: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 12437:     }
1.36      albertel 12438: }
                   12439: 
1.474     albertel 12440: sub latest_receipt_algorithm_id {
1.835     albertel 12441:     return 'receipt3';
1.474     albertel 12442: }
                   12443: 
1.480     www      12444: sub recunique {
                   12445:     my $fucourseid=shift;
                   12446:     my $unique;
1.835     albertel 12447:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   12448: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12449: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      12450:     } else {
                   12451: 	$unique=$perlvar{'lonReceipt'};
                   12452:     }
                   12453:     return unpack("%32C*",$unique);
                   12454: }
                   12455: 
                   12456: sub recprefix {
                   12457:     my $fucourseid=shift;
                   12458:     my $prefix;
1.835     albertel 12459:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   12460: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12461: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      12462:     } else {
                   12463: 	$prefix=$perlvar{'lonHostID'};
                   12464:     }
                   12465:     return unpack("%32C*",$prefix);
                   12466: }
                   12467: 
1.76      www      12468: sub ireceipt {
1.474     albertel 12469:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 12470: 
                   12471:     my $return =&recprefix($fucourseid).'-';
                   12472: 
                   12473:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   12474: 	$env{'request.state'} eq 'construct') {
                   12475: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   12476: 	return $return;
                   12477:     }
                   12478: 
1.76      www      12479:     my $cuname=unpack("%32C*",$funame);
                   12480:     my $cudom=unpack("%32C*",$fudom);
                   12481:     my $cucourseid=unpack("%32C*",$fucourseid);
                   12482:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      12483:     my $cunique=&recunique($fucourseid);
1.474     albertel 12484:     my $cpart=unpack("%32S*",$part);
1.835     albertel 12485:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   12486: 
1.790     albertel 12487: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 12488: 			       
                   12489: 	$return.= ($cunique%$cuname+
                   12490: 		   $cunique%$cudom+
                   12491: 		   $cusymb%$cuname+
                   12492: 		   $cusymb%$cudom+
                   12493: 		   $cucourseid%$cuname+
                   12494: 		   $cucourseid%$cudom+
                   12495: 		   $cpart%$cuname+
                   12496: 		   $cpart%$cudom);
                   12497:     } else {
                   12498: 	$return.= ($cunique%$cuname+
                   12499: 		   $cunique%$cudom+
                   12500: 		   $cusymb%$cuname+
                   12501: 		   $cusymb%$cudom+
                   12502: 		   $cucourseid%$cuname+
                   12503: 		   $cucourseid%$cudom);
                   12504:     }
                   12505:     return $return;
1.76      www      12506: }
                   12507: 
                   12508: sub receipt {
1.474     albertel 12509:     my ($part)=@_;
1.790     albertel 12510:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 12511:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      12512: }
1.260     ng       12513: 
1.790     albertel 12514: sub whichuser {
                   12515:     my ($passedsymb)=@_;
                   12516:     my ($symb,$courseid,$domain,$name,$publicuser);
                   12517:     if (defined($env{'form.grade_symb'})) {
                   12518: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   12519: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   12520: 	if (!$allowed &&
                   12521: 	    exists($env{'request.course.sec'}) &&
                   12522: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   12523: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   12524: 			      '/'.$env{'request.course.sec'});
                   12525: 	}
                   12526: 	if ($allowed) {
                   12527: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   12528: 	    $courseid=$tmp_courseid;
                   12529: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   12530: 	    ($name)=&get_env_multiple('form.grade_username');
                   12531: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   12532: 	}
                   12533:     }
                   12534:     if (!$passedsymb) {
                   12535: 	$symb=&symbread();
                   12536:     } else {
                   12537: 	$symb=$passedsymb;
                   12538:     }
                   12539:     $courseid=$env{'request.course.id'};
                   12540:     $domain=$env{'user.domain'};
                   12541:     $name=$env{'user.name'};
                   12542:     if ($name eq 'public' && $domain eq 'public') {
                   12543: 	if (!defined($env{'form.username'})) {
                   12544: 	    $env{'form.username'}.=time.rand(10000000);
                   12545: 	}
                   12546: 	$name.=$env{'form.username'};
                   12547:     }
                   12548:     return ($symb,$courseid,$domain,$name,$publicuser);
                   12549: 
                   12550: }
                   12551: 
1.36      albertel 12552: # ------------------------------------------------------------ Serves up a file
1.472     albertel 12553: # returns either the contents of the file or 
                   12554: # -1 if the file doesn't exist
1.481     raeburn  12555: #
                   12556: # if the target is a file that was uploaded via DOCS, 
                   12557: # a check will be made to see if a current copy exists on the local server,
                   12558: # if it does this will be served, otherwise a copy will be retrieved from
                   12559: # the home server for the course and stored in /home/httpd/html/userfiles on
                   12560: # the local server.   
1.472     albertel 12561: 
1.36      albertel 12562: sub getfile {
1.538     albertel 12563:     my ($file) = @_;
1.609     banghart 12564:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 12565:     &repcopy($file);
                   12566:     return &readfile($file);
                   12567: }
                   12568: 
                   12569: sub repcopy_userfile {
                   12570:     my ($file)=@_;
1.1142    raeburn  12571:     my $londocroot = $perlvar{'lonDocRoot'};
                   12572:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  12573:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 12574:     my ($cdom,$cnum,$filename) = 
1.811     albertel 12575: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 12576:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   12577:     if (-e "$file") {
1.828     www      12578: # we already have a local copy, check it out
1.538     albertel 12579: 	my @fileinfo = stat($file);
1.828     www      12580: 	my $rtncode;
                   12581: 	my $info;
1.538     albertel 12582: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 12583: 	if ($lwpresp ne 'ok') {
1.828     www      12584: # there is no such file anymore, even though we had a local copy
1.482     albertel 12585: 	    if ($rtncode eq '404') {
1.538     albertel 12586: 		unlink($file);
1.482     albertel 12587: 	    }
                   12588: 	    return -1;
                   12589: 	}
                   12590: 	if ($info < $fileinfo[9]) {
1.828     www      12591: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  12592: 	    return 'ok';
1.828     www      12593: 	} else {
                   12594: # the file is outdated, get rid of it
                   12595: 	    unlink($file);
1.482     albertel 12596: 	}
1.828     www      12597:     }
                   12598: # one way or the other, at this point, we don't have the file
                   12599: # construct the correct path for the file
                   12600:     my @parts = ($cdom,$cnum); 
                   12601:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   12602: 	push @parts, split(/\//,$1);
                   12603:     }
                   12604:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   12605:     foreach my $part (@parts) {
                   12606: 	$path .= '/'.$part;
                   12607: 	if (!-e $path) {
                   12608: 	    mkdir($path,0770);
1.482     albertel 12609: 	}
                   12610:     }
1.828     www      12611: # now the path exists for sure
                   12612: # get a user agent
                   12613:     my $ua=new LWP::UserAgent;
                   12614:     my $transferfile=$file.'.in.transfer';
                   12615: # FIXME: this should flock
                   12616:     if (-e $transferfile) { return 'ok'; }
                   12617:     my $request;
                   12618:     $uri=~s/^\///;
1.980     raeburn  12619:     my $homeserver = &homeserver($cnum,$cdom);
                   12620:     my $protocol = $protocol{$homeserver};
                   12621:     $protocol = 'http' if ($protocol ne 'https');
                   12622:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      12623:     my $response=$ua->request($request,$transferfile);
                   12624: # did it work?
                   12625:     if ($response->is_error()) {
                   12626: 	unlink($transferfile);
                   12627: 	&logthis("Userfile repcopy failed for $uri");
                   12628: 	return -1;
                   12629:     }
                   12630: # worked, rename the transfer file
                   12631:     rename($transferfile,$file);
1.607     raeburn  12632:     return 'ok';
1.481     raeburn  12633: }
                   12634: 
1.517     albertel 12635: sub tokenwrapper {
                   12636:     my $uri=shift;
1.980     raeburn  12637:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 12638:     $uri=~s|^/||;
1.620     albertel 12639:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 12640:     my $token=$1;
1.552     albertel 12641:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   12642:     if ($udom && $uname && $file) {
                   12643: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  12644:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  12645:         my $homeserver = &homeserver($uname,$udom);
                   12646:         my $protocol = $protocol{$homeserver};
                   12647:         $protocol = 'http' if ($protocol ne 'https');
                   12648:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 12649:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   12650:                                '&tokenissued='.$perlvar{'lonHostID'};
                   12651:     } else {
                   12652:         return '/adm/notfound.html';
                   12653:     }
                   12654: }
                   12655: 
1.828     www      12656: # call with reqtype HEAD: get last modification time
                   12657: # call with reqtype GET: get the file contents
                   12658: # Do not call this with reqtype GET for large files! It loads everything into memory
                   12659: #
1.481     raeburn  12660: sub getuploaded {
                   12661:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   12662:     $uri=~s/^\///;
1.980     raeburn  12663:     my $homeserver = &homeserver($cnum,$cdom);
                   12664:     my $protocol = $protocol{$homeserver};
                   12665:     $protocol = 'http' if ($protocol ne 'https');
                   12666:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  12667:     my $ua=new LWP::UserAgent;
                   12668:     my $request=new HTTP::Request($reqtype,$uri);
                   12669:     my $response=$ua->request($request);
                   12670:     $$rtncode = $response->code;
1.482     albertel 12671:     if (! $response->is_success()) {
                   12672: 	return 'failed';
                   12673:     }      
                   12674:     if ($reqtype eq 'HEAD') {
1.486     www      12675: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 12676:     } elsif ($reqtype eq 'GET') {
                   12677: 	$$info = $response->content;
1.472     albertel 12678:     }
1.482     albertel 12679:     return 'ok';
1.36      albertel 12680: }
                   12681: 
1.481     raeburn  12682: sub readfile {
                   12683:     my $file = shift;
                   12684:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   12685:     my $fh;
1.1172.2.96  raeburn  12686:     open($fh,"<",$file);
1.481     raeburn  12687:     my $a='';
1.800     albertel 12688:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  12689:     return $a;
                   12690: }
                   12691: 
1.36      albertel 12692: sub filelocation {
1.590     banghart 12693:     my ($dir,$file) = @_;
                   12694:     my $location;
                   12695:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 12696: 
                   12697:     if ($file =~ m-^/adm/-) {
                   12698: 	$file=~s-^/adm/wrapper/-/-;
                   12699: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   12700:     }
1.882     albertel 12701: 
1.1139    www      12702:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  12703:         $location = $file;
1.609     banghart 12704:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 12705:         my ($udom,$uname,$filename)=
1.811     albertel 12706:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 12707:         my $home=&homeserver($uname,$udom);
                   12708:         my $is_me=0;
                   12709:         my @ids=&current_machine_ids();
                   12710:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   12711:         if ($is_me) {
1.1117    foxr     12712:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 12713:         } else {
                   12714:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   12715:   	      $udom.'/'.$uname.'/'.$filename;
                   12716:         }
1.882     albertel 12717:     } elsif ($file =~ m-^/adm/-) {
                   12718: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 12719:     } else {
                   12720:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      12721:         $file=~s:^/(res|priv)/:/:;
                   12722:         my $space=$1;
1.590     banghart 12723:         if ( !( $file =~ m:^/:) ) {
                   12724:             $location = $dir. '/'.$file;
                   12725:         } else {
1.1142    raeburn  12726:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 12727:         }
1.59      albertel 12728:     }
1.590     banghart 12729:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 12730:     while ($location=~m{/\.\./}) {
                   12731: 	if ($location =~ m{/[^/]+/\.\./}) {
                   12732: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   12733: 	} else {
                   12734: 	    $location=~ s{/\.\./}{/}g;
                   12735: 	}
                   12736:     } #remove dir/..
1.590     banghart 12737:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   12738:     return $location;
1.46      www      12739: }
1.36      albertel 12740: 
1.46      www      12741: sub hreflocation {
                   12742:     my ($dir,$file)=@_;
1.980     raeburn  12743:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 12744: 	$file=filelocation($dir,$file);
1.700     albertel 12745:     } elsif ($file=~m-^/adm/-) {
                   12746: 	$file=~s-^/adm/wrapper/-/-;
                   12747: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 12748:     }
                   12749:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   12750: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   12751:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  12752: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   12753: 	        {/uploaded/$1/$2/}x;
1.46      www      12754:     }
1.913     albertel 12755:     if ($file=~ m{^/userfiles/}) {
                   12756: 	$file =~ s{^/userfiles/}{/uploaded/};
                   12757:     }
1.462     albertel 12758:     return $file;
1.465     albertel 12759: }
                   12760: 
1.1139    www      12761: 
                   12762: 
                   12763: 
                   12764: 
1.465     albertel 12765: sub current_machine_domains {
1.853     albertel 12766:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   12767: }
                   12768: 
                   12769: sub machine_domains {
                   12770:     my ($hostname) = @_;
1.465     albertel 12771:     my @domains;
1.838     albertel 12772:     my %hostname = &all_hostnames();
1.465     albertel 12773:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  12774: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 12775: 	if ($hostname eq $name) {
1.844     albertel 12776: 	    push(@domains,&host_domain($id));
1.465     albertel 12777: 	}
                   12778:     }
                   12779:     return @domains;
                   12780: }
                   12781: 
                   12782: sub current_machine_ids {
1.853     albertel 12783:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   12784: }
                   12785: 
                   12786: sub machine_ids {
                   12787:     my ($hostname) = @_;
                   12788:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 12789:     my @ids;
1.888     albertel 12790:     my %name_to_host = &all_names();
1.889     albertel 12791:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   12792: 	return @{ $name_to_host{$hostname} };
                   12793:     }
                   12794:     return;
1.31      www      12795: }
                   12796: 
1.824     raeburn  12797: sub additional_machine_domains {
                   12798:     my @domains;
1.1172.2.96  raeburn  12799:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824     raeburn  12800:     while( my $line = <$fh>) {
                   12801:         $line =~ s/\s//g;
                   12802:         push(@domains,$line);
                   12803:     }
                   12804:     return @domains;
                   12805: }
                   12806: 
                   12807: sub default_login_domain {
                   12808:     my $domain = $perlvar{'lonDefDomain'};
                   12809:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   12810:     foreach my $posdom (&current_machine_domains(),
                   12811:                         &additional_machine_domains()) {
                   12812:         if (lc($posdom) eq lc($testdomain)) {
                   12813:             $domain=$posdom;
                   12814:             last;
                   12815:         }
                   12816:     }
                   12817:     return $domain;
                   12818: }
                   12819: 
1.1172.2.106  raeburn  12820: sub shared_institution {
                   12821:     my ($dom) = @_;
                   12822:     my $same_intdom;
                   12823:     my $hostintdom = &internet_dom($perlvar{'lonHostID'});
                   12824:     if ($hostintdom ne '') {
                   12825:         my %iphost = &get_iphost();
                   12826:         my $primary_id = &domain($dom,'primary');
                   12827:         my $primary_ip = &get_host_ip($primary_id);
                   12828:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
                   12829:             foreach my $id (@{$iphost{$primary_ip}}) {
                   12830:                 my $intdom = &internet_dom($id);
                   12831:                 if ($intdom eq $hostintdom) {
                   12832:                     $same_intdom = 1;
                   12833:                     last;
                   12834:                 }
                   12835:             }
                   12836:         }
                   12837:     }
                   12838:     return $same_intdom;
                   12839: }
                   12840: 
1.31      www      12841: # ------------------------------------------------------------- Declutters URLs
                   12842: 
                   12843: sub declutter {
                   12844:     my $thisfn=shift;
1.569     albertel 12845:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49  raeburn  12846:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   12847:         $thisfn=~s{^/home/httpd/html}{};
                   12848:     }
1.31      www      12849:     $thisfn=~s/^\///;
1.697     albertel 12850:     $thisfn=~s|^adm/wrapper/||;
                   12851:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      12852:     $thisfn=~s/^res\///;
1.1172    bisitz   12853:     $thisfn=~s/^priv\///;
1.1032    raeburn  12854:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   12855:         $thisfn=~s/\?.+$//;
                   12856:     }
1.268     www      12857:     return $thisfn;
                   12858: }
                   12859: 
                   12860: # ------------------------------------------------------------- Clutter up URLs
                   12861: 
                   12862: sub clutter {
                   12863:     my $thisfn='/'.&declutter(shift);
1.887     albertel 12864:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 12865: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      12866:        $thisfn='/res'.$thisfn; 
                   12867:     }
1.1031    raeburn  12868:     if ($thisfn !~m|^/adm|) {
                   12869: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 12870: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 12871: 	} else {
                   12872: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   12873: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 12874: 	    if ($embstyle eq 'ssi'
                   12875: 		|| ($embstyle eq 'hdn')
                   12876: 		|| ($embstyle eq 'rat')
                   12877: 		|| ($embstyle eq 'prv')
                   12878: 		|| ($embstyle eq 'ign')) {
                   12879: 		#do nothing with these
                   12880: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 12881: 		|| ($embstyle eq 'emb')
                   12882: 		|| ($embstyle eq 'wrp')) {
                   12883: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 12884: 	    } elsif ($embstyle eq 'unk'
                   12885: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 12886: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 12887: 	    } else {
1.718     www      12888: #		&logthis("Got a blank emb style");
1.695     albertel 12889: 	    }
1.694     albertel 12890: 	}
                   12891:     }
1.31      www      12892:     return $thisfn;
1.12      www      12893: }
                   12894: 
1.787     albertel 12895: sub clutter_with_no_wrapper {
                   12896:     my $uri = &clutter(shift);
                   12897:     if ($uri =~ m-^/adm/-) {
                   12898: 	$uri =~ s-^/adm/wrapper/-/-;
                   12899: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   12900:     }
                   12901:     return $uri;
                   12902: }
                   12903: 
1.557     albertel 12904: sub freeze_escape {
                   12905:     my ($value)=@_;
                   12906:     if (ref($value)) {
                   12907: 	$value=&nfreeze($value);
                   12908: 	return '__FROZEN__'.&escape($value);
                   12909:     }
                   12910:     return &escape($value);
                   12911: }
                   12912: 
1.11      www      12913: 
1.557     albertel 12914: sub thaw_unescape {
                   12915:     my ($value)=@_;
                   12916:     if ($value =~ /^__FROZEN__/) {
                   12917: 	substr($value,0,10,undef);
                   12918: 	$value=&unescape($value);
                   12919: 	return &thaw($value);
                   12920:     }
                   12921:     return &unescape($value);
                   12922: }
                   12923: 
1.436     albertel 12924: sub correct_line_ends {
                   12925:     my ($result)=@_;
                   12926:     $$result =~s/\r\n/\n/mg;
                   12927:     $$result =~s/\r/\n/mg;
1.415     albertel 12928: }
1.1       albertel 12929: # ================================================================ Main Program
                   12930: 
1.184     www      12931: sub goodbye {
1.204     albertel 12932:    &logthis("Starting Shut down");
1.443     albertel 12933: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 12934:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 12935: #converted
1.599     albertel 12936: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 12937:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   12938: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   12939: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 12940: #1.1 only
1.870     albertel 12941: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   12942: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   12943: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   12944: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   12945:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 12946:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   12947:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      12948:    &flushcourselogs();
                   12949:    &logthis("Shutting down");
                   12950: }
                   12951: 
1.852     albertel 12952: sub get_dns {
1.1172.2.17  raeburn  12953:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 12954:     if (!$ignore_cache) {
                   12955: 	my ($content,$cached)=
                   12956: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   12957: 	if ($cached) {
1.1172.2.17  raeburn  12958: 	    &$func($content,$hashref);
1.869     albertel 12959: 	    return;
                   12960: 	}
                   12961:     }
                   12962: 
                   12963:     my %alldns;
1.1172.2.96  raeburn  12964:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   12965:         foreach my $dns (<$config>) {
                   12966: 	    next if ($dns !~ /^\^(\S*)/x);
                   12967:             my $line = $1;
                   12968:             my ($host,$protocol) = split(/:/,$line);
                   12969:             if ($protocol ne 'https') {
                   12970:                 $protocol = 'http';
                   12971:             }
                   12972: 	    $alldns{$host} = $protocol;
1.979     raeburn  12973:         }
1.1172.2.96  raeburn  12974:         close($config);
1.869     albertel 12975:     }
                   12976:     while (%alldns) {
1.1172.2.52  raeburn  12977: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 12978: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  12979:         $ua->timeout(30);
1.979     raeburn  12980: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 12981: 	my $response=$ua->request($request);
1.979     raeburn  12982:         delete($alldns{$dns});
1.852     albertel 12983: 	next if ($response->is_error());
                   12984: 	my @content = split("\n",$response->content);
1.1172.2.17  raeburn  12985:         unless ($nocache) {
1.1172.2.23  raeburn  12986: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  12987:         }
                   12988: 	&$func(\@content,$hashref);
1.869     albertel 12989: 	return;
1.852     albertel 12990:     }
1.871     albertel 12991:     my $which = (split('/',$url))[3];
                   12992:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.105  raeburn  12993:     if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   12994:         my @content = <$config>;
                   12995:         &$func(\@content,$hashref);
                   12996:     }
1.1172.2.17  raeburn  12997:     return;
                   12998: }
                   12999: 
                   13000: # ------------------------------------------------------Get DNS checksums file
                   13001: sub parse_dns_checksums_tab {
                   13002:     my ($lines,$hashref) = @_;
1.1172.2.53  raeburn  13003:     my $lonhost = $perlvar{'lonHostID'};
                   13004:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17  raeburn  13005:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53  raeburn  13006:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   13007:     my $webconfdir = '/etc/httpd/conf';
                   13008:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   13009:         $webconfdir = '/etc/apache2';
                   13010:     } elsif ($distro =~ /^sles(\d+)$/) {
                   13011:         if ($1 >= 10) {
                   13012:             $webconfdir = '/etc/apache2';
                   13013:         }
                   13014:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   13015:         if ($1 >= 10.0) {
                   13016:             $webconfdir = '/etc/apache2';
                   13017:         }
                   13018:     }
1.1172.2.17  raeburn  13019:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13020:     my (%chksum,%revnum);
                   13021:     if (ref($lines) eq 'ARRAY') {
                   13022:         chomp(@{$lines});
1.1172.2.34  raeburn  13023:         my $version = shift(@{$lines});
                   13024:         if ($version eq $release) {
1.1172.2.17  raeburn  13025:             foreach my $line (@{$lines}) {
1.1172.2.34  raeburn  13026:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53  raeburn  13027:                 if ($file =~ m{^/etc/httpd/conf}) {
                   13028:                     if ($webconfdir eq '/etc/apache2') {
                   13029:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   13030:                     }
                   13031:                 }
1.1172.2.34  raeburn  13032:                 $chksum{$file} = $shasum;
                   13033:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  13034:             }
                   13035:             if (ref($hashref) eq 'HASH') {
                   13036:                 %{$hashref} = (
                   13037:                                 sums     => \%chksum,
                   13038:                                 versions => \%revnum,
                   13039:                               );
                   13040:             }
                   13041:         }
                   13042:     }
1.869     albertel 13043:     return;
1.852     albertel 13044: }
1.1172.2.17  raeburn  13045: 
                   13046: sub fetch_dns_checksums {
                   13047:     my %checksums;
1.1172.2.34  raeburn  13048:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48  raeburn  13049:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34  raeburn  13050:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13051:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  13052:              \%checksums);
                   13053:     return \%checksums;
                   13054: }
                   13055: 
1.327     albertel 13056: # ------------------------------------------------------------ Read domain file
                   13057: {
1.852     albertel 13058:     my $loaded;
1.846     albertel 13059:     my %domain;
                   13060: 
1.852     albertel 13061:     sub parse_domain_tab {
                   13062: 	my ($lines) = @_;
                   13063: 	foreach my $line (@$lines) {
                   13064: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      13065: 
1.846     albertel 13066: 	    chomp($line);
1.852     albertel 13067: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 13068: 	    my %this_domain;
                   13069: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   13070: 			       'lang_def', 'city', 'longi', 'lati',
                   13071: 			       'primary') {
                   13072: 		$this_domain{$field} = shift(@elements);
                   13073: 	    }
                   13074: 	    $domain{$name} = \%this_domain;
1.852     albertel 13075: 	}
                   13076:     }
1.864     albertel 13077: 
                   13078:     sub reset_domain_info {
                   13079: 	undef($loaded);
                   13080: 	undef(%domain);
                   13081:     }
                   13082: 
1.852     albertel 13083:     sub load_domain_tab {
1.1172.2.70  raeburn  13084: 	my ($ignore_cache,$nocache) = @_;
                   13085: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 13086: 	my $fh;
1.1172.2.96  raeburn  13087: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 13088: 	    my @lines = <$fh>;
                   13089: 	    &parse_domain_tab(\@lines);
1.448     albertel 13090: 	}
1.852     albertel 13091: 	close($fh);
                   13092: 	$loaded = 1;
1.327     albertel 13093:     }
1.846     albertel 13094: 
                   13095:     sub domain {
1.852     albertel 13096: 	&load_domain_tab() if (!$loaded);
                   13097: 
1.846     albertel 13098: 	my ($name,$what) = @_;
                   13099: 	return if ( !exists($domain{$name}) );
                   13100: 
                   13101: 	if (!$what) {
                   13102: 	    return $domain{$name}{'description'};
                   13103: 	}
                   13104: 	return $domain{$name}{$what};
                   13105:     }
1.974     raeburn  13106: 
                   13107:     sub domain_info {
                   13108:         &load_domain_tab() if (!$loaded);
                   13109:         return %domain;
                   13110:     }
                   13111: 
1.327     albertel 13112: }
                   13113: 
                   13114: 
1.1       albertel 13115: # ------------------------------------------------------------- Read hosts file
                   13116: {
1.838     albertel 13117:     my %hostname;
1.844     albertel 13118:     my %hostdom;
1.845     albertel 13119:     my %libserv;
1.852     albertel 13120:     my $loaded;
1.888     albertel 13121:     my %name_to_host;
1.1074    raeburn  13122:     my %internetdom;
1.1107    raeburn  13123:     my %LC_dns_serv;
1.852     albertel 13124: 
                   13125:     sub parse_hosts_tab {
                   13126: 	my ($file) = @_;
                   13127: 	foreach my $configline (@$file) {
                   13128: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  13129:             chomp($configline);
                   13130: 	    if ($configline =~ /^\^/) {
                   13131:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   13132:                     $LC_dns_serv{$1} = 1;
                   13133:                 }
                   13134:                 next;
                   13135:             }
1.1074    raeburn  13136: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 13137: 	    $name=~s/\s//g;
                   13138: 	    if ($id && $domain && $role && $name) {
1.1172.2.96  raeburn  13139:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   13140:                     my $curr = $hostname{$id};
                   13141:                     my $skip;
                   13142:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   13143:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   13144:                             $skip = 1;
                   13145:                         } else {
                   13146:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   13147:                         }
                   13148:                     }
                   13149:                     unless ($skip) {
                   13150:                         push(@{$name_to_host{$name}},$id);
                   13151:                     }
                   13152:                 } else {
                   13153:                     push(@{$name_to_host{$name}},$id);
                   13154:                 }
1.852     albertel 13155: 		$hostname{$id}=$name;
                   13156: 		$hostdom{$id}=$domain;
                   13157: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  13158:                 if (defined($protocol)) {
                   13159:                     if ($protocol eq 'https') {
                   13160:                         $protocol{$id} = $protocol;
                   13161:                     } else {
                   13162:                         $protocol{$id} = 'http'; 
                   13163:                     }
1.968     raeburn  13164:                 } else {
1.969     raeburn  13165:                     $protocol{$id} = 'http';
1.968     raeburn  13166:                 }
1.1074    raeburn  13167:                 if (defined($intdom)) {
                   13168:                     $internetdom{$id} = $intdom;
                   13169:                 }
1.852     albertel 13170: 	    }
                   13171: 	}
                   13172:     }
1.864     albertel 13173:     
                   13174:     sub reset_hosts_info {
1.897     albertel 13175: 	&purge_remembered();
1.864     albertel 13176: 	&reset_domain_info();
                   13177: 	&reset_hosts_ip_info();
1.892     albertel 13178: 	undef(%name_to_host);
1.864     albertel 13179: 	undef(%hostname);
                   13180: 	undef(%hostdom);
                   13181: 	undef(%libserv);
                   13182: 	undef($loaded);
                   13183:     }
1.1       albertel 13184: 
1.852     albertel 13185:     sub load_hosts_tab {
1.1172.2.70  raeburn  13186: 	my ($ignore_cache,$nocache) = @_;
                   13187: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96  raeburn  13188: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 13189: 	my @config = <$config>;
                   13190: 	&parse_hosts_tab(\@config);
                   13191: 	close($config);
                   13192: 	$loaded=1;
1.1       albertel 13193:     }
1.852     albertel 13194: 
1.838     albertel 13195:     sub hostname {
1.852     albertel 13196: 	&load_hosts_tab() if (!$loaded);
                   13197: 
1.838     albertel 13198: 	my ($lonid) = @_;
                   13199: 	return $hostname{$lonid};
                   13200:     }
1.845     albertel 13201: 
1.838     albertel 13202:     sub all_hostnames {
1.852     albertel 13203: 	&load_hosts_tab() if (!$loaded);
                   13204: 
1.838     albertel 13205: 	return %hostname;
                   13206:     }
1.845     albertel 13207: 
1.888     albertel 13208:     sub all_names {
1.1172.2.70  raeburn  13209:         my ($ignore_cache,$nocache) = @_;
                   13210: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 13211: 
                   13212: 	return %name_to_host;
                   13213:     }
                   13214: 
1.974     raeburn  13215:     sub all_host_domain {
                   13216:         &load_hosts_tab() if (!$loaded);
                   13217:         return %hostdom;
                   13218:     }
                   13219: 
1.845     albertel 13220:     sub is_library {
1.852     albertel 13221: 	&load_hosts_tab() if (!$loaded);
                   13222: 
1.845     albertel 13223: 	return exists($libserv{$_[0]});
                   13224:     }
                   13225: 
                   13226:     sub all_library {
1.852     albertel 13227: 	&load_hosts_tab() if (!$loaded);
                   13228: 
1.845     albertel 13229: 	return %libserv;
                   13230:     }
                   13231: 
1.1062    droeschl 13232:     sub unique_library {
                   13233: 	#2x reverse removes all hostnames that appear more than once
                   13234:         my %unique = reverse &all_library();
                   13235:         return reverse %unique;
                   13236:     }
                   13237: 
1.841     albertel 13238:     sub get_servers {
1.852     albertel 13239: 	&load_hosts_tab() if (!$loaded);
                   13240: 
1.841     albertel 13241: 	my ($domain,$type) = @_;
                   13242: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   13243: 	                                          : %hostname;
                   13244: 	my %result;
1.842     albertel 13245: 	if (ref($domain) eq 'ARRAY') {
                   13246: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 13247: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 13248: 		    $result{$host} = $hostname;
                   13249: 		}
                   13250: 	    }
                   13251: 	} else {
                   13252: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   13253: 		if ($hostdom{$host} eq $domain) {
                   13254: 		    $result{$host} = $hostname;
                   13255: 		}
1.841     albertel 13256: 	    }
                   13257: 	}
                   13258: 	return %result;
                   13259:     }
1.845     albertel 13260: 
1.1062    droeschl 13261:     sub get_unique_servers {
                   13262:         my %unique = reverse &get_servers(@_);
                   13263: 	return reverse %unique;
                   13264:     }
                   13265: 
1.844     albertel 13266:     sub host_domain {
1.852     albertel 13267: 	&load_hosts_tab() if (!$loaded);
                   13268: 
1.844     albertel 13269: 	my ($lonid) = @_;
                   13270: 	return $hostdom{$lonid};
                   13271:     }
                   13272: 
1.841     albertel 13273:     sub all_domains {
1.852     albertel 13274: 	&load_hosts_tab() if (!$loaded);
                   13275: 
1.841     albertel 13276: 	my %seen;
                   13277: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   13278: 	return @uniq;
                   13279:     }
1.1074    raeburn  13280: 
                   13281:     sub internet_dom {
                   13282:         &load_hosts_tab() if (!$loaded);
                   13283: 
                   13284:         my ($lonid) = @_;
                   13285:         return $internetdom{$lonid};
                   13286:     }
1.1107    raeburn  13287: 
                   13288:     sub is_LC_dns {
                   13289:         &load_hosts_tab() if (!$loaded);
                   13290: 
                   13291:         my ($hostname) = @_;
                   13292:         return exists($LC_dns_serv{$hostname});
                   13293:     }
                   13294: 
1.1       albertel 13295: }
                   13296: 
1.847     albertel 13297: { 
                   13298:     my %iphost;
1.856     albertel 13299:     my %name_to_ip;
                   13300:     my %lonid_to_ip;
1.869     albertel 13301: 
1.847     albertel 13302:     sub get_hosts_from_ip {
                   13303: 	my ($ip) = @_;
                   13304: 	my %iphosts = &get_iphost();
                   13305: 	if (ref($iphosts{$ip})) {
                   13306: 	    return @{$iphosts{$ip}};
                   13307: 	}
                   13308: 	return;
1.839     albertel 13309:     }
1.864     albertel 13310:     
                   13311:     sub reset_hosts_ip_info {
                   13312: 	undef(%iphost);
                   13313: 	undef(%name_to_ip);
                   13314: 	undef(%lonid_to_ip);
                   13315:     }
1.856     albertel 13316: 
                   13317:     sub get_host_ip {
                   13318: 	my ($lonid) = @_;
                   13319: 	if (exists($lonid_to_ip{$lonid})) {
                   13320: 	    return $lonid_to_ip{$lonid};
                   13321: 	}
                   13322: 	my $name=&hostname($lonid);
                   13323:    	my $ip = gethostbyname($name);
                   13324: 	return if (!$ip || length($ip) ne 4);
                   13325: 	$ip=inet_ntoa($ip);
                   13326: 	$name_to_ip{$name}   = $ip;
                   13327: 	$lonid_to_ip{$lonid} = $ip;
                   13328: 	return $ip;
                   13329:     }
1.847     albertel 13330:     
                   13331:     sub get_iphost {
1.1172.2.70  raeburn  13332: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 13333: 
1.869     albertel 13334: 	if (!$ignore_cache) {
                   13335: 	    if (%iphost) {
                   13336: 		return %iphost;
                   13337: 	    }
                   13338: 	    my ($ip_info,$cached)=
                   13339: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   13340: 	    if ($cached) {
                   13341: 		%iphost      = %{$ip_info->[0]};
                   13342: 		%name_to_ip  = %{$ip_info->[1]};
                   13343: 		%lonid_to_ip = %{$ip_info->[2]};
                   13344: 		return %iphost;
                   13345: 	    }
                   13346: 	}
1.894     albertel 13347: 
                   13348: 	# get yesterday's info for fallback
                   13349: 	my %old_name_to_ip;
                   13350: 	my ($ip_info,$cached)=
                   13351: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   13352: 	if ($cached) {
                   13353: 	    %old_name_to_ip = %{$ip_info->[1]};
                   13354: 	}
                   13355: 
1.1172.2.70  raeburn  13356: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 13357: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 13358: 	    my $ip;
                   13359: 	    if (!exists($name_to_ip{$name})) {
                   13360: 		$ip = gethostbyname($name);
                   13361: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 13362: 		    if (defined($old_name_to_ip{$name})) {
                   13363: 			$ip = $old_name_to_ip{$name};
                   13364: 			&logthis("Can't find $name defaulting to old $ip");
                   13365: 		    } else {
                   13366: 			&logthis("Name $name no IP found");
                   13367: 			next;
                   13368: 		    }
                   13369: 		} else {
                   13370: 		    $ip=inet_ntoa($ip);
1.847     albertel 13371: 		}
                   13372: 		$name_to_ip{$name} = $ip;
                   13373: 	    } else {
                   13374: 		$ip = $name_to_ip{$name};
1.653     albertel 13375: 	    }
1.888     albertel 13376: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   13377: 		$lonid_to_ip{$id} = $ip;
                   13378: 	    }
                   13379: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 13380: 	}
1.1172.2.70  raeburn  13381:         unless ($nocache) {
                   13382: 	    &do_cache_new('iphost','iphost',
                   13383: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   13384: 		          48*60*60);
                   13385:         }
1.869     albertel 13386: 
1.847     albertel 13387: 	return %iphost;
1.598     albertel 13388:     }
                   13389: 
1.992     raeburn  13390:     #
                   13391:     #  Given a DNS returns the loncapa host name for that DNS 
                   13392:     # 
                   13393:     sub host_from_dns {
                   13394:         my ($dns) = @_;
                   13395:         my @hosts;
                   13396:         my $ip;
                   13397: 
1.993     raeburn  13398:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  13399:             $ip = $name_to_ip{$dns};
                   13400:         }
                   13401:         if (!$ip) {
                   13402:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   13403:             if (length($ip) == 4) { 
                   13404: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   13405:             }
                   13406:         }
                   13407:         if ($ip) {
                   13408: 	    @hosts = get_hosts_from_ip($ip);
                   13409: 	    return $hosts[0];
                   13410:         }
                   13411:         return undef;
1.986     foxr     13412:     }
1.992     raeburn  13413: 
1.1074    raeburn  13414:     sub get_internet_names {
                   13415:         my ($lonid) = @_;
                   13416:         return if ($lonid eq '');
                   13417:         my ($idnref,$cached)=
                   13418:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   13419:         if ($cached) {
                   13420:             return $idnref;
                   13421:         }
                   13422:         my $ip = &get_host_ip($lonid);
                   13423:         my @hosts = &get_hosts_from_ip($ip);
                   13424:         my %iphost = &get_iphost();
                   13425:         my (@idns,%seen);
                   13426:         foreach my $id (@hosts) {
                   13427:             my $dom = &host_domain($id);
                   13428:             my $prim_id = &domain($dom,'primary');
                   13429:             my $prim_ip = &get_host_ip($prim_id);
                   13430:             next if ($seen{$prim_ip});
                   13431:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   13432:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   13433:                     my $intdom = &internet_dom($id);
                   13434:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   13435:                         push(@idns,$intdom);
                   13436:                     }
                   13437:                 }
                   13438:             }
                   13439:             $seen{$prim_ip} = 1;
                   13440:         }
1.1172.2.23  raeburn  13441:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  13442:     }
                   13443: 
1.986     foxr     13444: }
                   13445: 
1.1079    raeburn  13446: sub all_loncaparevs {
1.1172.2.39  raeburn  13447:     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  13448: }
                   13449: 
1.1172.2.27  raeburn  13450: # ------------------------------------------------------- Read loncaparev table
                   13451: {
                   13452:     sub load_loncaparevs {
                   13453:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96  raeburn  13454:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27  raeburn  13455:                 while (my $configline=<$config>) {
                   13456:                     chomp($configline);
                   13457:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   13458:                     $loncaparevs{$hostid}=$loncaparev;
                   13459:                 }
                   13460:                 close($config);
                   13461:             }
                   13462:         }
                   13463:     }
                   13464: }
                   13465: 
                   13466: # ----------------------------------------------------- Read serverhostID table
                   13467: {
                   13468:     sub load_serverhomeIDs {
                   13469:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96  raeburn  13470:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27  raeburn  13471:                 while (my $configline=<$config>) {
                   13472:                     chomp($configline);
                   13473:                     my ($name,$id)=split(/:/,$configline);
                   13474:                     $serverhomeIDs{$name}=$id;
                   13475:                 }
                   13476:                 close($config);
                   13477:             }
                   13478:         }
                   13479:     }
                   13480: }
                   13481: 
                   13482: 
1.862     albertel 13483: BEGIN {
                   13484: 
                   13485: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   13486:     unless ($readit) {
                   13487: {
                   13488:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   13489:     %perlvar = (%perlvar,%{$configvars});
                   13490: }
                   13491: 
                   13492: 
1.1       albertel 13493: # ------------------------------------------------------ Read spare server file
                   13494: {
1.1172.2.96  raeburn  13495:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 13496: 
                   13497:     while (my $configline=<$config>) {
                   13498:        chomp($configline);
1.284     matthew  13499:        if ($configline) {
1.784     albertel 13500: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 13501: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 13502: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 13503:        }
                   13504:     }
1.448     albertel 13505:     close($config);
1.1       albertel 13506: }
1.11      www      13507: # ------------------------------------------------------------ Read permissions
                   13508: {
1.1172.2.96  raeburn  13509:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      13510: 
                   13511:     while (my $configline=<$config>) {
1.448     albertel 13512: 	chomp($configline);
                   13513: 	if ($configline) {
                   13514: 	    my ($role,$perm)=split(/ /,$configline);
                   13515: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   13516: 	}
1.11      www      13517:     }
1.448     albertel 13518:     close($config);
1.11      www      13519: }
                   13520: 
                   13521: # -------------------------------------------- Read plain texts for permissions
                   13522: {
1.1172.2.96  raeburn  13523:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      13524: 
                   13525:     while (my $configline=<$config>) {
1.448     albertel 13526: 	chomp($configline);
                   13527: 	if ($configline) {
1.742     raeburn  13528: 	    my ($short,@plain)=split(/:/,$configline);
                   13529:             %{$prp{$short}} = ();
                   13530: 	    if (@plain > 0) {
                   13531:                 $prp{$short}{'std'} = $plain[0];
                   13532:                 for (my $i=1; $i<@plain; $i++) {
                   13533:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   13534:                 }
                   13535:             }
1.448     albertel 13536: 	}
1.135     www      13537:     }
1.448     albertel 13538:     close($config);
1.135     www      13539: }
                   13540: 
                   13541: # ---------------------------------------------------------- Read package table
                   13542: {
1.1172.2.96  raeburn  13543:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      13544: 
                   13545:     while (my $configline=<$config>) {
1.483     albertel 13546: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 13547: 	chomp($configline);
                   13548: 	my ($short,$plain)=split(/:/,$configline);
                   13549: 	my ($pack,$name)=split(/\&/,$short);
                   13550: 	if ($plain ne '') {
                   13551: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   13552: 	    $packagetab{$short}=$plain; 
                   13553: 	}
1.11      www      13554:     }
1.448     albertel 13555:     close($config);
1.329     matthew  13556: }
                   13557: 
1.1172.2.27  raeburn  13558: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  13559: 
1.1172.2.27  raeburn  13560: &load_loncaparevs();
                   13561: 
                   13562: # ------------------------------------------------------- Read serverhostID table
                   13563: 
                   13564: &load_serverhomeIDs();
1.1074    raeburn  13565: 
1.1172.2.27  raeburn  13566: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  13567: {
                   13568:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   13569:     if (-e $file) {
                   13570:         my $parser = HTML::LCParser->new($file);
                   13571:         while (my $token = $parser->get_token()) {
                   13572:             if ($token->[0] eq 'S') {
                   13573:                 my $item = $token->[1];
                   13574:                 my $name = $token->[2]{'name'};
                   13575:                 my $value = $token->[2]{'value'};
                   13576:                 if ($item ne '' && $name ne '' && $value ne '') {
                   13577:                     my $release = $parser->get_text();
                   13578:                     $release =~ s/(^\s*|\s*$ )//gx;
                   13579:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   13580:                 }
                   13581:             }
                   13582:         }
                   13583:     }
1.1073    raeburn  13584: }
                   13585: 
1.1138    raeburn  13586: # ---------------------------------------------------------- Read managers table
                   13587: {
                   13588:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96  raeburn  13589:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  13590:             while (my $configline=<$config>) {
                   13591:                 chomp($configline);
                   13592:                 next if ($configline =~ /^\#/);
                   13593:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   13594:                     $managerstab{$configline} = 1;
                   13595:                 }
                   13596:             }
                   13597:             close($config);
                   13598:         }
                   13599:     }
                   13600: }
                   13601: 
1.329     matthew  13602: # ------------- set up temporary directory
                   13603: {
1.1117    foxr     13604:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  13605: 
1.11      www      13606: }
                   13607: 
1.1172.2.104  raeburn  13608: # ------------- set default texengine (domain default overrides this)
                   13609: {
                   13610:     $deftex = LONCAPA::texengine();
                   13611: }
                   13612: 
1.794     albertel 13613: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   13614: 				'compress_threshold'=> 20_000,
                   13615:  			        });
1.185     www      13616: 
1.281     www      13617: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      13618: $dumpcount=0;
1.958     www      13619: $locknum=0;
1.22      www      13620: 
1.163     harris41 13621: &logtouch();
1.672     albertel 13622: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      13623: $readit=1;
1.564     albertel 13624:     {
                   13625: 	use integer;
                   13626: 	my $test=(2**32)+1;
1.568     albertel 13627: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 13628: 	&logthis(" Detected 64bit platform ($_64bit)");
                   13629:     }
1.195     www      13630: }
1.1       albertel 13631: }
1.179     www      13632: 
1.1       albertel 13633: 1;
1.191     harris41 13634: __END__
                   13635: 
1.243     albertel 13636: =pod
                   13637: 
1.191     harris41 13638: =head1 NAME
                   13639: 
1.243     albertel 13640: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 13641: 
                   13642: =head1 SYNOPSIS
                   13643: 
1.243     albertel 13644: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 13645: 
                   13646:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   13647: 
1.243     albertel 13648: Common parameters:
                   13649: 
                   13650: =over 4
                   13651: 
                   13652: =item *
                   13653: 
                   13654: $uname : an internal username (if $cname expecting a course Id specifically)
                   13655: 
                   13656: =item *
                   13657: 
                   13658: $udom : a domain (if $cdom expecting a course's domain specifically)
                   13659: 
                   13660: =item *
                   13661: 
                   13662: $symb : a resource instance identifier
                   13663: 
                   13664: =item *
                   13665: 
                   13666: $namespace : the name of a .db file that contains the data needed or
                   13667: being set.
                   13668: 
                   13669: =back
                   13670: 
1.394     bowersj2 13671: =head1 OVERVIEW
1.191     harris41 13672: 
1.394     bowersj2 13673: lonnet provides subroutines which interact with the
                   13674: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   13675: about classes, users, and resources.
1.243     albertel 13676: 
                   13677: For many of these objects you can also use this to store data about
                   13678: them or modify them in various ways.
1.191     harris41 13679: 
1.394     bowersj2 13680: =head2 Symbs
1.191     harris41 13681: 
1.394     bowersj2 13682: To identify a specific instance of a resource, LON-CAPA uses symbols
                   13683: or "symbs"X<symb>. These identifiers are built from the URL of the
                   13684: map, the resource number of the resource in the map, and the URL of
                   13685: the resource itself. The latter is somewhat redundant, but might help
                   13686: if maps change.
                   13687: 
                   13688: An example is
                   13689: 
                   13690:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   13691: 
                   13692: The respective map entry is
                   13693: 
                   13694:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   13695:   title="Problem 2">
                   13696:  </resource>
                   13697: 
                   13698: Symbs are used by the random number generator, as well as to store and
                   13699: restore data specific to a certain instance of for example a problem.
                   13700: 
                   13701: =head2 Storing And Retrieving Data
                   13702: 
                   13703: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   13704: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   13705: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   13706: is is the non-critical message twin of cstore. These functions are for
                   13707: handlers to store a perl hash to a user's permanent data space in an
                   13708: easy manner, and to retrieve it again on another call. It is expected
                   13709: that a handler would use this once at the beginning to retrieve data,
                   13710: and then again once at the end to send only the new data back.
                   13711: 
                   13712: The data is stored in the user's data directory on the user's
                   13713: homeserver under the ID of the course.
                   13714: 
                   13715: The hash that is returned by restore will have all of the previous
                   13716: value for all of the elements of the hash.
                   13717: 
                   13718: Example:
                   13719: 
                   13720:  #creating a hash
                   13721:  my %hash;
                   13722:  $hash{'foo'}='bar';
                   13723: 
                   13724:  #storing it
                   13725:  &Apache::lonnet::cstore(\%hash);
                   13726: 
                   13727:  #changing a value
                   13728:  $hash{'foo'}='notbar';
                   13729: 
                   13730:  #adding a new value
                   13731:  $hash{'bar'}='foo';
                   13732:  &Apache::lonnet::cstore(\%hash);
                   13733: 
                   13734:  #retrieving the hash
                   13735:  my %history=&Apache::lonnet::restore();
                   13736: 
                   13737:  #print the hash
                   13738:  foreach my $key (sort(keys(%history))) {
                   13739:    print("\%history{$key} = $history{$key}");
                   13740:  }
                   13741: 
                   13742: Will print out:
1.191     harris41 13743: 
1.394     bowersj2 13744:  %history{1:foo} = bar
                   13745:  %history{1:keys} = foo:timestamp
                   13746:  %history{1:timestamp} = 990455579
                   13747:  %history{2:bar} = foo
                   13748:  %history{2:foo} = notbar
                   13749:  %history{2:keys} = foo:bar:timestamp
                   13750:  %history{2:timestamp} = 990455580
                   13751:  %history{bar} = foo
                   13752:  %history{foo} = notbar
                   13753:  %history{timestamp} = 990455580
                   13754:  %history{version} = 2
                   13755: 
                   13756: Note that the special hash entries C<keys>, C<version> and
                   13757: C<timestamp> were added to the hash. C<version> will be equal to the
                   13758: total number of versions of the data that have been stored. The
                   13759: C<timestamp> attribute will be the UNIX time the hash was
                   13760: stored. C<keys> is available in every historical section to list which
                   13761: keys were added or changed at a specific historical revision of a
                   13762: hash.
                   13763: 
                   13764: B<Warning>: do not store the hash that restore returns directly. This
                   13765: will cause a mess since it will restore the historical keys as if the
                   13766: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 13767: 
1.394     bowersj2 13768: Calling convention:
1.191     harris41 13769: 
1.1172.2.27  raeburn  13770:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64  raeburn  13771:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 13772: 
1.394     bowersj2 13773: For more detailed information, see lonnet specific documentation.
1.191     harris41 13774: 
1.394     bowersj2 13775: =head1 RETURN MESSAGES
1.191     harris41 13776: 
1.394     bowersj2 13777: =over 4
1.191     harris41 13778: 
1.394     bowersj2 13779: =item * B<con_lost>: unable to contact remote host
1.191     harris41 13780: 
1.394     bowersj2 13781: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   13782: when the connection is brought back up
1.191     harris41 13783: 
1.394     bowersj2 13784: =item * B<con_failed>: unable to contact remote host and unable to save message
                   13785: for later delivery
1.191     harris41 13786: 
1.967     bisitz   13787: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 13788: 
1.394     bowersj2 13789: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 13790: that was requested
1.191     harris41 13791: 
1.243     albertel 13792: =back
1.191     harris41 13793: 
1.243     albertel 13794: =head1 PUBLIC SUBROUTINES
1.191     harris41 13795: 
1.243     albertel 13796: =head2 Session Environment Functions
1.191     harris41 13797: 
1.243     albertel 13798: =over 4
1.191     harris41 13799: 
1.394     bowersj2 13800: =item * 
                   13801: X<appenv()>
1.949     raeburn  13802: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 13803: the user envirnoment file, and will be restored for each access this
1.620     albertel 13804: user makes during this session, also modifies the %env for the current
1.949     raeburn  13805: process. Optional rolesarrayref - if defined contains a reference to an array
                   13806: of roles which are exempt from the restriction on modifying user.role entries 
                   13807: in the user's environment.db and in %env.    
1.191     harris41 13808: 
                   13809: =item *
1.394     bowersj2 13810: X<delenv()>
1.987     raeburn  13811: B<delenv($delthis,$regexp)>: removes all items from the session
                   13812: environment file that begin with $delthis. If the 
                   13813: optional second arg - $regexp - is true, $delthis is treated as a 
                   13814: regular expression, otherwise \Q$delthis\E is used. 
                   13815: The values are also deleted from the current processes %env.
1.191     harris41 13816: 
1.795     albertel 13817: =item * get_env_multiple($name) 
                   13818: 
                   13819: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   13820: values may be defined and end up as an array ref.
                   13821: 
                   13822: returns an array of values
                   13823: 
1.243     albertel 13824: =back
                   13825: 
                   13826: =head2 User Information
1.191     harris41 13827: 
1.243     albertel 13828: =over 4
1.191     harris41 13829: 
                   13830: =item *
1.394     bowersj2 13831: X<queryauthenticate()>
                   13832: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 13833: authentication scheme
                   13834: 
                   13835: =item *
1.394     bowersj2 13836: X<authenticate()>
1.1073    raeburn  13837: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 13838: authenticate user from domain's lib servers (first use the current
                   13839: one). C<$upass> should be the users password.
1.1073    raeburn  13840: $checkdefauth is optional (value is 1 if a check should be made to
                   13841:    authenticate user using default authentication method, and allow
                   13842:    account creation if username does not have account in the domain).
                   13843: $clientcancheckhost is optional (value is 1 if checking whether the
                   13844:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 13845: 
                   13846: =item *
1.394     bowersj2 13847: X<homeserver()>
                   13848: B<homeserver($uname,$udom)>: find the server which has
                   13849: the user's directory and files (there must be only one), this caches
                   13850: the answer, and also caches if there is a borken connection.
1.191     harris41 13851: 
                   13852: =item *
1.394     bowersj2 13853: X<idget()>
                   13854: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   13855: (IDs are a unique resource in a domain, there must be only 1 ID per
                   13856: username, and only 1 username per ID in a specific domain) (returns
                   13857: hash: id=>name,id=>name)
1.191     harris41 13858: 
                   13859: =item *
1.394     bowersj2 13860: X<idrget()>
                   13861: B<idrget($udom,@unames)>: find the IDs behind a list of
                   13862: usernames (returns hash: name=>id,name=>id)
1.191     harris41 13863: 
                   13864: =item *
1.394     bowersj2 13865: X<idput()>
                   13866: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 13867: 
                   13868: =item *
1.394     bowersj2 13869: X<rolesinit()>
1.1169    droeschl 13870: B<rolesinit($udom,$username)>: get user privileges.
                   13871: returns user role, first access and timer interval hashes
1.243     albertel 13872: 
                   13873: =item *
1.1171    droeschl 13874: X<privileged()>
                   13875: B<privileged($username,$domain)>: returns a true if user has a
                   13876: privileged and active role (i.e. su or dc), false otherwise.
                   13877: 
                   13878: =item *
1.551     albertel 13879: X<getsection()>
                   13880: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 13881: course $cname, return section name/number or '' for "not in course"
                   13882: and '-1' for "no section"
                   13883: 
                   13884: =item *
1.394     bowersj2 13885: X<userenvironment()>
                   13886: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 13887: passed in @what from the requested user's environment, returns a hash
                   13888: 
1.858     raeburn  13889: =item * 
                   13890: X<userlog_query()>
1.859     albertel 13891: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   13892: activity.log file. %filters defines filters applied when parsing the
                   13893: log file. These can be start or end timestamps, or the type of action
                   13894: - log to look for Login or Logout events, check for Checkin or
                   13895: Checkout, role for role selection. The response is in the form
                   13896: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   13897: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  13898: 
1.243     albertel 13899: =back
                   13900: 
                   13901: =head2 User Roles
                   13902: 
                   13903: =over 4
                   13904: 
                   13905: =item *
                   13906: 
1.1172.2.65  raeburn  13907: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   13908: returns codes for allowed actions.
                   13909: 
                   13910: The first argument is required, all others are optional.
                   13911: 
                   13912: $priv is the privilege being checked.
                   13913: $uri contains additional information about what is being checked for access (e.g.,
                   13914: URL, course ID etc.).
                   13915: $symb is the unique resource instance identifier in a course; if needed,
                   13916: but not provided, it will be retrieved via a call to &symbread().
                   13917: $role is the role for which a priv is being checked (only used if priv is evb).
                   13918: $clientip is the user's IP address (only used when checking for access to portfolio
                   13919: files).
                   13920: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
                   13921: prevents recursive calls to &allowed.
                   13922: 
1.243     albertel 13923:  F: full access
                   13924:  U,I,K: authentication modes (cxx only)
                   13925:  '': forbidden
                   13926:  1: user needs to choose course
                   13927:  2: browse allowed
1.766     albertel 13928:  A: passphrase authentication needed
1.1172.2.65  raeburn  13929:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 13930: 
                   13931: =item *
                   13932: 
1.1172.2.13  raeburn  13933: constructaccess($url,$setpriv) : check for access to construction space URL
                   13934: 
                   13935: See if the owner domain and name in the URL match those in the
                   13936: expected environment.  If so, return three element list
                   13937: ($ownername,$ownerdomain,$ownerhome).
                   13938: 
                   13939: Otherwise return the null string.
                   13940: 
                   13941: If second argument 'setpriv' is true, it assigns the privileges,
                   13942: and returns the same three element list, unless the owner has
                   13943: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   13944: in which case the null string is returned.
                   13945: 
                   13946: =item *
                   13947: 
1.1172.2.84  raeburn  13948: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   13949: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   13950: for system, domain, and course level. $uname and $udom are optional (current
                   13951: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 13952: 
                   13953: =item *
                   13954: 
1.988     raeburn  13955: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   13956: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  13957: $type is Course (default) or Community.
1.988     raeburn  13958: If $forcedefault evaluates to true, text returned will be default 
                   13959: text for $type. Otherwise, if this is a course, the text returned 
                   13960: will be a custom name for the role (if defined in the course's 
                   13961: environment).  If no custom name is defined the default is returned.
                   13962:    
1.832     raeburn  13963: =item *
                   13964: 
1.1172.2.23  raeburn  13965: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  13966: All arguments are optional. Returns a hash of a roles, either for
                   13967: co-author/assistant author roles for a user's Construction Space
1.906     albertel 13968: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  13969: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   13970: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   13971: For each key, value is set to colon-separated start and end times for
                   13972: the role.  If no username and domain are specified, will default to
1.934     raeburn  13973: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  13974: of role statuses (active, future or previous), roles 
                   13975: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   13976: to restrict the list of roles reported. If no array ref is 
                   13977: provided for types, will default to return only active roles.
1.834     albertel 13978: 
1.1172.2.13  raeburn  13979: =item *
                   13980: 
                   13981: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   13982: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   13983: 
                   13984: Additional optional arguments are: $type (if role checking is to be restricted
                   13985: to certain user status types -- previous (expired roles), active (currently
                   13986: available roles) or future (roles available in the future), and
                   13987: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  13988: have active Domain Coordinator role in course's domain or in additional
                   13989: domains (specified in 'Domains to check for privileged users' in course
                   13990: environment -- set via:  Course Settings -> Classlists and staff listing).
                   13991: 
                   13992: =item *
                   13993: 
                   13994: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   13995: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   13996: $possdomains and $possroles are optional array refs -- to domains to check and
                   13997: roles to check.  If $possdomains is not specified, a dump will be done of the
                   13998: users' roles.db to check for a dc or su role in any domain. This can be
                   13999: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   14000: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   14001: this then allows &privileged_by_domain() to be used, which caches the identity
                   14002: of privileged users, eliminating the need for repeated calls to &dump().
                   14003: 
                   14004: =item *
                   14005: 
                   14006: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   14007: where the outer hash keys are domains specified in the $possdomains array ref,
                   14008: next inner hash keys are privileged roles specified in the $roles array ref,
                   14009: and the innermost hash contains key = value pairs for username:domain = end:start
                   14010: for active or future "privileged" users with that role in that domain. To avoid
                   14011: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   14012: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  14013: 
1.243     albertel 14014: =back
                   14015: 
                   14016: =head2 User Modification
                   14017: 
                   14018: =over 4
                   14019: 
                   14020: =item *
                   14021: 
1.957     raeburn  14022: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 14023: user for the level given by URL.  Optional start and end dates (leave empty
                   14024: string or zero for "no date")
1.191     harris41 14025: 
                   14026: =item *
                   14027: 
1.243     albertel 14028: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   14029: change a users, password, possible return values are: ok,
                   14030: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   14031: refused
1.191     harris41 14032: 
                   14033: =item *
                   14034: 
1.243     albertel 14035: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 14036: 
                   14037: =item *
                   14038: 
1.1058    raeburn  14039: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   14040:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   14041: 
                   14042: will update user information (firstname,middlename,lastname,generation,
                   14043: permanentemail), and if forceid is true, student/employee ID also.
                   14044: A user's institutional affiliation(s) can also be updated.
                   14045: User information fields will not be overwritten with empty entries 
                   14046: unless the field is included in the $candelete array reference.
                   14047: This array is included when a single user is modified via "Manage Users",
                   14048: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 14049: 
                   14050: =item *
                   14051: 
1.286     matthew  14052: modifystudent
                   14053: 
1.957     raeburn  14054: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  14055: The course id is resolved based on the current user's environment.  
                   14056: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  14057: associated with a course.
                   14058: 
1.297     matthew  14059: This call is essentially a wrapper for lonnet::modifyuser and
                   14060: lonnet::modify_student_enrollment
1.286     matthew  14061: 
                   14062: Inputs: 
                   14063: 
                   14064: =over 4
                   14065: 
1.957     raeburn  14066: =item B<$udom> Student's loncapa domain
1.286     matthew  14067: 
1.957     raeburn  14068: =item B<$uname> Student's loncapa login name
1.286     matthew  14069: 
1.964     bisitz   14070: =item B<$uid> Student/Employee ID
1.286     matthew  14071: 
1.957     raeburn  14072: =item B<$umode> Student's authentication mode
1.286     matthew  14073: 
1.957     raeburn  14074: =item B<$upass> Student's password
1.286     matthew  14075: 
1.957     raeburn  14076: =item B<$first> Student's first name
1.286     matthew  14077: 
1.957     raeburn  14078: =item B<$middle> Student's middle name
1.286     matthew  14079: 
1.957     raeburn  14080: =item B<$last> Student's last name
1.286     matthew  14081: 
1.957     raeburn  14082: =item B<$gene> Student's generation
1.286     matthew  14083: 
1.957     raeburn  14084: =item B<$usec> Student's section in course
1.286     matthew  14085: 
                   14086: =item B<$end> Unix time of the roles expiration
                   14087: 
                   14088: =item B<$start> Unix time of the roles start date
                   14089: 
                   14090: =item B<$forceid> If defined, allow $uid to be changed
                   14091: 
                   14092: =item B<$desiredhome> server to use as home server for student
                   14093: 
1.957     raeburn  14094: =item B<$email> Student's permanent e-mail address
                   14095: 
                   14096: =item B<$type> Type of enrollment (auto or manual)
                   14097: 
1.963     raeburn  14098: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   14099: 
                   14100: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  14101: 
1.963     raeburn  14102: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  14103: 
1.963     raeburn  14104: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  14105: 
1.1172.2.19  raeburn  14106: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   14107: 
                   14108: =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  14109: 
1.286     matthew  14110: =back
1.297     matthew  14111: 
                   14112: =item *
                   14113: 
                   14114: modify_student_enrollment
                   14115: 
1.1172.2.31  raeburn  14116: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  14117: 'role.request.course' must be defined for this function to proceed.
                   14118: 
                   14119: Inputs:
                   14120: 
                   14121: =over 4
                   14122: 
1.1172.2.31  raeburn  14123: =item $udom, student's domain
1.297     matthew  14124: 
1.1172.2.31  raeburn  14125: =item $uname, student's name
1.297     matthew  14126: 
1.1172.2.31  raeburn  14127: =item $uid, student's user id
1.297     matthew  14128: 
1.1172.2.31  raeburn  14129: =item $first, student's first name
1.297     matthew  14130: 
                   14131: =item $middle
                   14132: 
                   14133: =item $last
                   14134: 
                   14135: =item $gene
                   14136: 
                   14137: =item $usec
                   14138: 
                   14139: =item $end
                   14140: 
                   14141: =item $start
                   14142: 
1.957     raeburn  14143: =item $type
                   14144: 
                   14145: =item $locktype
                   14146: 
                   14147: =item $cid
                   14148: 
                   14149: =item $selfenroll
                   14150: 
                   14151: =item $context
                   14152: 
1.1172.2.19  raeburn  14153: =item $credits, number of credits student will earn from this class
                   14154: 
1.1172.2.76  raeburn  14155: =item $instsec, institutional course section code for student
                   14156: 
1.297     matthew  14157: =back
                   14158: 
1.191     harris41 14159: 
                   14160: =item *
                   14161: 
1.243     albertel 14162: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   14163: custom role; give a custom role to a user for the level given by URL.  Specify
                   14164: name and domain of role author, and role name
1.191     harris41 14165: 
                   14166: =item *
                   14167: 
1.243     albertel 14168: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 14169: 
                   14170: =item *
                   14171: 
1.243     albertel 14172: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   14173: 
                   14174: =back
                   14175: 
                   14176: =head2 Course Infomation
                   14177: 
                   14178: =over 4
1.191     harris41 14179: 
                   14180: =item *
                   14181: 
1.1118    foxr     14182: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 14183: specified course id, including all environment settings for the
                   14184: course, the description of the course will be in the hash under the
                   14185: key 'description'
1.191     harris41 14186: 
1.1118    foxr     14187: $options is an optional parameter that if supplied is a hash reference that controls
                   14188: what how this function works.  It has the following key/values:
                   14189: 
                   14190: =over 4
                   14191: 
                   14192: =item freshen_cache
                   14193: 
                   14194: If defined, and the environment cache for the course is valid, it is 
                   14195: returned in the returned hash.
                   14196: 
                   14197: =item one_time
                   14198: 
                   14199: If defined, the last cache time is set to _now_
                   14200: 
                   14201: =item user
                   14202: 
                   14203: If defined, the supplied username is used instead of the current user.
                   14204: 
                   14205: 
                   14206: =back
                   14207: 
1.191     harris41 14208: =item *
                   14209: 
1.624     albertel 14210: resdata($name,$domain,$type,@which) : request for current parameter
                   14211: setting for a specific $type, where $type is either 'course' or 'user',
                   14212: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  14213: answers for 10 minutes.
1.243     albertel 14214: 
1.877     foxr     14215: =item *
                   14216: 
                   14217: get_courseresdata($courseid, $domain) : dump the entire course resource
                   14218: data base, returning a hash that is keyed by the resource name and has
                   14219: values that are the resource value.  I believe that the timestamps and
                   14220: versions are also returned.
                   14221: 
1.1172.2.31  raeburn  14222: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   14223: supplemental content area. This routine caches the number of files for
                   14224: 10 minutes.
                   14225: 
1.243     albertel 14226: =back
                   14227: 
                   14228: =head2 Course Modification
                   14229: 
                   14230: =over 4
1.191     harris41 14231: 
                   14232: =item *
                   14233: 
1.243     albertel 14234: writecoursepref($courseid,%prefs) : write preferences (environment
                   14235: database) for a course
1.191     harris41 14236: 
                   14237: =item *
                   14238: 
1.1011    raeburn  14239: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   14240: 
                   14241: =item *
                   14242: 
1.1038    raeburn  14243: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 14244: 
1.1167    droeschl 14245: =item *
                   14246: 
                   14247: is_course($courseid), is_course($cdom, $cnum)
                   14248: 
                   14249: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   14250: two component version $cdom, $cnum. It checks if the specified course exists.
                   14251: 
                   14252: Returns:
                   14253:     undef if the course doesn't exist, otherwise
                   14254:     in scalar context the combined courseid.
                   14255:     in list context the two components of the course identifier, domain and 
                   14256:     courseid.    
                   14257: 
1.243     albertel 14258: =back
                   14259: 
                   14260: =head2 Resource Subroutines
                   14261: 
                   14262: =over 4
1.191     harris41 14263: 
                   14264: =item *
                   14265: 
1.243     albertel 14266: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 14267: 
                   14268: =item *
                   14269: 
1.243     albertel 14270: repcopy($filename) : subscribes to the requested file, and attempts to
                   14271: replicate from the owning library server, Might return
1.607     raeburn  14272: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   14273: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 14274: resource. Expects the local filesystem pathname
                   14275: (/home/httpd/html/res/....)
                   14276: 
                   14277: =back
                   14278: 
                   14279: =head2 Resource Information
                   14280: 
                   14281: =over 4
1.191     harris41 14282: 
                   14283: =item *
                   14284: 
1.1172.2.28  raeburn  14285: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   14286: and returns the value of a variety of different possible values,
                   14287: $varname should be a request string, and the other parameters can be
                   14288: used to specify who and what one is asking about. Ordinarily, $cid 
                   14289: does not need to be specified, as it is retrived from 
                   14290: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   14291: within lonuserstate::loadmap() when initializing a course, before
                   14292: $env{'request.course.id'} has been set, so it needs to be provided
                   14293: in that one case.
1.243     albertel 14294: 
                   14295: Possible values for $varname are environment.lastname (or other item
                   14296: from the envirnment hash), user.name (or someother aspect about the
                   14297: user), resource.0.maxtries (or some other part and parameter of a
                   14298: resource)
1.204     albertel 14299: 
                   14300: =item *
                   14301: 
1.243     albertel 14302: directcondval($number) : get current value of a condition; reads from a state
                   14303: string
1.204     albertel 14304: 
                   14305: =item *
                   14306: 
1.243     albertel 14307: condval($condidx) : value of condition index based on state
1.204     albertel 14308: 
                   14309: =item *
                   14310: 
1.243     albertel 14311: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   14312: resource's metadata, $what should be either a specific key, or either
                   14313: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   14314: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   14315: 
                   14316: this function automatically caches all requests
1.191     harris41 14317: 
                   14318: =item *
                   14319: 
1.243     albertel 14320: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   14321: network of library servers; returns file handle of where SQL and regex results
                   14322: will be stored for query
1.191     harris41 14323: 
                   14324: =item *
                   14325: 
1.1172.2.66  raeburn  14326: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
                   14327: return symbolic list entry (all arguments optional).
                   14328: 
                   14329: Args: filename is the filename (including path) for the file for which a symb
                   14330: is required; donotrecurse, if true will prevent calls to allowed() being made
                   14331: to check access status if more than one resource was found in the bighash
                   14332: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
                   14333: a randompick); ignorecachednull, if true will prevent a symb of '' being
                   14334: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   14335: cause possible symbs to be checked to determine if they are subject to content
                   14336: blocking, if so they will not be included as possible symbs; possibles is a
                   14337: ref to a hash, which, as a side effect, will be populated with all possible
                   14338: symbs (content blocking not tested).
                   14339: 
1.243     albertel 14340: returns the data handle
1.191     harris41 14341: 
                   14342: =item *
                   14343: 
1.1172.2.17  raeburn  14344: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  14345: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 14346: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  14347: on failure, user must be in a course, as it assumes the existence of
                   14348: the course initial hash, and uses $env('request.course.id'}.  The third
                   14349: arg is an optional reference to a scalar.  If this arg is passed in the
                   14350: call to symbverify, it will be set to 1 if the symb has been set to be 
                   14351: encrypted; otherwise it will be null.
1.243     albertel 14352: 
1.191     harris41 14353: =item *
                   14354: 
1.243     albertel 14355: symbclean($symb) : removes versions numbers from a symb, returns the
                   14356: cleaned symb
1.191     harris41 14357: 
                   14358: =item *
                   14359: 
1.243     albertel 14360: is_on_map($uri) : checks if the $uri is somewhere on the current
                   14361: course map, user must be in a course for it to work.
1.191     harris41 14362: 
                   14363: =item *
                   14364: 
1.243     albertel 14365: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 14366: 
                   14367: =item *
                   14368: 
1.243     albertel 14369: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   14370: a random seed, all arguments are optional, if they aren't sent it uses the
                   14371: environment to derive them. Note: if symb isn't sent and it can't get one
                   14372: from &symbread it will use the current time as its return value
1.191     harris41 14373: 
                   14374: =item *
                   14375: 
1.243     albertel 14376: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   14377: unfakeable, receipt
1.191     harris41 14378: 
                   14379: =item *
                   14380: 
1.620     albertel 14381: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 14382: 
                   14383: =item *
                   14384: 
1.243     albertel 14385: countacc($url) : count the number of accesses to a given URL
1.191     harris41 14386: 
                   14387: =item *
                   14388: 
1.243     albertel 14389: 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 14390: 
                   14391: =item *
                   14392: 
1.243     albertel 14393: 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 14394: 
                   14395: =item *
                   14396: 
1.243     albertel 14397: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 14398: 
                   14399: =item *
                   14400: 
1.243     albertel 14401: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   14402: forcing spreadsheet to reevaluate the resource scores next time.
                   14403: 
1.1172.2.13  raeburn  14404: =item *
                   14405: 
                   14406: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   14407: when viewing in course context.
                   14408: 
                   14409:  input: six args -- filename (decluttered), course number, course domain,
                   14410:                     url, symb (if registered) and group (if this is a
                   14411:                     group item -- e.g., bulletin board, group page etc.).
                   14412: 
                   14413:  output: array of five scalars --
                   14414:          $cfile -- url for file editing if editable on current server
                   14415:          $home -- homeserver of resource (i.e., for author if published,
                   14416:                                           or course if uploaded.).
                   14417:          $switchserver --  1 if server switch will be needed.
                   14418:          $forceedit -- 1 if icon/link should be to go to edit mode
                   14419:          $forceview -- 1 if icon/link should be to go to view mode
                   14420: 
                   14421: =item *
                   14422: 
                   14423: is_course_upload($file,$cnum,$cdom)
                   14424: 
                   14425: Used in course context to determine if current file was uploaded to
                   14426: the course (i.e., would be found in /userfiles/docs on the course's
                   14427: homeserver.
                   14428: 
                   14429:   input: 3 args -- filename (decluttered), course number and course domain.
                   14430:   output: boolean -- 1 if file was uploaded.
                   14431: 
1.243     albertel 14432: =back
                   14433: 
                   14434: =head2 Storing/Retreiving Data
                   14435: 
                   14436: =over 4
1.191     harris41 14437: 
                   14438: =item *
                   14439: 
1.1172.2.64  raeburn  14440: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
                   14441: permanently for this url; hashref needs to be given and should be a \%hashname;
                   14442: the remaining args aren't required and if they aren't passed or are '' they will
                   14443: be derived from the env (with the exception of $laststore, which is an
                   14444: optional arg used when a user's submission is stored in grading).
                   14445: $laststore is $version=$timestamp, where $version is the most recent version
                   14446: number retrieved for the corresponding $symb in the $namespace db file, and
                   14447: $timestamp is the timestamp for that transaction (UNIX time).
                   14448: $laststore is currently only passed when cstore() is called by
                   14449: structuretags::finalize_storage().
1.191     harris41 14450: 
                   14451: =item *
                   14452: 
1.1172.2.64  raeburn  14453: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
                   14454: but uses critical subroutine
1.191     harris41 14455: 
                   14456: =item *
                   14457: 
1.243     albertel 14458: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   14459: all args are optional
1.191     harris41 14460: 
                   14461: =item *
                   14462: 
1.717     albertel 14463: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   14464: dumps the complete (or key matching regexp) namespace into a hash
                   14465: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   14466: normally &store()ed into
                   14467: 
                   14468: $range should be either an integer '100' (give me the first 100
                   14469:                                            matching records)
                   14470:               or be  two integers sperated by a - with no spaces
                   14471:                  '30-50' (give me the 30th through the 50th matching
                   14472:                           records)
                   14473: 
                   14474: 
                   14475: =item *
                   14476: 
1.1172.2.59  raeburn  14477: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 14478: replaces a &store() version of data with a replacement set of data
                   14479: for a particular resource in a namespace passed in the $storehash hash 
1.1172.2.59  raeburn  14480: reference. If $tolog is true, the transaction is logged in the courselog
                   14481: with an action=PUTSTORE.
1.717     albertel 14482: 
                   14483: =item *
                   14484: 
1.243     albertel 14485: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   14486: works very similar to store/cstore, but all data is stored in a
                   14487: temporary location and can be reset using tmpreset, $storehash should
                   14488: be a hash reference, returns nothing on success
1.191     harris41 14489: 
                   14490: =item *
                   14491: 
1.243     albertel 14492: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   14493: similar to restore, but all data is stored in a temporary location and
                   14494: can be reset using tmpreset. Returns a hash of values on success,
                   14495: error string otherwise.
1.191     harris41 14496: 
                   14497: =item *
                   14498: 
1.243     albertel 14499: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   14500: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 14501: 
                   14502: =item *
                   14503: 
1.243     albertel 14504: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14505: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 14506: 
                   14507: =item *
                   14508: 
1.243     albertel 14509: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   14510: namesp ($udom and $uname are optional)
1.191     harris41 14511: 
                   14512: =item *
                   14513: 
1.702     albertel 14514: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 14515: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 14516: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  14517: 
1.702     albertel 14518: $range should be either an integer '100' (give me the first 100
                   14519:                                            matching records)
                   14520:               or be  two integers sperated by a - with no spaces
                   14521:                  '30-50' (give me the 30th through the 50th matching
                   14522:                           records)
1.449     matthew  14523: =item *
                   14524: 
                   14525: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   14526: $store can be a scalar, an array reference, or if the amount to be 
                   14527: incremented is > 1, a hash reference.
                   14528: 
                   14529: ($udom and $uname are optional)
1.191     harris41 14530: 
                   14531: =item *
                   14532: 
1.243     albertel 14533: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   14534: ($udom and $uname are optional)
1.191     harris41 14535: 
                   14536: =item *
                   14537: 
1.243     albertel 14538: cput($namespace,$storehash,$udom,$uname) : critical put
                   14539: ($udom and $uname are optional)
1.191     harris41 14540: 
                   14541: =item *
                   14542: 
1.748     albertel 14543: newput($namespace,$storehash,$udom,$uname) :
                   14544: 
                   14545: Attempts to store the items in the $storehash, but only if they don't
                   14546: currently exist, if this succeeds you can be certain that you have 
                   14547: successfully created a new key value pair in the $namespace db.
                   14548: 
                   14549: 
                   14550: Args:
                   14551:  $namespace: name of database to store values to
                   14552:  $storehash: hashref to store to the db
                   14553:  $udom: (optional) domain of user containing the db
                   14554:  $uname: (optional) name of user caontaining the db
                   14555: 
                   14556: Returns:
                   14557:  'ok' -> succeeded in storing all keys of $storehash
                   14558:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   14559:                         least <key> already existed in the db (other
                   14560:                         requested keys may also already exist)
1.967     bisitz   14561:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 14562:  'con_lost' -> unable to contact request server
                   14563:  'refused' -> action was not allowed by remote machine
                   14564: 
                   14565: 
                   14566: =item *
                   14567: 
1.243     albertel 14568: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14569: reference filled in from namesp (encrypts the return communication)
                   14570: ($udom and $uname are optional)
1.191     harris41 14571: 
                   14572: =item *
                   14573: 
1.243     albertel 14574: log($udom,$name,$home,$message) : write to permanent log for user; use
                   14575: critical subroutine
                   14576: 
1.806     raeburn  14577: =item *
                   14578: 
1.860     raeburn  14579: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   14580: array reference filled in from namespace found in domain level on either
                   14581: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  14582: 
                   14583: =item *
                   14584: 
1.860     raeburn  14585: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   14586: domain level either on specified domain server ($uhome) or primary domain 
                   14587: server ($udom and $uhome are optional)
1.806     raeburn  14588: 
1.943     raeburn  14589: =item * 
                   14590: 
1.1172.2.35  raeburn  14591: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
                   14592: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   14593: the target domain.
                   14594: 
                   14595: May also include additional key => value pairs for the following groups:
                   14596: 
                   14597: =over
                   14598: 
                   14599: =item
                   14600: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   14601: 
                   14602: =over
                   14603: 
                   14604: =item defaultquota, authorquota
                   14605: 
                   14606: =back
                   14607: 
                   14608: =item
                   14609: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   14610: portfolio for users).
                   14611: 
                   14612: =over
                   14613: 
                   14614: =item
                   14615: aboutme, blog, webdav, portfolio
                   14616: 
                   14617: =back
                   14618: 
                   14619: =item
                   14620: requestcourses: ability to request courses, and how requests are processed.
                   14621: 
                   14622: =over
                   14623: 
                   14624: =item
1.1172.2.37  raeburn  14625: official, unofficial, community, textbook
1.1172.2.35  raeburn  14626: 
                   14627: =back
                   14628: 
                   14629: =item
                   14630: inststatus: types of institutional affiliation, and order in which they are displayed.
                   14631: 
                   14632: =over
                   14633: 
                   14634: =item
1.1172.2.44  raeburn  14635: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35  raeburn  14636: 
                   14637: =back
                   14638: 
                   14639: =item
                   14640: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   14641: for course's uploaded content.
                   14642: 
                   14643: =over
                   14644: 
                   14645: =item
1.1172.2.68  raeburn  14646: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
                   14647: communityquota, textbookquota
1.1172.2.35  raeburn  14648: 
                   14649: =back
                   14650: 
                   14651: =item
                   14652: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   14653: on your servers.
                   14654: 
                   14655: =over
                   14656: 
                   14657: =item
                   14658: remotesessions, hostedsessions
                   14659: 
                   14660: =back
                   14661: 
                   14662: =back
                   14663: 
                   14664: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   14665: utility to create a configuration.db file on a domain's primary library server
                   14666: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   14667: -- corresponding values are authentication type (internal, krb4, krb5,
                   14668: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
                   14669: will be available. Values are retrieved from cache (if current), unless the
                   14670: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   14671: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   14672: 
                   14673: Typical usage:
1.943     raeburn  14674: 
1.1172.2.35  raeburn  14675: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  14676: 
1.243     albertel 14677: =back
                   14678: 
                   14679: =head2 Network Status Functions
                   14680: 
                   14681: =over 4
1.191     harris41 14682: 
                   14683: =item *
                   14684: 
1.1137    raeburn  14685: dirlist() : return directory list based on URI (first arg).
                   14686: 
                   14687: Inputs: 1 required, 5 optional.
                   14688: 
                   14689: =over
                   14690: 
                   14691: =item 
                   14692: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   14693: 
                   14694: =item
                   14695: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   14696: 
                   14697: =item
                   14698: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   14699: 
                   14700: =item
                   14701: $getpropath - boolean: 1 if prepend path using &propath(). 
                   14702: 
                   14703: =item
                   14704: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   14705: 
                   14706: =item 
                   14707: $alternateRoot - path to prepend in place of path from $uri.
                   14708: 
                   14709: =back
                   14710: 
                   14711: Returns: Array of up to two items.
                   14712: 
                   14713: =over
                   14714: 
                   14715: a reference to an array of files/subdirectories
                   14716: 
                   14717: =over
                   14718: 
                   14719: Each element in the array of files/subdirectories is a & separated list of
                   14720: item name and the result of running stat on the item.  If dirlist was requested
                   14721: for a file instead of a directory, the item name will be ''. For a directory 
                   14722: listing, if the item is a metadata file, the element will end &N&M 
                   14723: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   14724: default copyright set (1).  
                   14725: 
                   14726: =back
                   14727: 
                   14728: a scalar containing error condition (if encountered).
                   14729: 
                   14730: =over
                   14731: 
                   14732: =item 
                   14733: no_host (no homeserver identified for $username:$domain).
                   14734: 
                   14735: =item 
                   14736: no_such_host (server contacted for listing not identified as valid host).
                   14737: 
                   14738: =item 
                   14739: con_lost (connection to remote server failed).
                   14740: 
                   14741: =item 
                   14742: refused (invalid $username:$domain received on lond side).
                   14743: 
                   14744: =item 
                   14745: no_such_dir (directory at specified path on lond side does not exist). 
                   14746: 
                   14747: =item 
                   14748: empty (directory at specified path on lond side is empty).
                   14749: 
                   14750: =over
                   14751: 
                   14752: This is currently not encountered because the &ls3, &ls2, 
                   14753: &ls (_handler) routines on the lond side do not filter out
                   14754: . and .. from a directory listing. 
                   14755: 
                   14756: =back
                   14757: 
                   14758: =back
                   14759: 
                   14760: =back
1.191     harris41 14761: 
                   14762: =item *
                   14763: 
1.243     albertel 14764: spareserver() : find server with least workload from spare.tab
                   14765: 
1.986     foxr     14766: 
                   14767: =item *
                   14768: 
                   14769: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   14770: if there is no corresponding loncapa host.
                   14771: 
1.243     albertel 14772: =back
                   14773: 
1.986     foxr     14774: 
1.243     albertel 14775: =head2 Apache Request
                   14776: 
                   14777: =over 4
1.191     harris41 14778: 
                   14779: =item *
                   14780: 
1.243     albertel 14781: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   14782: localhost, posts hash
                   14783: 
                   14784: =back
                   14785: 
                   14786: =head2 Data to String to Data
                   14787: 
                   14788: =over 4
1.191     harris41 14789: 
                   14790: =item *
                   14791: 
1.243     albertel 14792: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   14793: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 14794: 
                   14795: =item *
                   14796: 
1.243     albertel 14797: hashref2str($hashref) : convert a hashref into a string complete with
                   14798: escaping and '=' and '&' separators, supports elements that are
                   14799: arrayrefs and hashrefs
1.191     harris41 14800: 
                   14801: =item *
                   14802: 
1.243     albertel 14803: arrayref2str($arrayref) : convert an arrayref into a string complete
                   14804: with escaping and '&' separators, supports elements that are arrayrefs
                   14805: and hashrefs
1.191     harris41 14806: 
                   14807: =item *
                   14808: 
1.243     albertel 14809: str2hash($string) : convert string to hash using unescaping and
                   14810: splitting on '=' and '&', supports elements that are arrayrefs and
                   14811: hashrefs
1.191     harris41 14812: 
                   14813: =item *
                   14814: 
1.243     albertel 14815: str2array($string) : convert string to hash using unescaping and
                   14816: splitting on '&', supports elements that are arrayrefs and hashrefs
                   14817: 
                   14818: =back
                   14819: 
                   14820: =head2 Logging Routines
                   14821: 
                   14822: 
                   14823: These routines allow one to make log messages in the lonnet.log and
                   14824: lonnet.perm logfiles.
1.191     harris41 14825: 
1.1119    foxr     14826: =over 4
                   14827: 
1.191     harris41 14828: =item *
                   14829: 
1.243     albertel 14830: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 14831: 
                   14832: =item *
                   14833: 
1.243     albertel 14834: logthis() : append message to the normal lonnet.log file, it gets
                   14835: preiodically rolled over and deleted.
1.191     harris41 14836: 
                   14837: =item *
                   14838: 
1.243     albertel 14839: logperm() : append a permanent message to lonnet.perm.log, this log
                   14840: file never gets deleted by any automated portion of the system, only
                   14841: messages of critical importance should go in here.
                   14842: 
1.1119    foxr     14843: 
1.243     albertel 14844: =back
                   14845: 
                   14846: =head2 General File Helper Routines
                   14847: 
                   14848: =over 4
1.191     harris41 14849: 
                   14850: =item *
                   14851: 
1.481     raeburn  14852: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   14853: (a) files in /uploaded
                   14854:   (i) If a local copy of the file exists - 
                   14855:       compares modification date of local copy with last-modified date for 
                   14856:       definitive version stored on home server for course. If local copy is 
                   14857:       stale, requests a new version from the home server and stores it. 
                   14858:       If the original has been removed from the home server, then local copy 
                   14859:       is unlinked.
                   14860:   (ii) If local copy does not exist -
                   14861:       requests the file from the home server and stores it. 
                   14862:   
                   14863:   If $caller is 'uploadrep':  
                   14864:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   14865:     for request for files originally uploaded via DOCS. 
                   14866:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   14867:   
                   14868:   Otherwise:
                   14869:      This indicates a call from the content generation phase of the request.
                   14870:      -  returns the entire contents of the file or -1.
                   14871:      
                   14872: (b) files in /res
                   14873:    - returns the entire contents of a file or -1; 
                   14874:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 14875: 
1.712     albertel 14876: 
                   14877: =item *
                   14878: 
                   14879: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   14880:                   reference
                   14881: 
                   14882: returns either a stat() list of data about the file or an empty list
                   14883: if the file doesn't exist or couldn't find out about it (connection
                   14884: problems or user unknown)
                   14885: 
1.191     harris41 14886: =item *
                   14887: 
1.243     albertel 14888: filelocation($dir,$file) : returns file system location of a file
                   14889: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   14890: directory that relative $file lookups are to looked in ($dir of /a/dir
                   14891: and a file of ../bob will become /a/bob)
1.191     harris41 14892: 
                   14893: =item *
                   14894: 
                   14895: hreflocation($dir,$file) : returns file system location or a URL; same as
                   14896: filelocation except for hrefs
                   14897: 
                   14898: =item *
                   14899: 
1.1172.2.49  raeburn  14900: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   14901: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 14902: 
1.243     albertel 14903: =back
                   14904: 
1.608     albertel 14905: =head2 Usererfile file routines (/uploaded*)
                   14906: 
                   14907: =over 4
                   14908: 
                   14909: =item *
                   14910: 
                   14911: userfileupload(): main rotine for putting a file in a user or course's
                   14912:                   filespace, arguments are,
                   14913: 
1.620     albertel 14914:  formname - required - this is the name of the element in $env where the
1.608     albertel 14915:            filename, and the contents of the file to create/modifed exist
1.620     albertel 14916:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   14917:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  14918:  context - if coursedoc, store the file in the course of the active role
                   14919:              of the current user; 
                   14920:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   14921:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 14922:  subdir - required - subdirectory to put the file in under ../userfiles/
                   14923:          if undefined, it will be placed in "unknown"
                   14924: 
                   14925:  (This routine calls clean_filename() to remove any dangerous
                   14926:  characters from the filename, and then calls finuserfileupload() to
                   14927:  complete the transaction)
                   14928: 
                   14929:  returns either the url of the uploaded file (/uploaded/....) if successful
                   14930:  and /adm/notfound.html if unsuccessful
                   14931: 
                   14932: =item *
                   14933: 
                   14934: clean_filename(): routine for cleaing a filename up for storage in
                   14935:                  userfile space, argument is:
                   14936: 
                   14937:  filename - proposed filename
                   14938: 
                   14939: returns: the new clean filename
                   14940: 
                   14941: =item *
                   14942: 
1.1090    raeburn  14943: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 14944: userspace, probably shouldn't be called directly
                   14945: 
                   14946:   docuname: username or courseid of destination for the file
                   14947:   docudom: domain of user/course of destination for the file
                   14948:   formname: same as for userfileupload()
1.1090    raeburn  14949:   fname: filename (including subdirectories) for the file
                   14950:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   14951:   allfiles: reference to hash used to store objects found by parser
                   14952:   codebase: reference to hash used for codebases of java objects found by parser
                   14953:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   14954:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   14955:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   14956:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   14957:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   14958:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  14959:   mimetype: reference to scalar to accommodate mime type determined
                   14960:             from File::MMagic if $parser = parse.
1.608     albertel 14961: 
                   14962:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  14963:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   14964:  was 'overwrite').
                   14965:  
1.608     albertel 14966: 
                   14967: =item *
                   14968: 
                   14969: renameuserfile(): renames an existing userfile to a new name
                   14970: 
                   14971:   Args:
                   14972:    docuname: username or courseid of destination for the file
                   14973:    docudom: domain of user/course of destination for the file
                   14974:    old: current file name (including any subdirs under userfiles)
                   14975:    new: desired file name (including any subdirs under userfiles)
                   14976: 
                   14977: =item *
                   14978: 
                   14979: mkdiruserfile(): creates a directory is a userfiles dir
                   14980: 
                   14981:   Args:
                   14982:    docuname: username or courseid of destination for the file
                   14983:    docudom: domain of user/course of destination for the file
                   14984:    dir: dir to create (including any subdirs under userfiles)
                   14985: 
                   14986: =item *
                   14987: 
                   14988: removeuserfile(): removes a file that exists in userfiles
                   14989: 
                   14990:   Args:
                   14991:    docuname: username or courseid of destination for the file
                   14992:    docudom: domain of user/course of destination for the file
                   14993:    fname: filname to delete (including any subdirs under userfiles)
                   14994: 
                   14995: =item *
                   14996: 
                   14997: removeuploadedurl(): convience function for removeuserfile()
                   14998: 
                   14999:   Args:
                   15000:    url:  a full /uploaded/... url to delete
                   15001: 
1.747     albertel 15002: =item * 
                   15003: 
                   15004: get_portfile_permissions():
                   15005:   Args:
                   15006:     domain: domain of user or course contain the portfolio files
                   15007:     user: name of user or num of course contain the portfolio files
                   15008:   Returns:
                   15009:     hashref of a dump of the proper file_permissions.db
                   15010:    
                   15011: 
                   15012: =item * 
                   15013: 
                   15014: get_access_controls():
                   15015: 
                   15016: Args:
                   15017:   current_permissions: the hash ref returned from get_portfile_permissions()
                   15018:   group: (optional) the group you want the files associated with
                   15019:   file: (optional) the file you want access info on
                   15020: 
                   15021: Returns:
1.749     raeburn  15022:     a hash (keys are file names) of hashes containing
                   15023:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   15024:         values are XML containing access control settings (see below) 
1.747     albertel 15025: 
                   15026: Internal notes:
                   15027: 
1.749     raeburn  15028:  access controls are stored in file_permissions.db as key=value pairs.
                   15029:     key -> path to file/file_name\0uniqueID:scope_end_start
                   15030:         where scope -> public,guest,course,group,domains or users.
                   15031:               end -> UNIX time for end of access (0 -> no end date)
                   15032:               start -> UNIX time for start of access
                   15033: 
                   15034:     value -> XML description of access control
                   15035:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   15036:             <start></start>
                   15037:             <end></end>
                   15038: 
                   15039:             <password></password>  for scope type = guest
                   15040: 
                   15041:             <domain></domain>     for scope type = course or group
                   15042:             <number></number>
                   15043:             <roles id="">
                   15044:              <role></role>
                   15045:              <access></access>
                   15046:              <section></section>
                   15047:              <group></group>
                   15048:             </roles>
                   15049: 
                   15050:             <dom></dom>         for scope type = domains
                   15051: 
                   15052:             <users>             for scope type = users
                   15053:              <user>
                   15054:               <uname></uname>
                   15055:               <udom></udom>
                   15056:              </user>
                   15057:             </users>
                   15058:            </scope> 
                   15059:               
                   15060:  Access data is also aggregated for each file in an additional key=value pair:
                   15061:  key -> path to file/file_name\0accesscontrol 
                   15062:  value -> reference to hash
                   15063:           hash contains key = value pairs
                   15064:           where key = uniqueID:scope_end_start
                   15065:                 value = UNIX time record was last updated
                   15066: 
                   15067:           Used to improve speed of look-ups of access controls for each file.  
                   15068:  
                   15069:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   15070: 
1.1172.2.13  raeburn  15071: =item *
                   15072: 
1.749     raeburn  15073: modify_access_controls():
                   15074: 
                   15075: Modifies access controls for a portfolio file
                   15076: Args
                   15077: 1. file name
                   15078: 2. reference to hash of required changes,
                   15079: 3. domain
                   15080: 4. username
                   15081:   where domain,username are the domain of the portfolio owner 
                   15082:   (either a user or a course) 
                   15083: 
                   15084: Returns:
                   15085: 1. result of additions or updates ('ok' or 'error', with error message). 
                   15086: 2. result of deletions ('ok' or 'error', with error message).
                   15087: 3. reference to hash of any new or updated access controls.
                   15088: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   15089:    key = integer (inbound ID)
1.1172.2.13  raeburn  15090:    value = uniqueID
                   15091: 
                   15092: =item *
                   15093: 
                   15094: get_timebased_id():
                   15095: 
                   15096: Attempts to get a unique timestamp-based suffix for use with items added to a
                   15097: course via the Course Editor (e.g., folders, composite pages,
                   15098: group bulletin boards).
                   15099: 
                   15100: Args: (first three required; six others optional)
                   15101: 
                   15102: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   15103:    docssequence, or name of group
                   15104: 
                   15105: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   15106:    e.g., num, boardids
                   15107: 
                   15108: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   15109:    file will be named nohist_namespace.db
                   15110: 
                   15111: 4. cdom: domain of course; default is current course domain from %env
                   15112: 
                   15113: 5. cnum: course number; default is current course number from %env
                   15114: 
                   15115: 6. idtype: set to concat if an additional digit is to be appended to the
                   15116:    unix timestamp to form the suffix, if the plain timestamp is already
                   15117:    in use.  Default is to not do this, but simply increment the unix
                   15118:    timestamp by 1 until a unique key is obtained.
                   15119: 
                   15120: 7. who: holder of locking key; defaults to user:domain for user.
                   15121: 
                   15122: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   15123:    retrying); default is 3.
                   15124: 
                   15125: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   15126: 
                   15127: Returns:
                   15128: 
                   15129: 1. suffix obtained (numeric)
                   15130: 
                   15131: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   15132: 
                   15133: 3. error: contains (localized) error message if an error occurred.
                   15134: 
1.747     albertel 15135: 
1.608     albertel 15136: =back
                   15137: 
1.243     albertel 15138: =head2 HTTP Helper Routines
                   15139: 
                   15140: =over 4
                   15141: 
1.191     harris41 15142: =item *
                   15143: 
                   15144: escape() : unpack non-word characters into CGI-compatible hex codes
                   15145: 
                   15146: =item *
                   15147: 
                   15148: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   15149: 
1.243     albertel 15150: =back
                   15151: 
                   15152: =head1 PRIVATE SUBROUTINES
                   15153: 
                   15154: =head2 Underlying communication routines (Shouldn't call)
                   15155: 
                   15156: =over 4
                   15157: 
                   15158: =item *
                   15159: 
                   15160: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   15161: 
                   15162: =item *
                   15163: 
                   15164: reply() : uses subreply to send a message to remote machine, logs all failures
                   15165: 
                   15166: =item *
                   15167: 
                   15168: critical() : passes a critical message to another server; if cannot
                   15169: get through then place message in connection buffer directory and
                   15170: returns con_delayed, if incapable of saving message, returns
                   15171: con_failed
                   15172: 
                   15173: =item *
                   15174: 
                   15175: reconlonc() : tries to reconnect lonc client processes.
                   15176: 
                   15177: =back
                   15178: 
                   15179: =head2 Resource Access Logging
                   15180: 
                   15181: =over 4
                   15182: 
                   15183: =item *
                   15184: 
                   15185: flushcourselogs() : flush (save) buffer logs and access logs
                   15186: 
                   15187: =item *
                   15188: 
                   15189: courselog($what) : save message for course in hash
                   15190: 
                   15191: =item *
                   15192: 
                   15193: courseacclog($what) : save message for course using &courselog().  Perform
                   15194: special processing for specific resource types (problems, exams, quizzes, etc).
                   15195: 
1.191     harris41 15196: =item *
                   15197: 
                   15198: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   15199: as a PerlChildExitHandler
1.243     albertel 15200: 
                   15201: =back
                   15202: 
                   15203: =head2 Other
                   15204: 
                   15205: =over 4
                   15206: 
                   15207: =item *
                   15208: 
                   15209: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 15210: 
                   15211: =back
                   15212: 
                   15213: =cut
1.877     foxr     15214: 

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