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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.115! raeburn     4: # $Id: lonnet.pm,v 1.1172.2.114 2019/08/25 22:45:58 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
1.1172.2.114  raeburn    81:             %managerstab $passwdmin);
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.1172.2.110  raeburn   102: use LONCAPA::transliterate;
1.1117    foxr      103: 
1.1090    raeburn   104: use File::Copy;
1.676     albertel  105: 
1.195     www       106: my $readit;
1.1172.2.79  raeburn   107: my $max_connection_retries = 20;     # Or some such value.
1.1       albertel  108: 
1.619     albertel  109: require Exporter;
                    110: 
                    111: our @ISA = qw (Exporter);
                    112: our @EXPORT = qw(%env);
                    113: 
1.1172.2.9  raeburn   114: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729     www       115: {
                    116:     my $logid;
1.1172.2.9  raeburn   117:     sub write_log {
                    118: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    119:         if ($context eq 'course') {
                    120:             if (($cnum eq '') || ($cdom eq '')) {
                    121:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    122:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    123:             }
1.957     raeburn   124:         }
1.1172.2.13  raeburn   125: 	$logid ++;
1.957     raeburn   126:         my $now = time();
                    127: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.1172.2.9  raeburn   128:         my $logentry = {
                    129:                          $id => {
                    130:                                   'exe_uname' => $env{'user.name'},
                    131:                                   'exe_udom'  => $env{'user.domain'},
                    132:                                   'exe_time'  => $now,
                    133:                                   'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    134:                                   'delflag'   => $delflag,
                    135:                                   'logentry'  => $storehash,
                    136:                                   'uname'     => $uname,
                    137:                                   'udom'      => $udom,
                    138:                                 }
                    139:                        };
                    140:         return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729     www       141:     }
                    142: }
1.1       albertel  143: 
1.163     harris41  144: sub logtouch {
                    145:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  146:     unless (-e "$execdir/logs/lonnet.log") {	
1.1172.2.96  raeburn   147: 	open(my $fh,">>","$execdir/logs/lonnet.log");
1.163     harris41  148: 	close $fh;
                    149:     }
                    150:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    151:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    152: }
                    153: 
1.1       albertel  154: sub logthis {
                    155:     my $message=shift;
                    156:     my $execdir=$perlvar{'lonDaemons'};
                    157:     my $now=time;
                    158:     my $local=localtime($now);
1.1172.2.96  raeburn   159:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
1.986     foxr      160: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    161: 	print $fh $logstring;
1.448     albertel  162: 	close($fh);
                    163:     }
1.1       albertel  164:     return 1;
                    165: }
                    166: 
                    167: sub logperm {
                    168:     my $message=shift;
                    169:     my $execdir=$perlvar{'lonDaemons'};
                    170:     my $now=time;
                    171:     my $local=localtime($now);
1.1172.2.96  raeburn   172:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
1.448     albertel  173: 	print $fh "$now:$message:$local\n";
                    174: 	close($fh);
                    175:     }
1.1       albertel  176:     return 1;
                    177: }
                    178: 
1.850     albertel  179: sub create_connection {
1.853     albertel  180:     my ($hostname,$lonid) = @_;
1.851     albertel  181:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  182: 				     Type    => SOCK_STREAM,
                    183: 				     Timeout => 10);
                    184:     return 0 if (!$client);
1.890     albertel  185:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  186:     my $result = <$client>;
                    187:     chomp($result);
                    188:     return 1 if ($result eq 'done');
                    189:     return 0;
                    190: }
                    191: 
1.983     raeburn   192: sub get_server_timezone {
                    193:     my ($cnum,$cdom) = @_;
                    194:     my $home=&homeserver($cnum,$cdom);
                    195:     if ($home ne 'no_host') {
                    196:         my $cachetime = 24*3600;
                    197:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    198:         if (defined($cached)) {
                    199:             return $timezone;
                    200:         } else {
                    201:             my $timezone = &reply('servertimezone',$home);
                    202:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    203:         }
                    204:     }
                    205: }
1.850     albertel  206: 
1.1106    raeburn   207: sub get_server_distarch {
                    208:     my ($lonhost,$ignore_cache) = @_;
                    209:     if (defined($lonhost)) {
                    210:         if (!defined(&hostname($lonhost))) {
                    211:             return;
                    212:         }
                    213:         my $cachetime = 12*3600;
                    214:         if (!$ignore_cache) {
                    215:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    216:             if (defined($cached)) {
                    217:                 return $distarch;
                    218:             }
                    219:         }
                    220:         my $rep = &reply('serverdistarch',$lonhost);
                    221:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    222:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    223:                 $rep eq '') {
                    224:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    225:         }
                    226:     }
                    227:     return;
                    228: }
                    229: 
1.993     raeburn   230: sub get_server_loncaparev {
1.1073    raeburn   231:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   232:     if (defined($lonhost)) {
                    233:         if (!defined(&hostname($lonhost))) {
                    234:             undef($lonhost);
                    235:         }
                    236:     }
                    237:     if (!defined($lonhost)) {
                    238:         if (defined(&domain($dom,'primary'))) {
                    239:             $lonhost=&domain($dom,'primary');
                    240:             if ($lonhost eq 'no_host') {
                    241:                 undef($lonhost);
                    242:             }
                    243:         }
                    244:     }
                    245:     if (defined($lonhost)) {
1.1073    raeburn   246:         my $cachetime = 12*3600;
                    247:         if (!$ignore_cache) {
                    248:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    249:             if (defined($cached)) {
                    250:                 return $loncaparev;
                    251:             }
                    252:         }
                    253:         my ($answer,$loncaparev);
                    254:         my @ids=&current_machine_ids();
                    255:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    256:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   257:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   258:                 $loncaparev = $1;
                    259:             }
                    260:         } else {
                    261:             $answer = &reply('serverloncaparev',$lonhost);
                    262:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    263:                 if ($caller eq 'loncron') {
                    264:                     my $ua=new LWP::UserAgent;
1.1082    raeburn   265:                     $ua->timeout(4);
1.1073    raeburn   266:                     my $protocol = $protocol{$lonhost};
                    267:                     $protocol = 'http' if ($protocol ne 'https');
                    268:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
                    269:                     my $request=new HTTP::Request('GET',$url);
                    270:                     my $response=$ua->request($request);
                    271:                     unless ($response->is_error()) {
                    272:                         my $content = $response->content;
1.1081    raeburn   273:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   274:                             $loncaparev = $1;
                    275:                         }
                    276:                     }
                    277:                 } else {
                    278:                     $loncaparev = $loncaparevs{$lonhost};
                    279:                 }
1.1081    raeburn   280:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   281:                 $loncaparev = $1;
                    282:             }
1.993     raeburn   283:         }
1.1073    raeburn   284:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   285:     }
                    286: }
                    287: 
1.1074    raeburn   288: sub get_server_homeID {
                    289:     my ($hostname,$ignore_cache,$caller) = @_;
                    290:     unless ($ignore_cache) {
                    291:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    292:         if (defined($cached)) {
                    293:             return $serverhomeID;
                    294:         }
                    295:     }
                    296:     my $cachetime = 12*3600;
                    297:     my $serverhomeID;
                    298:     if ($caller eq 'loncron') { 
                    299:         my @machine_ids = &machine_ids($hostname);
                    300:         foreach my $id (@machine_ids) {
                    301:             my $response = &reply('serverhomeID',$id);
                    302:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    303:                 $serverhomeID = $response;
                    304:                 last;
                    305:             }
                    306:         }
                    307:         if ($serverhomeID eq '') {
                    308:             $serverhomeID = $machine_ids[-1];
                    309:         }
                    310:     } else {
                    311:         $serverhomeID = $serverhomeIDs{$hostname};
                    312:     }
                    313:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    314: }
                    315: 
1.1121    raeburn   316: sub get_remote_globals {
                    317:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   318:     my ($result,%returnhash,%whatneeded);
                    319:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   320:         foreach my $what (sort(keys(%{$whathash}))) {
                    321:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   322:             my ($response,$cached);
1.1121    raeburn   323:             unless ($ignore_cache) {
1.1125    raeburn   324:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   325:             }
                    326:             if (defined($cached)) {
1.1125    raeburn   327:                 $returnhash{$what} = $response;
1.1121    raeburn   328:             } else {
1.1125    raeburn   329:                 $whatneeded{$what} = 1;
1.1121    raeburn   330:             }
                    331:         }
1.1125    raeburn   332:         if (keys(%whatneeded) == 0) {
                    333:             $result = 'ok';
                    334:         } else {
1.1121    raeburn   335:             my $requested = &freeze_escape(\%whatneeded);
                    336:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   337:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    338:                 ($rep eq 'unknown_cmd')) {
                    339:                 $result = $rep;
                    340:             } else {
                    341:                 $result = 'ok';
1.1121    raeburn   342:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   343:                 foreach my $item (@pairs) {
                    344:                     my ($key,$value)=split(/=/,$item,2);
                    345:                     my $what = &unescape($key);
                    346:                     my $hashid = $lonhost.'-'.$what;
                    347:                     $returnhash{$what}=&thaw_unescape($value);
                    348:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   349:                 }
                    350:             }
                    351:         }
                    352:     }
1.1125    raeburn   353:     return ($result,\%returnhash);
1.1121    raeburn   354: }
                    355: 
1.1124    raeburn   356: sub remote_devalidate_cache {
1.1172.2.35  raeburn   357:     my ($lonhost,$cachekeys) = @_;
                    358:     my $items;
                    359:     return unless (ref($cachekeys) eq 'ARRAY');
                    360:     my $cachestr = join('&',@{$cachekeys});
                    361:     return &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124    raeburn   362: }
                    363: 
1.1       albertel  364: # -------------------------------------------------- Non-critical communication
                    365: sub subreply {
                    366:     my ($cmd,$server)=@_;
1.838     albertel  367:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      368:     #
                    369:     #  With loncnew process trimming, there's a timing hole between lonc server
                    370:     #  process exit and the master server picking up the listen on the AF_UNIX
                    371:     #  socket.  In that time interval, a lock file will exist:
                    372: 
                    373:     my $lockfile=$peerfile.".lock";
                    374:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
1.1172.2.79  raeburn   375: 	sleep(0.1);
1.549     foxr      376:     }
                    377:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      378:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      379:     #
1.550     foxr      380:     #   We'll give the connection a few tries before abandoning it.  If
                    381:     #   connection is not possible, we'll con_lost back to the client.
                    382:     #   
                    383:     my $client;
                    384:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    385: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    386: 				      Type    => SOCK_STREAM,
                    387: 				      Timeout => 10);
1.869     albertel  388: 	if ($client) {
1.550     foxr      389: 	    last;		# Connected!
1.850     albertel  390: 	} else {
1.853     albertel  391: 	    &create_connection(&hostname($server),$server);
1.550     foxr      392: 	}
1.1172.2.79  raeburn   393:         sleep(0.1);		# Try again later if failed connection.
1.550     foxr      394:     }
                    395:     my $answer;
                    396:     if ($client) {
1.704     albertel  397: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      398: 	$answer=<$client>;
                    399: 	if (!$answer) { $answer="con_lost"; }
                    400: 	chomp($answer);
                    401:     } else {
                    402: 	$answer = 'con_lost';	# Failed connection.
                    403:     }
1.1       albertel  404:     return $answer;
                    405: }
                    406: 
                    407: sub reply {
                    408:     my ($cmd,$server)=@_;
1.838     albertel  409:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  410:     my $answer=subreply($cmd,$server);
1.65      www       411:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.1172.2.111  raeburn   412:         my $logged = $cmd;
                    413:         if ($cmd =~ /^encrypt:([^:]+):/) {
                    414:             my $subcmd = $1;
                    415:             if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
                    416:                 ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
                    417:                 ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades')) {
                    418:                 (undef,undef,my @rest) = split(/:/,$cmd);
                    419:                 if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
                    420:                     splice(@rest,2,1,'Hidden');
                    421:                 } elsif ($subcmd eq 'passwd') {
                    422:                     splice(@rest,2,2,('Hidden','Hidden'));
                    423:                 } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
                    424:                          ($subcmd eq 'autoexportgrades')) {
                    425:                     splice(@rest,3,1,'Hidden');
                    426:                 }
                    427:                 $logged = join(':',('encrypt:'.$subcmd,@rest));
                    428:             }
                    429:         }
                    430:         &logthis("<font color=\"blue\">WARNING:".
                    431:                  " $logged to $server returned $answer</font>");
1.12      www       432:     }
1.1       albertel  433:     return $answer;
                    434: }
                    435: 
                    436: # ----------------------------------------------------------- Send USR1 to lonc
                    437: 
                    438: sub reconlonc {
1.891     albertel  439:     my ($lonid) = @_;
                    440:     if ($lonid) {
1.1172.2.72  raeburn   441:         my $hostname = &hostname($lonid);
1.891     albertel  442: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    443: 	if ($hostname && -e $peerfile) {
                    444: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    445: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    446: 					     Type    => SOCK_STREAM,
                    447: 					     Timeout => 10);
                    448: 	    if ($client) {
                    449: 		print $client ("reset_retries\n");
                    450: 		my $answer=<$client>;
                    451: 		#reset just this one.
                    452: 	    }
                    453: 	}
                    454: 	return;
                    455:     }
                    456: 
1.836     www       457:     &logthis("Trying to reconnect lonc");
1.1       albertel  458:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.1172.2.96  raeburn   459:     if (open(my $fh,"<",$loncfile)) {
1.1       albertel  460: 	my $loncpid=<$fh>;
                    461:         chomp($loncpid);
                    462:         if (kill 0 => $loncpid) {
                    463: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    464:             kill USR1 => $loncpid;
                    465:             sleep 1;
1.836     www       466:          } else {
1.12      www       467: 	    &logthis(
1.672     albertel  468:                "<font color=\"blue\">WARNING:".
1.12      www       469:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  470:         }
                    471:     } else {
1.836     www       472: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  473:     }
                    474: }
                    475: 
                    476: # ------------------------------------------------------ Critical communication
1.12      www       477: 
1.1       albertel  478: sub critical {
                    479:     my ($cmd,$server)=@_;
1.838     albertel  480:     unless (&hostname($server)) {
1.672     albertel  481:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       482:                " Critical message to unknown server ($server)</font>");
                    483:         return 'no_such_host';
                    484:     }
1.1       albertel  485:     my $answer=reply($cmd,$server);
                    486:     if ($answer eq 'con_lost') {
1.1172.2.72  raeburn   487: 	&reconlonc($server);
1.589     albertel  488: 	my $answer=reply($cmd,$server);
1.1       albertel  489:         if ($answer eq 'con_lost') {
                    490:             my $now=time;
                    491:             my $middlename=$cmd;
1.5       www       492:             $middlename=substr($middlename,0,16);
1.1       albertel  493:             $middlename=~s/\W//g;
                    494:             my $dfilename=
1.305     www       495:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    496:             $dumpcount++;
1.1       albertel  497:             {
1.448     albertel  498: 		my $dfh;
1.1172.2.96  raeburn   499: 		if (open($dfh,">",$dfilename)) {
1.448     albertel  500: 		    print $dfh "$cmd\n"; 
                    501: 		    close($dfh);
                    502: 		}
1.1       albertel  503:             }
1.1172.2.79  raeburn   504:             sleep 1;
1.1       albertel  505:             my $wcmd='';
                    506:             {
1.448     albertel  507: 		my $dfh;
1.1172.2.96  raeburn   508: 		if (open($dfh,"<",$dfilename)) {
1.448     albertel  509: 		    $wcmd=<$dfh>; 
                    510: 		    close($dfh);
                    511: 		}
1.1       albertel  512:             }
                    513:             chomp($wcmd);
1.7       www       514:             if ($wcmd eq $cmd) {
1.672     albertel  515: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       516:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  517:                 &logperm("D:$server:$cmd");
                    518: 	        return 'con_delayed';
                    519:             } else {
1.672     albertel  520:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       521:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  522:                 &logperm("F:$server:$cmd");
                    523:                 return 'con_failed';
                    524:             }
                    525:         }
                    526:     }
                    527:     return $answer;
1.405     albertel  528: }
                    529: 
1.755     albertel  530: # ------------------------------------------- check if return value is an error
                    531: 
                    532: sub error {
                    533:     my ($result) = @_;
1.756     albertel  534:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  535: 	if ($2 == 2) { return undef; }
                    536: 	return $1;
                    537:     }
                    538:     return undef;
                    539: }
                    540: 
1.783     albertel  541: sub convert_and_load_session_env {
                    542:     my ($lonidsdir,$handle)=@_;
                    543:     my @profile;
                    544:     {
1.917     albertel  545: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    546: 	if (!$opened) {
1.915     albertel  547: 	    return 0;
                    548: 	}
1.783     albertel  549: 	flock($idf,LOCK_SH);
                    550: 	@profile=<$idf>;
                    551: 	close($idf);
                    552:     }
                    553:     my %temp_env;
                    554:     foreach my $line (@profile) {
1.786     albertel  555: 	if ($line !~ m/=/) {
                    556: 	    return 0;
                    557: 	}
1.783     albertel  558: 	chomp($line);
                    559: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    560: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    561:     }
                    562:     unlink("$lonidsdir/$handle.id");
                    563:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    564: 	    0640)) {
                    565: 	%disk_env = %temp_env;
                    566: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    567: 	untie(%disk_env);
                    568:     }
1.786     albertel  569:     return 1;
1.783     albertel  570: }
                    571: 
1.374     www       572: # ------------------------------------------- Transfer profile into environment
1.780     albertel  573: my $env_loaded;
                    574: sub transfer_profile_to_env {
1.788     albertel  575:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    576:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       577: 
1.720     albertel  578:     if (!defined($lonidsdir)) {
                    579: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    580:     }
                    581:     if (!defined($handle)) {
                    582:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    583:     }
                    584: 
1.786     albertel  585:     my $convert;
                    586:     {
1.917     albertel  587:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    588: 	if (!$opened) {
1.915     albertel  589: 	    return;
                    590: 	}
1.786     albertel  591: 	flock($idf,LOCK_SH);
                    592: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    593: 		&GDBM_READER(),0640)) {
                    594: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    595: 	    untie(%disk_env);
                    596: 	} else {
                    597: 	    $convert = 1;
                    598: 	}
                    599:     }
                    600:     if ($convert) {
                    601: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    602: 	    &logthis("Failed to load session, or convert session.");
                    603: 	}
1.374     www       604:     }
1.783     albertel  605: 
1.786     albertel  606:     my %remove;
1.783     albertel  607:     while ( my $envname = each(%env) ) {
1.433     matthew   608:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    609:             if ($time < time-300) {
1.783     albertel  610:                 $remove{$key}++;
1.433     matthew   611:             }
                    612:         }
                    613:     }
1.783     albertel  614: 
1.619     albertel  615:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  616:     $env_loaded=1;
1.783     albertel  617:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   618:         &delenv($expired_key);
1.374     www       619:     }
1.1       albertel  620: }
                    621: 
1.916     albertel  622: # ---------------------------------------------------- Check for valid session 
                    623: sub check_for_valid_session {
1.1172.2.96  raeburn   624:     my ($r,$name,$userhashref,$domref) = @_;
1.916     albertel  625:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1172.2.108  raeburn   626:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
1.1155    raeburn   627:     if ($name eq 'lonDAV') {
                    628:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    629:     } else {
                    630:         $lonidsdir=$r->dir_config('lonIDsDir');
1.1172.2.108  raeburn   631:         if ($name eq '') {
                    632:             $name = 'lonID';
                    633:         }
                    634:     }
                    635:     if ($name eq 'lonID') {
                    636:         $secure = 'lonSID';
                    637:         $linkname = 'lonLinkID';
                    638:         $pubname = 'lonPubID';
                    639:         if (exists($cookies{$secure})) {
                    640:             $lonid=$cookies{$secure};
                    641:         } elsif (exists($cookies{$name})) {
                    642:             $lonid=$cookies{$name};
                    643:         } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
                    644:             $lonid=$cookies{$linkname};
                    645:         } elsif (exists($cookies{$pubname})) {
                    646:             $lonid=$cookies{$pubname};
                    647:         }
                    648:     } else {
                    649:         $lonid=$cookies{$name};
                    650:     }
                    651:     return undef if (!$lonid);
                    652: 
                    653:     my $handle=&LONCAPA::clean_handle($lonid->value);
                    654:     if (-l "$lonidsdir/$handle.id") {
                    655:         my $link = readlink("$lonidsdir/$handle.id");
                    656:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    657:             $handle = $1;
                    658:         }
1.1155    raeburn   659:     }
1.1172.2.96  raeburn   660:     if (!-e "$lonidsdir/$handle.id") {
                    661:         if ((ref($domref)) && ($name eq 'lonID') &&
                    662:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    663:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    664:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    665:                 $$domref = $possudom;
                    666:             }
                    667:         }
                    668:         return undef;
                    669:     }
1.916     albertel  670: 
1.917     albertel  671:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    672:     return undef if (!$opened);
1.916     albertel  673: 
                    674:     flock($idf,LOCK_SH);
                    675:     my %disk_env;
                    676:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    677: 	    &GDBM_READER(),0640)) {
                    678: 	return undef;	
                    679:     }
                    680: 
                    681:     if (!defined($disk_env{'user.name'})
                    682: 	|| !defined($disk_env{'user.domain'})) {
1.1172.2.107  raeburn   683:         untie(%disk_env);
1.916     albertel  684: 	return undef;
                    685:     }
1.1172.2.18  raeburn   686: 
1.1172.2.36  raeburn   687:     if (ref($userhashref) eq 'HASH') {
                    688:         $userhashref->{'name'} = $disk_env{'user.name'};
                    689:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1172.2.18  raeburn   690:     }
1.1172.2.107  raeburn   691:     untie(%disk_env);
1.1172.2.18  raeburn   692: 
1.916     albertel  693:     return $handle;
                    694: }
                    695: 
1.830     albertel  696: sub timed_flock {
                    697:     my ($file,$lock_type) = @_;
                    698:     my $failed=0;
                    699:     eval {
                    700: 	local $SIG{__DIE__}='DEFAULT';
                    701: 	local $SIG{ALRM}=sub {
                    702: 	    $failed=1;
                    703: 	    die("failed lock");
                    704: 	};
                    705: 	alarm(13);
                    706: 	flock($file,$lock_type);
                    707: 	alarm(0);
                    708:     };
                    709:     if ($failed) {
                    710: 	return undef;
                    711:     } else {
                    712: 	return 1;
                    713:     }
                    714: }
                    715: 
1.1172.2.107  raeburn   716: sub get_sessionfile_vars {
                    717:     my ($handle,$lonidsdir,$storearr) = @_;
                    718:     my %returnhash;
                    719:     unless (ref($storearr) eq 'ARRAY') {
                    720:         return %returnhash;
                    721:     }
                    722:     if (-l "$lonidsdir/$handle.id") {
                    723:         my $link = readlink("$lonidsdir/$handle.id");
                    724:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    725:             $handle = $1;
                    726:         }
                    727:     }
                    728:     if ((-e "$lonidsdir/$handle.id") &&
                    729:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    730:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    731:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    732:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
                    733:                 flock($idf,LOCK_SH);
                    734:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    735:                         &GDBM_READER(),0640)) {
                    736:                     foreach my $item (@{$storearr}) {
                    737:                         $returnhash{$item} = $disk_env{$item};
                    738:                     }
                    739:                     untie(%disk_env);
                    740:                 }
                    741:             }
                    742:         }
                    743:     }
                    744:     return %returnhash;
                    745: }
                    746: 
1.5       www       747: # ---------------------------------------------------------- Append Environment
                    748: 
                    749: sub appenv {
1.949     raeburn   750:     my ($newenv,$roles) = @_;
                    751:     if (ref($newenv) eq 'HASH') {
                    752:         foreach my $key (keys(%{$newenv})) {
                    753:             my $refused = 0;
                    754: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    755:                 $refused = 1;
                    756:                 if (ref($roles) eq 'ARRAY') {
1.1172.2.40  raeburn   757:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   758:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    759:                         $refused = 0;
                    760:                     }
                    761:                 }
                    762:             }
                    763:             if ($refused) {
                    764:                 &logthis("<font color=\"blue\">WARNING: ".
                    765:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    766:                          .'</font>');
                    767: 	        delete($newenv->{$key});
                    768:             } else {
                    769:                 $env{$key}=$newenv->{$key};
                    770:             }
                    771:         }
1.1172.2.96  raeburn   772:         my $lonids = $perlvar{'lonIDsDir'};
                    773:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
                    774:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    775:             if ($opened
                    776: 	        && &timed_flock($env_file,LOCK_EX)
                    777: 	        &&
                    778: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    779: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    780: 	        while (my ($key,$value) = each(%{$newenv})) {
                    781: 	            $disk_env{$key} = $value;
                    782: 	        }
                    783: 	        untie(%disk_env);
                    784:             }
1.35      www       785:         }
1.191     harris41  786:     }
1.56      www       787:     return 'ok';
                    788: }
                    789: # ----------------------------------------------------- Delete from Environment
                    790: 
                    791: sub delenv {
1.1104    raeburn   792:     my ($delthis,$regexp,$roles) = @_;
                    793:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    794:         my $refused = 1;
                    795:         if (ref($roles) eq 'ARRAY') {
                    796:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    797:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    798:                 $refused = 0;
                    799:             }
                    800:         }
                    801:         if ($refused) {
                    802:             &logthis("<font color=\"blue\">WARNING: ".
                    803:                      "Attempt to delete from environment ".$delthis);
                    804:             return 'error';
                    805:         }
1.56      www       806:     }
1.917     albertel  807:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    808:     if ($opened
1.915     albertel  809: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  810: 	&&
                    811: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    812: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  813: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   814: 	    if ($regexp) {
                    815:                 if ($key=~/^$delthis/) {
                    816:                     delete($env{$key});
                    817:                     delete($disk_env{$key});
                    818:                 } 
                    819:             } else {
                    820:                 if ($key=~/^\Q$delthis\E/) {
                    821: 		    delete($env{$key});
                    822: 		    delete($disk_env{$key});
                    823: 	        }
                    824:             }
1.448     albertel  825: 	}
1.783     albertel  826: 	untie(%disk_env);
1.5       www       827:     }
                    828:     return 'ok';
1.369     albertel  829: }
                    830: 
1.790     albertel  831: sub get_env_multiple {
                    832:     my ($name) = @_;
                    833:     my @values;
                    834:     if (defined($env{$name})) {
                    835:         # exists is it an array
                    836:         if (ref($env{$name})) {
                    837:             @values=@{ $env{$name} };
                    838:         } else {
                    839:             $values[0]=$env{$name};
                    840:         }
                    841:     }
                    842:     return(@values);
                    843: }
                    844: 
1.958     www       845: # ------------------------------------------------------------------- Locking
                    846: 
                    847: sub set_lock {
                    848:     my ($text)=@_;
                    849:     $locknum++;
                    850:     my $id=$$.'-'.$locknum;
                    851:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    852:              'session.lock.'.$id => $text});
                    853:     return $id;
                    854: }
                    855: 
                    856: sub get_locks {
                    857:     my $num=0;
                    858:     my %texts=();
                    859:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    860:        if ($lock=~/\w/) {
                    861:           $num++;
                    862:           $texts{$lock}=$env{'session.lock.'.$lock};
                    863:        }
                    864:    }
                    865:    return ($num,%texts);
                    866: }
                    867: 
                    868: sub remove_lock {
                    869:     my ($id)=@_;
                    870:     my $newlocks='';
                    871:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    872:        if (($lock=~/\w/) && ($lock ne $id)) {
                    873:           $newlocks.=','.$lock;
                    874:        }
                    875:     }
                    876:     &appenv({'session.locks' => $newlocks});
                    877:     &delenv('session.lock.'.$id);
                    878: }
                    879: 
                    880: sub remove_all_locks {
                    881:     my $activelocks=$env{'session.locks'};
                    882:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    883:        if ($lock=~/\w/) {
                    884:           &remove_lock($lock);
                    885:        }
                    886:     }
                    887: }
                    888: 
                    889: 
1.369     albertel  890: # ------------------------------------------ Find out current server userload
                    891: sub userload {
                    892:     my $numusers=0;
                    893:     {
                    894: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    895: 	my $filename;
                    896: 	my $curtime=time;
                    897: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  898: 	    next if ($filename eq '.' || $filename eq '..');
                    899: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.1172.2.112  raeburn   900:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
1.404     albertel  901: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  902: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  903: 	}
                    904: 	closedir(LONIDS);
                    905:     }
                    906:     my $userloadpercent=0;
                    907:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    908:     if ($maxuserload) {
1.371     albertel  909: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  910:     }
1.372     albertel  911:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  912:     return $userloadpercent;
1.283     www       913: }
                    914: 
1.1       albertel  915: # ------------------------------ Find server with least workload from spare.tab
1.11      www       916: 
1.1       albertel  917: sub spareserver {
1.1083    raeburn   918:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  919:     my $spare_server;
1.370     albertel  920:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  921:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    922:                                                      :  $userloadpercent;
1.1083    raeburn   923:     my ($uint_dom,$remotesessions);
                    924:     if (($udom ne '') && (&domain($udom) ne '')) {
                    925:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    926:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    927:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    928:         $remotesessions = $udomdefaults{'remotesessions'};
                    929:     }
1.1123    raeburn   930:     my $spareshash = &this_host_spares($udom);
                    931:     if (ref($spareshash) eq 'HASH') {
                    932:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    933:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1172.2.62  raeburn   934:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    935:                                              $try_server));
1.1123    raeburn   936: 	        ($spare_server, $lowest_load) =
                    937: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    938:             }
1.1083    raeburn   939:         }
1.784     albertel  940: 
1.1123    raeburn   941:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    942: 
                    943:         if (!$found_server) {
                    944:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    945: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1172.2.62  raeburn   946:                     next unless (&spare_can_host($udom,$uint_dom,
                    947:                                                  $remotesessions,$try_server));
1.1123    raeburn   948: 	            ($spare_server, $lowest_load) =
                    949: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    950:                 }
                    951: 	    }
                    952:         }
1.784     albertel  953:     }
                    954: 
                    955:     if (!$want_server_name) {
1.968     raeburn   956:         my $protocol = 'http';
                    957:         if ($protocol{$spare_server} eq 'https') {
                    958:             $protocol = $protocol{$spare_server};
                    959:         }
1.1001    raeburn   960:         if (defined($spare_server)) {
                    961:             my $hostname = &hostname($spare_server);
1.1083    raeburn   962:             if (defined($hostname)) {
1.1001    raeburn   963: 	        $spare_server = $protocol.'://'.$hostname;
                    964:             }
                    965:         }
1.784     albertel  966:     }
                    967:     return $spare_server;
                    968: }
                    969: 
                    970: sub compare_server_load {
1.1172.2.41  raeburn   971:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                    972: 
                    973:     if ($required) {
                    974:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                    975:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                    976:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                    977:         if (($major eq '' && $minor eq '') ||
                    978:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                    979:             return ($spare_server,$lowest_load);
                    980:         }
                    981:     }
1.784     albertel  982: 
                    983:     my $loadans     = &reply('load',    $try_server);
                    984:     my $userloadans = &reply('userload',$try_server);
                    985: 
                    986:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   987: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  988:     }
                    989: 
                    990:     my $load;
                    991:     if ($loadans =~ /\d/) {
                    992: 	if ($userloadans =~ /\d/) {
                    993: 	    #both are numbers, pick the bigger one
                    994: 	    $load = ($loadans > $userloadans) ? $loadans 
                    995: 		                              : $userloadans;
1.411     albertel  996: 	} else {
1.784     albertel  997: 	    $load = $loadans;
1.411     albertel  998: 	}
1.784     albertel  999:     } else {
                   1000: 	$load = $userloadans;
                   1001:     }
                   1002: 
                   1003:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                   1004: 	$spare_server = $try_server;
                   1005: 	$lowest_load  = $load;
1.370     albertel 1006:     }
1.784     albertel 1007:     return ($spare_server,$lowest_load);
1.202     matthew  1008: }
1.914     albertel 1009: 
                   1010: # --------------------------- ask offload servers if user already has a session
                   1011: sub find_existing_session {
                   1012:     my ($udom,$uname) = @_;
1.1123    raeburn  1013:     my $spareshash = &this_host_spares($udom);
                   1014:     if (ref($spareshash) eq 'HASH') {
                   1015:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                   1016:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                   1017:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1018:             }
                   1019:         }
                   1020:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                   1021:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                   1022:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1023:             }
                   1024:         }
1.914     albertel 1025:     }
                   1026:     return;
                   1027: }
                   1028: 
1.1172.2.107  raeburn  1029: # check if user's browser sent load balancer cookie and server still has session
                   1030: # and is not overloaded.
                   1031: sub check_for_balancer_cookie {
                   1032:     my ($r,$update_mtime) = @_;
                   1033:     my ($otherserver,$cookie);
                   1034:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                   1035:     if (exists($cookies{'balanceID'})) {
                   1036:         my $balid = $cookies{'balanceID'};
                   1037:         $cookie=&LONCAPA::clean_handle($balid->value);
                   1038:         my $balancedir=$r->dir_config('lonBalanceDir');
                   1039:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
                   1040:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
                   1041:                 my ($possudom,$possuname) = ($1,$2);
                   1042:                 my $has_session = 0;
                   1043:                 if ((&domain($possudom) ne '') &&
                   1044:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
                   1045:                     my $try_server;
                   1046:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
                   1047:                     if ($opened) {
                   1048:                         flock($idf,LOCK_SH);
                   1049:                         while (my $line = <$idf>) {
                   1050:                             chomp($line);
                   1051:                             if (&hostname($line) ne '') {
                   1052:                                 $try_server = $line;
                   1053:                                 last;
                   1054:                             }
                   1055:                         }
                   1056:                         close($idf);
                   1057:                         if (($try_server) &&
                   1058:                             (&has_user_session($try_server,$possudom,$possuname))) {
                   1059:                             my $lowest_load = 30000;
                   1060:                             ($otherserver,$lowest_load) =
                   1061:                                 &compare_server_load($try_server,undef,$lowest_load);
                   1062:                             if ($otherserver ne '' && $lowest_load < 100) {
                   1063:                                 $has_session = 1;
                   1064:                             } else {
                   1065:                                 undef($otherserver);
                   1066:                             }
                   1067:                         }
                   1068:                     }
                   1069:                 }
                   1070:                 if ($has_session) {
                   1071:                     if ($update_mtime) {
                   1072:                         my $atime = my $mtime = time;
                   1073:                         utime($atime,$mtime,"$balancedir/$cookie.id");
                   1074:                     }
                   1075:                 } else {
                   1076:                     unlink("$balancedir/$cookie.id");
                   1077:                 }
                   1078:             }
                   1079:         }
                   1080:     }
                   1081:     return ($otherserver,$cookie);
                   1082: }
                   1083: 
                   1084: sub delbalcookie {
                   1085:     my ($cookie,$balancer) =@_;
                   1086:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
                   1087:         my ($udom,$uname) = ($1,$2);
                   1088:         my $uprimary_id = &domain($udom,'primary');
                   1089:         my $uintdom = &internet_dom($uprimary_id);
                   1090:         my $intdom = &internet_dom($balancer);
                   1091:         my $serverhomedom = &host_domain($balancer);
                   1092:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1093:             return &reply("delbalcookie:$cookie",$balancer);
                   1094:         }
                   1095:     }
                   1096: }
                   1097: 
1.914     albertel 1098: # -------------------------------- ask if server already has a session for user
                   1099: sub has_user_session {
                   1100:     my ($lonid,$udom,$uname) = @_;
                   1101:     my $result = &reply(join(':','userhassession',
                   1102: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                   1103:     return 1 if ($result eq 'ok');
                   1104: 
                   1105:     return 0;
                   1106: }
                   1107: 
1.1076    raeburn  1108: # --------- determine least loaded server in a user's domain which allows login
                   1109: 
                   1110: sub choose_server {
1.1172.2.47  raeburn  1111:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn  1112:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn  1113:     my %servers = &get_servers($udom);
1.1076    raeburn  1114:     my $lowest_load = 30000;
1.1172.2.47  raeburn  1115:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                   1116:     if ($skiploadbal) {
                   1117:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                   1118:         unless (defined($cached)) {
                   1119:             my $cachetime = 60*60*24;
                   1120:             my %domconfig =
                   1121:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1122:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1123:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                   1124:                                            $cachetime);
                   1125:             }
                   1126:         }
                   1127:     }
1.1076    raeburn  1128:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn  1129:         my $loginvia;
1.1172.2.47  raeburn  1130:         if ($skiploadbal) {
                   1131:             if (ref($balancers) eq 'HASH') {
                   1132:                 next if (exists($balancers->{$lonhost}));
                   1133:             }
                   1134:         }
1.1115    raeburn  1135:         if ($checkloginvia) {
                   1136:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn  1137:             if ($loginvia) {
                   1138:                 my ($server,$path) = split(/:/,$loginvia);
                   1139:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1140:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn  1141:                 if ($login_host eq $server) {
                   1142:                     $portal_path = $path;
1.1151    raeburn  1143:                     $isredirect = 1;
1.1116    raeburn  1144:                 }
                   1145:             } else {
                   1146:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1147:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn  1148:                 if ($login_host eq $lonhost) {
                   1149:                     $portal_path = '';
1.1151    raeburn  1150:                     $isredirect = ''; 
1.1116    raeburn  1151:                 }
                   1152:             }
                   1153:         } else {
1.1076    raeburn  1154:             ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1155:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1156:         }
                   1157:     }
                   1158:     if ($login_host ne '') {
1.1116    raeburn  1159:         $hostname = &hostname($login_host);
1.1076    raeburn  1160:     }
1.1172.2.88  raeburn  1161:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076    raeburn  1162: }
                   1163: 
1.202     matthew  1164: # --------------------------------------------- Try to change a user's password
                   1165: 
                   1166: sub changepass {
1.799     raeburn  1167:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1168:     $currentpass = &escape($currentpass);
                   1169:     $newpass     = &escape($newpass);
1.1030    raeburn  1170:     my $lonhost = $perlvar{'lonHostID'};
                   1171:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1172: 		       $server);
                   1173:     if (! $answer) {
                   1174: 	&logthis("No reply on password change request to $server ".
                   1175: 		 "by $uname in domain $udom.");
                   1176:     } elsif ($answer =~ "^ok") {
                   1177:         &logthis("$uname in $udom successfully changed their password ".
                   1178: 		 "on $server.");
                   1179:     } elsif ($answer =~ "^pwchange_failure") {
                   1180: 	&logthis("$uname in $udom was unable to change their password ".
                   1181: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1182: 		 "or pwchange");
                   1183:     } elsif ($answer =~ "^non_authorized") {
                   1184:         &logthis("$uname in $udom did not get their password correct when ".
                   1185: 		 "attempting to change it on $server.");
                   1186:     } elsif ($answer =~ "^auth_mode_error") {
                   1187:         &logthis("$uname in $udom attempted to change their password despite ".
                   1188: 		 "not being locally or internally authenticated on $server.");
                   1189:     } elsif ($answer =~ "^unknown_user") {
                   1190:         &logthis("$uname in $udom attempted to change their password ".
                   1191: 		 "on $server but were unable to because $server is not ".
                   1192: 		 "their home server.");
                   1193:     } elsif ($answer =~ "^refused") {
                   1194: 	&logthis("$server refused to change $uname in $udom password because ".
                   1195: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1196:     } elsif ($answer =~ "invalid_client") {
                   1197:         &logthis("$server refused to change $uname in $udom password because ".
                   1198:                  "it was a reset by e-mail originating from an invalid server.");
1.1172.2.113  raeburn  1199:     } elsif ($answer =~ "^prioruse") {
                   1200:        &logthis("$server refused to change $uname in $udom password because ".
                   1201:                 "the password had been used before");
1.202     matthew  1202:     }
                   1203:     return $answer;
1.1       albertel 1204: }
                   1205: 
1.169     harris41 1206: # ----------------------- Try to determine user's current authentication scheme
                   1207: 
                   1208: sub queryauthenticate {
                   1209:     my ($uname,$udom)=@_;
1.456     albertel 1210:     my $uhome=&homeserver($uname,$udom);
                   1211:     if (!$uhome) {
                   1212: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1213: 	return 'no_host';
                   1214:     }
                   1215:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1216:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1217: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1218:     }
1.456     albertel 1219:     return $answer;
1.169     harris41 1220: }
                   1221: 
1.1       albertel 1222: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1223: 
1.1       albertel 1224: sub authenticate {
1.1073    raeburn  1225:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1226:     $upass=&escape($upass);
                   1227:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1228:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1229:     my $newhome;
1.836     www      1230:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1231: # Maybe the machine was offline and only re-appeared again recently?
                   1232:         &reconlonc();
                   1233: # One more
1.952     raeburn  1234: 	$uhome=&homeserver($uname,$udom,1);
                   1235:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1236:             if (defined(&domain($udom,'primary'))) {
                   1237:                 $newhome=&domain($udom,'primary');
                   1238:             }
                   1239:             if ($newhome ne '') {
                   1240:                 $uhome = $newhome;
                   1241:             }
                   1242:         }
1.836     www      1243: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1244: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1245: 	    return 'no_host';
                   1246:         }
1.1       albertel 1247:     }
1.1073    raeburn  1248:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1249:     if ($answer eq 'authorized') {
1.952     raeburn  1250:         if ($newhome) {
                   1251:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1252:             return 'no_account_on_host'; 
                   1253:         } else {
                   1254:             &logthis("User $uname at $udom authorized by $uhome");
                   1255:             return $uhome;
                   1256:         }
1.471     albertel 1257:     }
                   1258:     if ($answer eq 'non_authorized') {
                   1259: 	&logthis("User $uname at $udom rejected by $uhome");
                   1260: 	return 'no_host'; 
1.9       www      1261:     }
1.471     albertel 1262:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1263:     return 'no_host';
                   1264: }
                   1265: 
1.1073    raeburn  1266: sub can_host_session {
1.1074    raeburn  1267:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1268:     my $canhost = 1;
1.1074    raeburn  1269:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1270:     if (ref($remotesessions) eq 'HASH') {
                   1271:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1272:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1273:                 $canhost = 0;
                   1274:             } else {
                   1275:                 $canhost = 1;
                   1276:             }
                   1277:         }
                   1278:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1279:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1280:                 $canhost = 1;
                   1281:             } else {
                   1282:                 $canhost = 0;
                   1283:             }
                   1284:         }
                   1285:         if ($canhost) {
                   1286:             if ($remotesessions->{'version'} ne '') {
                   1287:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1288:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1289:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1290:                         my $major = $1;
                   1291:                         my $minor = $2;
                   1292:                         if (($major < $reqmajor ) ||
                   1293:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1294:                             $canhost = 0;
                   1295:                         }
                   1296:                     } else {
                   1297:                         $canhost = 0;
                   1298:                     }
                   1299:                 }
                   1300:             }
                   1301:         }
                   1302:     }
                   1303:     if ($canhost) {
                   1304:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1305:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1306:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1307:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1308:                 if (($uint_dom ne '') && 
                   1309:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1310:                     $canhost = 0;
                   1311:                 } else {
                   1312:                     $canhost = 1;
                   1313:                 }
                   1314:             }
                   1315:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1316:                 if (($uint_dom ne '') && 
                   1317:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1318:                     $canhost = 1;
                   1319:                 } else {
                   1320:                     $canhost = 0;
                   1321:                 }
                   1322:             }
                   1323:         }
                   1324:     }
                   1325:     return $canhost;
                   1326: }
                   1327: 
1.1083    raeburn  1328: sub spare_can_host {
                   1329:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1330:     my $canhost=1;
1.1172.2.62  raeburn  1331:     my $try_server_hostname = &hostname($try_server);
                   1332:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1333:     my $serverhomedom = &host_domain($serverhomeID);
                   1334:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1335:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1336:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1337:             $canhost = 0;
                   1338:         }
                   1339:     }
                   1340:     if (($canhost) && ($uint_dom)) {
                   1341:         my @intdoms;
                   1342:         my $internet_names = &get_internet_names($try_server);
                   1343:         if (ref($internet_names) eq 'ARRAY') {
                   1344:             @intdoms = @{$internet_names};
                   1345:         }
                   1346:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1347:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1348:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1349:                                          $remotesessions,
                   1350:                                          $defdomdefaults{'hostedsessions'});
                   1351:         }
1.1083    raeburn  1352:     }
                   1353:     return $canhost;
                   1354: }
                   1355: 
1.1123    raeburn  1356: sub this_host_spares {
                   1357:     my ($dom) = @_;
1.1126    raeburn  1358:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1359:     my @hosts = &current_machine_ids();
                   1360:     foreach my $lonhost (@hosts) {
                   1361:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1362:             $dom_in_use = $dom;
                   1363:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1364:             last;
                   1365:         }
                   1366:     }
1.1126    raeburn  1367:     if ($dom_in_use ne '') {
                   1368:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1369:     }
                   1370:     if (ref($result) ne 'HASH') {
                   1371:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1372:         $dom_in_use = &host_domain($lonhost_in_use);
                   1373:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1374:         if (ref($result) ne 'HASH') {
                   1375:             $result = \%spareid;
                   1376:         }
                   1377:     }
                   1378:     return $result;
                   1379: }
                   1380: 
                   1381: sub spares_for_offload  {
                   1382:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1383:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1384:     if (defined($cached)) {
                   1385:         return $result;
                   1386:     } else {
1.1126    raeburn  1387:         my $cachetime = 60*60*24;
                   1388:         my %domconfig =
                   1389:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1390:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1391:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1392:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1393:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1394:                 }
                   1395:             }
                   1396:         }
                   1397:     }
1.1126    raeburn  1398:     return;
1.1123    raeburn  1399: }
                   1400: 
1.1129    raeburn  1401: sub get_lonbalancer_config {
                   1402:     my ($servers) = @_;
                   1403:     my ($currbalancer,$currtargets);
                   1404:     if (ref($servers) eq 'HASH') {
                   1405:         foreach my $server (keys(%{$servers})) {
                   1406:             my %what = (
                   1407:                          spareid => 1,
                   1408:                          perlvar => 1,
                   1409:                        );
                   1410:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1411:             if ($result eq 'ok') {
                   1412:                 if (ref($returnhash) eq 'HASH') {
                   1413:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1414:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1415:                             $currbalancer = $server;
                   1416:                             $currtargets = {};
                   1417:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1418:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1419:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1420:                                 }
                   1421:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1422:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1423:                                 }
                   1424:                             }
                   1425:                             last;
                   1426:                         }
                   1427:                     }
                   1428:                 }
                   1429:             }
                   1430:         }
                   1431:     }
                   1432:     return ($currbalancer,$currtargets);
                   1433: }
                   1434: 
                   1435: sub check_loadbalancing {
1.1172.2.88  raeburn  1436:     my ($uname,$udom,$caller) = @_;
1.1172.2.12  raeburn  1437:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1172.2.107  raeburn  1438:         $rule_in_effect,$offloadto,$otherserver,$setcookie);
1.1129    raeburn  1439:     my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4  raeburn  1440:     my @hosts = &current_machine_ids();
1.1129    raeburn  1441:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1442:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1443:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1444:     my $serverhomedom = &host_domain($lonhost);
1.1172.2.75  raeburn  1445:     my $domneedscache; 
1.1129    raeburn  1446:     my $cachetime = 60*60*24;
                   1447: 
                   1448:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1449:         $dom_in_use = $udom;
                   1450:         $homeintdom = 1;
                   1451:     } else {
                   1452:         $dom_in_use = $serverhomedom;
                   1453:     }
                   1454:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1455:     unless (defined($cached)) {
                   1456:         my %domconfig =
                   1457:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1458:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1459:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1172.2.75  raeburn  1460:         } else {
                   1461:             $domneedscache = $dom_in_use;
1.1129    raeburn  1462:         }
                   1463:     }
                   1464:     if (ref($result) eq 'HASH') {
1.1172.2.107  raeburn  1465:         ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12  raeburn  1466:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1467:         if ($is_balancer) {
                   1468:             if (ref($currrules) eq 'HASH') {
                   1469:                 if ($homeintdom) {
                   1470:                     if ($uname ne '') {
                   1471:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1472:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1473:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1474:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1475:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1476:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1477:                             }
                   1478:                         }
                   1479:                         if ($rule_in_effect eq '') {
                   1480:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1481:                             if ($userenv{'inststatus'} ne '') {
                   1482:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1483:                                 my ($othertitle,$usertypes,$types) =
                   1484:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1485:                                 if (ref($types) eq 'ARRAY') {
                   1486:                                     foreach my $type (@{$types}) {
                   1487:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1488:                                             if (exists($currrules->{$type})) {
                   1489:                                                 $rule_in_effect = $currrules->{$type};
                   1490:                                             }
                   1491:                                         }
                   1492:                                     }
                   1493:                                 }
                   1494:                             } else {
                   1495:                                 if (exists($currrules->{'default'})) {
                   1496:                                     $rule_in_effect = $currrules->{'default'};
                   1497:                                 }
                   1498:                             }
                   1499:                         }
                   1500:                     } else {
                   1501:                         if (exists($currrules->{'default'})) {
                   1502:                             $rule_in_effect = $currrules->{'default'};
                   1503:                         }
                   1504:                     }
                   1505:                 } else {
                   1506:                     if ($currrules->{'_LC_external'} ne '') {
                   1507:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1508:                     }
                   1509:                 }
                   1510:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1511:                                                        $uname,$udom);
                   1512:             }
                   1513:         }
                   1514:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35  raeburn  1515:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1516:         unless (defined($cached)) {
                   1517:             my %domconfig =
                   1518:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1519:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1172.2.75  raeburn  1520:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1521:             } else {
                   1522:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1523:             }
                   1524:         }
                   1525:         if (ref($result) eq 'HASH') {
1.1172.2.107  raeburn  1526:             ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12  raeburn  1527:                 &check_balancer_result($result,@hosts);
                   1528:             if ($is_balancer) {
1.1129    raeburn  1529:                 if (ref($currrules) eq 'HASH') {
                   1530:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1531:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1532:                     }
                   1533:                 }
                   1534:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1535:                                                        $uname,$udom);
                   1536:             }
                   1537:         } else {
                   1538:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1539:                 $is_balancer = 1;
                   1540:                 $offloadto = &this_host_spares($dom_in_use);
                   1541:             }
1.1172.2.75  raeburn  1542:             unless (defined($cached)) {
                   1543:                 $domneedscache = $serverhomedom;
                   1544:             }
1.1129    raeburn  1545:         }
                   1546:     } else {
                   1547:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1548:             $is_balancer = 1;
                   1549:             $offloadto = &this_host_spares($dom_in_use);
                   1550:         }
1.1172.2.75  raeburn  1551:         unless (defined($cached)) {
                   1552:             $domneedscache = $serverhomedom;
                   1553:         }
                   1554:     }
                   1555:     if ($domneedscache) {
                   1556:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1557:     }
1.1172.2.5  raeburn  1558:     if ($is_balancer) {
                   1559:         my $lowest_load = 30000;
                   1560:         if (ref($offloadto) eq 'HASH') {
                   1561:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1562:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1563:                     ($otherserver,$lowest_load) =
                   1564:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1565:                 }
1.1129    raeburn  1566:             }
1.1172.2.5  raeburn  1567:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1568: 
1.1172.2.5  raeburn  1569:             if (!$found_server) {
                   1570:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1571:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1572:                         ($otherserver,$lowest_load) =
                   1573:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1574:                     }
                   1575:                 }
                   1576:             }
                   1577:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1578:             if (@{$offloadto} == 1) {
                   1579:                 $otherserver = $offloadto->[0];
                   1580:             } elsif (@{$offloadto} > 1) {
                   1581:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1582:                     ($otherserver,$lowest_load) =
                   1583:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1584:                 }
                   1585:             }
                   1586:         }
1.1172.2.88  raeburn  1587:         unless ($caller eq 'login') {
                   1588:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1589:                 $is_balancer = 0;
                   1590:                 if ($uname ne '' && $udom ne '') {
                   1591:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1592:                         &appenv({'user.loadbalexempt'     => $lonhost,
                   1593:                                  'user.loadbalcheck.time' => time});
                   1594:                     }
1.1172.2.5  raeburn  1595:                 }
1.1129    raeburn  1596:             }
                   1597:         }
1.1172.2.107  raeburn  1598:         unless ($homeintdom) {
                   1599:             undef($setcookie);
                   1600:         }
1.1129    raeburn  1601:     }
1.1172.2.107  raeburn  1602:     return ($is_balancer,$otherserver,$setcookie);
1.1129    raeburn  1603: }
                   1604: 
1.1172.2.12  raeburn  1605: sub check_balancer_result {
                   1606:     my ($result,@hosts) = @_;
1.1172.2.107  raeburn  1607:     my ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12  raeburn  1608:     if (ref($result) eq 'HASH') {
                   1609:         if ($result->{'lonhost'} ne '') {
                   1610:             my $currbalancer = $result->{'lonhost'};
                   1611:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1612:                 $is_balancer = 1;
                   1613:                 $currtargets = $result->{'targets'};
                   1614:                 $currrules = $result->{'rules'};
                   1615:             }
                   1616:         } else {
                   1617:             foreach my $key (keys(%{$result})) {
                   1618:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1619:                     (ref($result->{$key}) eq 'HASH')) {
                   1620:                     $is_balancer = 1;
                   1621:                     $currrules = $result->{$key}{'rules'};
                   1622:                     $currtargets = $result->{$key}{'targets'};
1.1172.2.107  raeburn  1623:                     $setcookie = $result->{$key}{'cookie'};
1.1172.2.12  raeburn  1624:                     last;
                   1625:                 }
                   1626:             }
                   1627:         }
                   1628:     }
1.1172.2.107  raeburn  1629:     return ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12  raeburn  1630: }
                   1631: 
1.1129    raeburn  1632: sub get_loadbalancer_targets {
                   1633:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1634:     my $offloadto;
1.1172.2.4  raeburn  1635:     if ($rule_in_effect eq 'none') {
                   1636:         return [$perlvar{'lonHostID'}];
                   1637:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1638:         $offloadto = $currtargets;
                   1639:     } else {
                   1640:         if ($rule_in_effect eq 'homeserver') {
                   1641:             my $homeserver = &homeserver($uname,$udom);
                   1642:             if ($homeserver ne 'no_host') {
                   1643:                 $offloadto = [$homeserver];
                   1644:             }
                   1645:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1646:             my %domconfig =
                   1647:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1648:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1649:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1650:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1651:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1652:                     }
                   1653:                 }
                   1654:             } else {
1.1172.2.7  raeburn  1655:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1656:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1657:                 if (&hostname($remotebalancer) ne '') {
                   1658:                     $offloadto = [$remotebalancer];
                   1659:                 }
                   1660:             }
                   1661:         } elsif (&hostname($rule_in_effect) ne '') {
                   1662:             $offloadto = [$rule_in_effect];
                   1663:         }
                   1664:     }
                   1665:     return $offloadto;
                   1666: }
                   1667: 
1.1127    raeburn  1668: sub internet_dom_servers {
                   1669:     my ($dom) = @_;
                   1670:     my (%uniqservers,%servers);
                   1671:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1672:     my @machinedoms = &machine_domains($primaryserver);
                   1673:     foreach my $mdom (@machinedoms) {
                   1674:         my %currservers = %servers;
                   1675:         my %server = &get_servers($mdom);
                   1676:         %servers = (%currservers,%server);
                   1677:     }
                   1678:     my %by_hostname;
                   1679:     foreach my $id (keys(%servers)) {
                   1680:         push(@{$by_hostname{$servers{$id}}},$id);
                   1681:     }
                   1682:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1683:         if (@{$by_hostname{$hostname}} > 1) {
                   1684:             my $match = 0;
                   1685:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1686:                 if (&host_domain($id) eq $dom) {
                   1687:                     $uniqservers{$id} = $hostname;
                   1688:                     $match = 1;
                   1689:                 }
                   1690:             }
                   1691:             unless ($match) {
                   1692:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1693:             }
                   1694:         } else {
                   1695:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1696:         }
                   1697:     }
                   1698:     return %uniqservers;
                   1699: }
                   1700: 
1.1       albertel 1701: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1702: 
1.599     albertel 1703: my %homecache;
1.1       albertel 1704: sub homeserver {
1.230     stredwic 1705:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1706:     my $index="$uname:$udom";
1.426     albertel 1707: 
1.599     albertel 1708:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1709: 
                   1710:     my %servers = &get_servers($udom,'library');
                   1711:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1712:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1713: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1714: 
                   1715: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1716: 	if ($answer eq 'found') {
                   1717: 	    delete($badServerCache{$tryserver}); 
                   1718: 	    return $homecache{$index}=$tryserver;
                   1719: 	} elsif ($answer eq 'no_host') {
                   1720: 	    $badServerCache{$tryserver}=1;
                   1721: 	}
1.1       albertel 1722:     }    
                   1723:     return 'no_host';
1.70      www      1724: }
                   1725: 
                   1726: # ------------------------------------- Find the usernames behind a list of IDs
                   1727: 
                   1728: sub idget {
                   1729:     my ($udom,@ids)=@_;
                   1730:     my %returnhash=();
                   1731:     
1.841     albertel 1732:     my %servers = &get_servers($udom,'library');
                   1733:     foreach my $tryserver (keys(%servers)) {
1.1172.2.73  raeburn  1734: 	my $idlist=join('&', map { &escape($_); } @ids);
1.841     albertel 1735: 	$idlist=~tr/A-Z/a-z/; 
                   1736: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1737: 	my @answer=();
                   1738: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1739: 	    @answer=split(/\&/,$reply);
                   1740: 	}                    ;
                   1741: 	my $i;
                   1742: 	for ($i=0;$i<=$#ids;$i++) {
                   1743: 	    if ($answer[$i]) {
1.1172.2.73  raeburn  1744: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.841     albertel 1745: 	    } 
                   1746: 	}
                   1747:     } 
1.70      www      1748:     return %returnhash;
                   1749: }
                   1750: 
                   1751: # ------------------------------------- Find the IDs behind a list of usernames
                   1752: 
                   1753: sub idrget {
                   1754:     my ($udom,@unames)=@_;
                   1755:     my %returnhash=();
1.800     albertel 1756:     foreach my $uname (@unames) {
                   1757:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1758:     }
1.70      www      1759:     return %returnhash;
                   1760: }
                   1761: 
                   1762: # ------------------------------- Store away a list of names and associated IDs
                   1763: 
                   1764: sub idput {
                   1765:     my ($udom,%ids)=@_;
                   1766:     my %servers=();
1.800     albertel 1767:     foreach my $uname (keys(%ids)) {
                   1768: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1769:         my $uhom=&homeserver($uname,$udom);
1.70      www      1770:         if ($uhom ne 'no_host') {
1.800     albertel 1771:             my $id=&escape($ids{$uname});
1.70      www      1772:             $id=~tr/A-Z/a-z/;
1.800     albertel 1773:             my $esc_unam=&escape($uname);
1.70      www      1774: 	    if ($servers{$uhom}) {
1.800     albertel 1775: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1776:             } else {
1.800     albertel 1777:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1778:             }
                   1779:         }
1.191     harris41 1780:     }
1.800     albertel 1781:     foreach my $server (keys(%servers)) {
                   1782:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1783:     }
1.344     www      1784: }
                   1785: 
1.1172.2.30  raeburn  1786: # ---------------------------------------- Delete unwanted IDs from ids.db file
                   1787: 
                   1788: sub iddel {
                   1789:     my ($udom,$idshashref,$uhome)=@_;
                   1790:     my %result=();
                   1791:     unless (ref($idshashref) eq 'HASH') {
                   1792:         return %result;
                   1793:     }
                   1794:     my %servers=();
                   1795:     while (my ($id,$uname) = each(%{$idshashref})) {
                   1796:         my $uhom;
                   1797:         if ($uhome) {
                   1798:             $uhom = $uhome;
                   1799:         } else {
                   1800:             $uhom=&homeserver($uname,$udom);
                   1801:         }
                   1802:         if ($uhom ne 'no_host') {
                   1803:             if ($servers{$uhom}) {
                   1804:                 $servers{$uhom}.='&'.&escape($id);
                   1805:             } else {
                   1806:                 $servers{$uhom}=&escape($id);
                   1807:             }
                   1808:         }
                   1809:     }
                   1810:     foreach my $server (keys(%servers)) {
                   1811:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1812:     }
                   1813:     return %result;
                   1814: }
                   1815: 
1.1023    raeburn  1816: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1817: sub dump_dom {
1.1165    droeschl 1818:     my ($namespace, $udom, $regexp) = @_;
                   1819: 
                   1820:     $udom ||= $env{'user.domain'};
                   1821: 
                   1822:     return () unless $udom;
                   1823: 
                   1824:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1825: }
                   1826: 
1.1023    raeburn  1827: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1828: 
                   1829: sub get_dom {
1.860     raeburn  1830:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1172.2.57  raeburn  1831:     return if ($udom eq 'public');
1.806     raeburn  1832:     my $items='';
                   1833:     foreach my $item (@$storearr) {
                   1834:         $items.=&escape($item).'&';
                   1835:     }
                   1836:     $items=~s/\&$//;
1.860     raeburn  1837:     if (!$udom) {
                   1838:         $udom=$env{'user.domain'};
1.1172.2.57  raeburn  1839:         return if ($udom eq 'public');
1.860     raeburn  1840:         if (defined(&domain($udom,'primary'))) {
                   1841:             $uhome=&domain($udom,'primary');
                   1842:         } else {
1.874     albertel 1843:             undef($uhome);
1.860     raeburn  1844:         }
                   1845:     } else {
                   1846:         if (!$uhome) {
                   1847:             if (defined(&domain($udom,'primary'))) {
                   1848:                 $uhome=&domain($udom,'primary');
                   1849:             }
                   1850:         }
                   1851:     }
                   1852:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1853:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1854:         my %returnhash;
1.875     albertel 1855:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1856:             return %returnhash;
                   1857:         }
1.806     raeburn  1858:         my @pairs=split(/\&/,$rep);
                   1859:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1860:             return @pairs;
                   1861:         }
                   1862:         my $i=0;
                   1863:         foreach my $item (@$storearr) {
                   1864:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1865:             $i++;
                   1866:         }
                   1867:         return %returnhash;
                   1868:     } else {
1.880     banghart 1869:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1870:     }
                   1871: }
                   1872: 
                   1873: # -------------------------------------------- put items in domain db files 
                   1874: 
                   1875: sub put_dom {
1.860     raeburn  1876:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1877:     if (!$udom) {
                   1878:         $udom=$env{'user.domain'};
                   1879:         if (defined(&domain($udom,'primary'))) {
                   1880:             $uhome=&domain($udom,'primary');
                   1881:         } else {
1.874     albertel 1882:             undef($uhome);
1.860     raeburn  1883:         }
                   1884:     } else {
                   1885:         if (!$uhome) {
                   1886:             if (defined(&domain($udom,'primary'))) {
                   1887:                 $uhome=&domain($udom,'primary');
                   1888:             }
                   1889:         }
                   1890:     } 
                   1891:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1892:         my $items='';
                   1893:         foreach my $item (keys(%$storehash)) {
                   1894:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1895:         }
                   1896:         $items=~s/\&$//;
                   1897:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1898:     } else {
1.860     raeburn  1899:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1900:     }
                   1901: }
                   1902: 
1.1023    raeburn  1903: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1904: sub newput_dom {
1.1023    raeburn  1905:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1906:     my $result;
                   1907:     if (!$udom) {
                   1908:         $udom=$env{'user.domain'};
                   1909:     }
1.1023    raeburn  1910:     if ($udom) {
                   1911:         my $uname = &get_domainconfiguser($udom);
                   1912:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1913:     }
                   1914:     return $result;
                   1915: }
                   1916: 
1.1023    raeburn  1917: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1918: sub del_dom {
1.1023    raeburn  1919:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1920:     if (ref($storearr) eq 'ARRAY') {
                   1921:         if (!$udom) {
                   1922:             $udom=$env{'user.domain'};
                   1923:         }
1.1023    raeburn  1924:         if ($udom) {
                   1925:             my $uname = &get_domainconfiguser($udom); 
                   1926:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1927:         }
                   1928:     }
                   1929: }
                   1930: 
1.1023    raeburn  1931: # ----------------------------------construct domainconfig user for a domain 
                   1932: sub get_domainconfiguser {
                   1933:     my ($udom) = @_;
                   1934:     return $udom.'-domainconfig';
                   1935: }
                   1936: 
1.837     raeburn  1937: sub retrieve_inst_usertypes {
                   1938:     my ($udom) = @_;
                   1939:     my (%returnhash,@order);
1.989     raeburn  1940:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1941:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1942:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44  raeburn  1943:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  1944:     } else {
                   1945:         if (defined(&domain($udom,'primary'))) {
                   1946:             my $uhome=&domain($udom,'primary');
                   1947:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1948:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44  raeburn  1949:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  1950:                 return (\%returnhash,\@order);
                   1951:             }
                   1952:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1953:             my @pairs=split(/\&/,$hashitems);
                   1954:             foreach my $item (@pairs) {
                   1955:                 my ($key,$value)=split(/=/,$item,2);
                   1956:                 $key = &unescape($key);
                   1957:                 next if ($key =~ /^error: 2 /);
                   1958:                 $returnhash{$key}=&thaw_unescape($value);
                   1959:             }
                   1960:             my @esc_order = split(/\&/,$orderitems);
                   1961:             foreach my $item (@esc_order) {
                   1962:                 push(@order,&unescape($item));
                   1963:             }
                   1964:         } else {
1.1172.2.44  raeburn  1965:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  1966:         }
1.1172.2.44  raeburn  1967:         return (\%returnhash,\@order);
1.837     raeburn  1968:     }
                   1969: }
                   1970: 
1.868     raeburn  1971: sub is_domainimage {
                   1972:     my ($url) = @_;
1.1172.2.74  raeburn  1973:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  1974:         if (&domain($1) ne '') {
                   1975:             return '1';
                   1976:         }
                   1977:     }
                   1978:     return;
                   1979: }
                   1980: 
1.899     raeburn  1981: sub inst_directory_query {
                   1982:     my ($srch) = @_;
                   1983:     my $udom = $srch->{'srchdomain'};
                   1984:     my %results;
                   1985:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1986:     my $outcome;
1.899     raeburn  1987:     if ($homeserver ne '') {
1.904     albertel 1988: 	my $queryid=&reply("querysend:instdirsearch:".
                   1989: 			   &escape($srch->{'srchby'}).':'.
                   1990: 			   &escape($srch->{'srchterm'}).':'.
                   1991: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1992: 	my $host=&hostname($homeserver);
                   1993: 	if ($queryid !~/^\Q$host\E\_/) {
1.1172.2.96  raeburn  1994: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 1995: 	    return;
                   1996: 	}
                   1997: 	my $response = &get_query_reply($queryid);
                   1998: 	my $maxtries = 5;
                   1999: 	my $tries = 1;
                   2000: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2001: 	    $response = &get_query_reply($queryid);
                   2002: 	    $tries ++;
                   2003: 	}
                   2004: 
                   2005:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  2006:             if ($response eq 'unavailable') {
                   2007:                 $outcome = $response;
                   2008:             } else {
                   2009:                 $outcome = 'ok';
                   2010:                 my @matches = split(/\n/,$response);
                   2011:                 foreach my $match (@matches) {
                   2012:                     my ($key,$value) = split(/=/,$match);
                   2013:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   2014:                 }
1.899     raeburn  2015:             }
                   2016:         }
                   2017:     }
1.909     raeburn  2018:     return ($outcome,%results);
1.899     raeburn  2019: }
                   2020: 
                   2021: sub usersearch {
                   2022:     my ($srch) = @_;
                   2023:     my $dom = $srch->{'srchdomain'};
                   2024:     my %results;
                   2025:     my %libserv = &all_library();
                   2026:     my $query = 'usersearch';
                   2027:     foreach my $tryserver (keys(%libserv)) {
                   2028:         if (&host_domain($tryserver) eq $dom) {
                   2029:             my $host=&hostname($tryserver);
                   2030:             my $queryid=
1.911     raeburn  2031:                 &reply("querysend:".&escape($query).':'.
                   2032:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2033:                        &escape($srch->{'srchtype'}).':'.
                   2034:                        &escape($srch->{'srchterm'}),$tryserver);
                   2035:             if ($queryid !~/^\Q$host\E\_/) {
                   2036:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2037:                 next;
1.899     raeburn  2038:             }
                   2039:             my $reply = &get_query_reply($queryid);
                   2040:             my $maxtries = 1;
                   2041:             my $tries = 1;
                   2042:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2043:                 $reply = &get_query_reply($queryid);
                   2044:                 $tries ++;
                   2045:             }
                   2046:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2047:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2048:             } else {
1.911     raeburn  2049:                 my @matches;
                   2050:                 if ($reply =~ /\n/) {
                   2051:                     @matches = split(/\n/,$reply);
                   2052:                 } else {
                   2053:                     @matches = split(/\&/,$reply);
                   2054:                 }
1.899     raeburn  2055:                 foreach my $match (@matches) {
                   2056:                     my ($uname,$udom,%userhash);
1.911     raeburn  2057:                     foreach my $entry (split(/:/,$match)) {
                   2058:                         my ($key,$value) =
                   2059:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2060:                         $userhash{$key} = $value;
                   2061:                         if ($key eq 'username') {
                   2062:                             $uname = $value;
                   2063:                         } elsif ($key eq 'domain') {
                   2064:                             $udom = $value;
1.911     raeburn  2065:                         }
1.899     raeburn  2066:                     }
                   2067:                     $results{$uname.':'.$udom} = \%userhash;
                   2068:                 }
                   2069:             }
                   2070:         }
                   2071:     }
                   2072:     return %results;
                   2073: }
                   2074: 
1.912     raeburn  2075: sub get_instuser {
                   2076:     my ($udom,$uname,$id) = @_;
                   2077:     my $homeserver = &domain($udom,'primary');
                   2078:     my ($outcome,%results);
                   2079:     if ($homeserver ne '') {
                   2080:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2081:                            &escape($id).':'.&escape($udom),$homeserver);
                   2082:         my $host=&hostname($homeserver);
                   2083:         if ($queryid !~/^\Q$host\E\_/) {
                   2084:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2085:             return;
                   2086:         }
                   2087:         my $response = &get_query_reply($queryid);
                   2088:         my $maxtries = 5;
                   2089:         my $tries = 1;
                   2090:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2091:             $response = &get_query_reply($queryid);
                   2092:             $tries ++;
                   2093:         }
                   2094:         if (!&error($response) && $response ne 'refused') {
                   2095:             if ($response eq 'unavailable') {
                   2096:                 $outcome = $response;
                   2097:             } else {
                   2098:                 $outcome = 'ok';
                   2099:                 my @matches = split(/\n/,$response);
                   2100:                 foreach my $match (@matches) {
                   2101:                     my ($key,$value) = split(/=/,$match);
                   2102:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2103:                 }
                   2104:             }
                   2105:         }
                   2106:     }
                   2107:     my %userinfo;
                   2108:     if (ref($results{$uname}) eq 'HASH') {
                   2109:         %userinfo = %{$results{$uname}};
                   2110:     } 
                   2111:     return ($outcome,%userinfo);
                   2112: }
                   2113: 
1.1172.2.69  raeburn  2114: sub get_multiple_instusers {
                   2115:     my ($udom,$users,$caller) = @_;
                   2116:     my ($outcome,$results);
                   2117:     if (ref($users) eq 'HASH') {
                   2118:         my $count = keys(%{$users});
                   2119:         my $requested = &freeze_escape($users);
                   2120:         my $homeserver = &domain($udom,'primary');
                   2121:         if ($homeserver ne '') {
                   2122:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2123:             my $host=&hostname($homeserver);
                   2124:             if ($queryid !~/^\Q$host\E\_/) {
                   2125:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2126:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2127:                 return ($outcome,$results);
                   2128:             }
                   2129:             my $response = &get_query_reply($queryid);
                   2130:             my $maxtries = 5;
                   2131:             if ($count > 100) {
                   2132:                 $maxtries = 1+int($count/20);
                   2133:             }
                   2134:             my $tries = 1;
                   2135:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2136:                 $response = &get_query_reply($queryid);
                   2137:                 $tries ++;
                   2138:             }
                   2139:             if ($response eq '') {
                   2140:                 $results = {};
                   2141:                 foreach my $key (keys(%{$users})) {
                   2142:                     my ($uname,$id);
                   2143:                     if ($caller eq 'id') {
                   2144:                         $id = $key;
                   2145:                     } else {
                   2146:                         $uname = $key;
                   2147:                     }
                   2148:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
                   2149:                     $outcome = $resp;
                   2150:                     if ($resp eq 'ok') {
                   2151:                         %{$results} = (%{$results}, %info);
                   2152:                     } else {
                   2153:                         last;
                   2154:                     }
                   2155:                 }
                   2156:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2157:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2158:                     $outcome = $response;
                   2159:                 } else {
                   2160:                     ($outcome,my $userdata) = split(/=/,$response,2);
                   2161:                     if ($outcome eq 'ok') {
                   2162:                         $results = &thaw_unescape($userdata);
                   2163:                     }
                   2164:                 }
                   2165:             }
                   2166:         }
                   2167:     }
                   2168:     return ($outcome,$results);
                   2169: }
                   2170: 
1.912     raeburn  2171: sub inst_rulecheck {
1.923     raeburn  2172:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2173:     my %returnhash;
                   2174:     if ($udom ne '') {
                   2175:         if (ref($rules) eq 'ARRAY') {
                   2176:             @{$rules} = map {&escape($_);} (@{$rules});
                   2177:             my $rulestr = join(':',@{$rules});
                   2178:             my $homeserver=&domain($udom,'primary');
                   2179:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2180:                 my $response;
                   2181:                 if ($item eq 'username') {                
                   2182:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2183:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2184:                                               $homeserver));
1.923     raeburn  2185:                 } elsif ($item eq 'id') {
                   2186:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2187:                                               ':'.&escape($id).':'.$rulestr,
                   2188:                                               $homeserver));
1.945     raeburn  2189:                 } elsif ($item eq 'selfcreate') {
                   2190:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2191:                                                &escape($udom).':'.&escape($uname).
                   2192:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2193:                 }
1.912     raeburn  2194:                 if ($response ne 'refused') {
                   2195:                     my @pairs=split(/\&/,$response);
                   2196:                     foreach my $item (@pairs) {
                   2197:                         my ($key,$value)=split(/=/,$item,2);
                   2198:                         $key = &unescape($key);
                   2199:                         next if ($key =~ /^error: 2 /);
                   2200:                         $returnhash{$key}=&thaw_unescape($value);
                   2201:                     }
                   2202:                 }
                   2203:             }
                   2204:         }
                   2205:     }
                   2206:     return %returnhash;
                   2207: }
                   2208: 
                   2209: sub inst_userrules {
1.923     raeburn  2210:     my ($udom,$check) = @_;
1.912     raeburn  2211:     my (%ruleshash,@ruleorder);
                   2212:     if ($udom ne '') {
                   2213:         my $homeserver=&domain($udom,'primary');
                   2214:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2215:             my $response;
                   2216:             if ($check eq 'id') {
                   2217:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2218:                                  $homeserver);
1.943     raeburn  2219:             } elsif ($check eq 'email') {
                   2220:                 $response=&reply('instemailrules:'.&escape($udom),
                   2221:                                  $homeserver);
1.923     raeburn  2222:             } else {
                   2223:                 $response=&reply('instuserrules:'.&escape($udom),
                   2224:                                  $homeserver);
                   2225:             }
1.912     raeburn  2226:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2227:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2228:                 ($response ne 'no_such_host')) {
                   2229:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2230:                 my @pairs=split(/\&/,$hashitems);
                   2231:                 foreach my $item (@pairs) {
                   2232:                     my ($key,$value)=split(/=/,$item,2);
                   2233:                     $key = &unescape($key);
                   2234:                     next if ($key =~ /^error: 2 /);
                   2235:                     $ruleshash{$key}=&thaw_unescape($value);
                   2236:                 }
                   2237:                 my @esc_order = split(/\&/,$orderitems);
                   2238:                 foreach my $item (@esc_order) {
                   2239:                     push(@ruleorder,&unescape($item));
                   2240:                 }
                   2241:             }
                   2242:         }
                   2243:     }
                   2244:     return (\%ruleshash,\@ruleorder);
                   2245: }
                   2246: 
1.976     raeburn  2247: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2248: 
                   2249: sub get_domain_defaults {
1.1172.2.35  raeburn  2250:     my ($domain,$ignore_cache) = @_;
                   2251:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2252:     my $cachetime = 60*60*24;
1.1172.2.35  raeburn  2253:     unless ($ignore_cache) {
                   2254:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2255:         if (defined($cached)) {
                   2256:             if (ref($result) eq 'HASH') {
                   2257:                 return %{$result};
                   2258:             }
1.943     raeburn  2259:         }
                   2260:     }
                   2261:     my %domdefaults;
                   2262:     my %domconfig =
1.989     raeburn  2263:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2264:                                   'requestcourses','inststatus',
1.1172.2.9  raeburn  2265:                                   'coursedefaults','usersessions',
1.1172.2.46  raeburn  2266:                                   'requestauthor','selfenrollment',
1.1172.2.89  raeburn  2267:                                   'coursecategories','autoenroll',
                   2268:                                   'helpsettings'],$domain);
1.1172.2.41  raeburn  2269:     my @coursetypes = ('official','unofficial','community','textbook');
1.943     raeburn  2270:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2271:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2272:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2273:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2274:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2275:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2276:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1172.2.91  raeburn  2277:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2278:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2279:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943     raeburn  2280:     } else {
                   2281:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2282:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2283:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2284:     }
1.976     raeburn  2285:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2286:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2287:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2288:         } else {
                   2289:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29  raeburn  2290:         }
1.1172.2.6  raeburn  2291:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2292:         foreach my $item (@usertools) {
                   2293:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2294:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2295:             }
                   2296:         }
1.1172.2.29  raeburn  2297:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2298:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2299:         }
1.976     raeburn  2300:     }
1.985     raeburn  2301:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37  raeburn  2302:         foreach my $item ('official','unofficial','community','textbook') {
1.985     raeburn  2303:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2304:         }
                   2305:     }
1.1172.2.9  raeburn  2306:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2307:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2308:     }
1.989     raeburn  2309:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44  raeburn  2310:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2311:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2312:         }
                   2313:     }
1.1047    raeburn  2314:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60  raeburn  2315:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2316:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2317:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2318:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2319:         }
1.1172.2.41  raeburn  2320:         foreach my $type (@coursetypes) {
                   2321:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2322:                 unless ($type eq 'community') {
                   2323:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2324:                 }
                   2325:             }
                   2326:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2327:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2328:             }
1.1172.2.60  raeburn  2329:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2330:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2331:                     $domdefaults{$type.'postsubtimeout'} =
                   2332:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
                   2333:                 }
                   2334:             }
1.1172.2.30  raeburn  2335:         }
1.1172.2.67  raeburn  2336:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2337:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2338:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2339:                 if (@clonecodes) {
                   2340:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2341:                 }
                   2342:             }
                   2343:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2344:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2345:         }
1.1172.2.103  raeburn  2346:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2347:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
                   2348:         }
1.1047    raeburn  2349:     }
1.1073    raeburn  2350:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2351:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2352:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2353:         }
                   2354:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2355:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2356:         }
1.1172.2.62  raeburn  2357:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2358:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2359:         }
1.1073    raeburn  2360:     }
1.1172.2.41  raeburn  2361:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2362:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2363:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2364:                             'approval','limit');
                   2365:             foreach my $type (@coursetypes) {
                   2366:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2367:                     my @mgrdc = ();
                   2368:                     foreach my $item (@settings) {
                   2369:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2370:                             push(@mgrdc,$item);
                   2371:                         }
                   2372:                     }
                   2373:                     if (@mgrdc) {
                   2374:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2375:                     }
                   2376:                 }
                   2377:             }
                   2378:         }
                   2379:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2380:             foreach my $type (@coursetypes) {
                   2381:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2382:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2383:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2384:                     }
                   2385:                 }
                   2386:             }
                   2387:         }
                   2388:     }
1.1172.2.46  raeburn  2389:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2390:         $domdefaults{'catauth'} = 'std';
                   2391:         $domdefaults{'catunauth'} = 'std';
                   2392:         if ($domconfig{'coursecategories'}{'auth'}) {
                   2393:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2394:         }
                   2395:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2396:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2397:         }
                   2398:     }
1.1172.2.76  raeburn  2399:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2400:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2401:     }
1.1172.2.89  raeburn  2402:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2403:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2404:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2405:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2406:         }
                   2407:     }
1.1172.2.23  raeburn  2408:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2409:     return %domdefaults;
                   2410: }
                   2411: 
1.1172.2.106  raeburn  2412: sub get_dom_cats {
                   2413:     my ($dom) = @_;
                   2414:     return unless (&domain($dom));
                   2415:     my ($cats,$cached)=&is_cached_new('cats',$dom);
                   2416:     unless (defined($cached)) {
                   2417:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
                   2418:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2419:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
                   2420:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
                   2421:             } else {
                   2422:                 $cats = {};
                   2423:             }
                   2424:         } else {
                   2425:             $cats = {};
                   2426:         }
                   2427:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
                   2428:     }
                   2429:     return $cats;
                   2430: }
                   2431: 
                   2432: sub get_dom_instcats {
                   2433:     my ($dom) = @_;
                   2434:     return unless (&domain($dom));
                   2435:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
                   2436:     unless (defined($cached)) {
                   2437:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
                   2438:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
                   2439:         if ($totcodes > 0) {
                   2440:             my $caller = 'global';
                   2441:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
                   2442:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
                   2443:                 $instcats = {
                   2444:                                 codes => \%codes,
                   2445:                                 codetitles => \@codetitles,
                   2446:                                 cat_titles => \%cat_titles,
                   2447:                                 cat_order => \%cat_order,
                   2448:                             };
                   2449:                 &do_cache_new('instcats',$dom,$instcats,3600);
                   2450:             }
                   2451:         }
                   2452:     }
                   2453:     return $instcats;
                   2454: }
                   2455: 
                   2456: sub retrieve_instcodes {
                   2457:     my ($coursecodes,$dom) = @_;
                   2458:     my $totcodes;
                   2459:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
                   2460:     foreach my $course (keys(%courses)) {
                   2461:         if (ref($courses{$course}) eq 'HASH') {
                   2462:             if ($courses{$course}{'inst_code'} ne '') {
                   2463:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
                   2464:                 $totcodes ++;
                   2465:             }
                   2466:         }
                   2467:     }
                   2468:     return $totcodes;
                   2469: }
                   2470: 
1.1172.2.113  raeburn  2471: # --------------------------------------------- Get domain config for passwords
                   2472: 
                   2473: sub get_passwdconf {
                   2474:     my ($dom) = @_;
                   2475:     my (%passwdconf,$gotconf,$lookup);
                   2476:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
                   2477:     if (defined($cached)) {
                   2478:         if (ref($result) eq 'HASH') {
                   2479:             %passwdconf = %{$result};
                   2480:             $gotconf = 1;
                   2481:         }
                   2482:     }
                   2483:     unless ($gotconf) {
                   2484:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
                   2485:         if (ref($domconfig{'passwords'}) eq 'HASH') {
                   2486:             %passwdconf = %{$domconfig{'passwords'}};
                   2487:         }
                   2488:         my $cachetime = 24*60*60;
                   2489:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
                   2490:     }
                   2491:     return %passwdconf;
                   2492: }
                   2493: 
1.344     www      2494: # --------------------------------------------------- Assign a key to a student
                   2495: 
                   2496: sub assign_access_key {
1.364     www      2497: #
                   2498: # a valid key looks like uname:udom#comments
                   2499: # comments are being appended
                   2500: #
1.498     www      2501:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2502:     $kdom=
1.620     albertel 2503:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2504:     $knum=
1.620     albertel 2505:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2506:     $cdom=
1.620     albertel 2507:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2508:     $cnum=
1.620     albertel 2509:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2510:     $udom=$env{'user.name'} unless (defined($udom));
                   2511:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2512:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2513:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2514:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2515:                                                   # assigned to this person
                   2516:                                                   # - this should not happen,
1.345     www      2517:                                                   # unless something went wrong
                   2518:                                                   # the first time around
                   2519: # ready to assign
1.364     www      2520:         $logentry=$1.'; '.$logentry;
1.496     www      2521:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2522:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2523: # key now belongs to user
1.346     www      2524: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2525:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2526:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2527:                 return 'ok';
                   2528:             } else {
                   2529:                 return 
                   2530:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2531: 	    }
                   2532:         } else {
                   2533:             return 'error: Could not assign key, try again later.';
                   2534:         }
1.364     www      2535:     } elsif (!$existing{$ckey}) {
1.345     www      2536: # the key does not exist
                   2537: 	return 'error: The key does not exist';
                   2538:     } else {
                   2539: # the key is somebody else's
                   2540: 	return 'error: The key is already in use';
                   2541:     }
1.344     www      2542: }
                   2543: 
1.364     www      2544: # ------------------------------------------ put an additional comment on a key
                   2545: 
                   2546: sub comment_access_key {
                   2547: #
                   2548: # a valid key looks like uname:udom#comments
                   2549: # comments are being appended
                   2550: #
                   2551:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2552:     $cdom=
1.620     albertel 2553:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2554:     $cnum=
1.620     albertel 2555:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2556:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2557:     if ($existing{$ckey}) {
                   2558:         $existing{$ckey}.='; '.$logentry;
                   2559: # ready to assign
1.367     www      2560:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2561:                                                  $cdom,$cnum) eq 'ok') {
                   2562: 	    return 'ok';
                   2563:         } else {
                   2564: 	    return 'error: Count not store comment.';
                   2565:         }
                   2566:     } else {
                   2567: # the key does not exist
                   2568: 	return 'error: The key does not exist';
                   2569:     }
                   2570: }
                   2571: 
1.344     www      2572: # ------------------------------------------------------ Generate a set of keys
                   2573: 
                   2574: sub generate_access_keys {
1.364     www      2575:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2576:     $cdom=
1.620     albertel 2577:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2578:     $cnum=
1.620     albertel 2579:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2580:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2581:     unless (($cdom) && ($cnum)) { return 0; }
                   2582:     if ($number>10000) { return 0; }
                   2583:     sleep(2); # make sure don't get same seed twice
                   2584:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2585:     my $total=0;
                   2586:     for (my $i=1;$i<=$number;$i++) {
                   2587:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2588:                   sprintf("%lx",int(100000*rand)).'-'.
                   2589:                   sprintf("%lx",int(100000*rand));
                   2590:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2591:        $newkey=~s/0/h/g; # and also 0 and O
                   2592:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2593:        if ($existing{$newkey}) {
                   2594:            $i--;
                   2595:        } else {
1.364     www      2596: 	  if (&put('accesskeys',
                   2597:               { $newkey => '# generated '.localtime().
1.620     albertel 2598:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2599:                            '; '.$logentry },
                   2600: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2601:               $total++;
                   2602: 	  }
                   2603:        }
                   2604:     }
1.620     albertel 2605:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2606:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2607:     return $total;
                   2608: }
                   2609: 
                   2610: # ------------------------------------------------------- Validate an accesskey
                   2611: 
                   2612: sub validate_access_key {
                   2613:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2614:     $cdom=
1.620     albertel 2615:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2616:     $cnum=
1.620     albertel 2617:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2618:     $udom=$env{'user.domain'} unless (defined($udom));
                   2619:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2620:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2621:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2622: }
                   2623: 
                   2624: # ------------------------------------- Find the section of student in a course
1.652     albertel 2625: sub devalidate_getsection_cache {
                   2626:     my ($udom,$unam,$courseid)=@_;
                   2627:     my $hashid="$udom:$unam:$courseid";
                   2628:     &devalidate_cache_new('getsection',$hashid);
                   2629: }
1.298     matthew  2630: 
1.815     albertel 2631: sub courseid_to_courseurl {
                   2632:     my ($courseid) = @_;
                   2633:     #already url style courseid
                   2634:     return $courseid if ($courseid =~ m{^/});
                   2635: 
                   2636:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2637: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2638: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2639: 	return "/$cdom/$cnum";
                   2640:     }
                   2641: 
                   2642:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2643:     if (exists($courseinfo{'num'})) {
                   2644: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2645:     }
                   2646: 
                   2647:     return undef;
                   2648: }
                   2649: 
1.298     matthew  2650: sub getsection {
                   2651:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2652:     my $cachetime=1800;
1.551     albertel 2653: 
                   2654:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2655:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2656:     if (defined($cached)) { return $result; }
                   2657: 
1.298     matthew  2658:     my %Pending; 
                   2659:     my %Expired;
                   2660:     #
                   2661:     # Each role can either have not started yet (pending), be active, 
                   2662:     #    or have expired.
                   2663:     #
                   2664:     # If there is an active role, we are done.
                   2665:     #
                   2666:     # If there is more than one role which has not started yet, 
                   2667:     #     choose the one which will start sooner
                   2668:     # If there is one role which has not started yet, return it.
                   2669:     #
                   2670:     # If there is more than one expired role, choose the one which ended last.
                   2671:     # If there is a role which has expired, return it.
                   2672:     #
1.815     albertel 2673:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2674:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2675:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2676:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2677:         my $section=$1;
                   2678:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2679:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2680:         my $now=time;
1.548     albertel 2681:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2682:             $Expired{$end}=$section;
                   2683:             next;
                   2684:         }
1.548     albertel 2685:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2686:             $Pending{$start}=$section;
                   2687:             next;
                   2688:         }
1.599     albertel 2689:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2690:     }
                   2691:     #
                   2692:     # Presumedly there will be few matching roles from the above
                   2693:     # loop and the sorting time will be negligible.
                   2694:     if (scalar(keys(%Pending))) {
                   2695:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2696:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2697:     } 
                   2698:     if (scalar(keys(%Expired))) {
                   2699:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2700:         my $time = pop(@sorted);
1.599     albertel 2701:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2702:     }
1.599     albertel 2703:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2704: }
1.70      www      2705: 
1.599     albertel 2706: sub save_cache {
                   2707:     &purge_remembered();
1.722     albertel 2708:     #&Apache::loncommon::validate_page();
1.620     albertel 2709:     undef(%env);
1.780     albertel 2710:     undef($env_loaded);
1.599     albertel 2711: }
1.452     albertel 2712: 
1.599     albertel 2713: my $to_remember=-1;
                   2714: my %remembered;
                   2715: my %accessed;
                   2716: my $kicks=0;
                   2717: my $hits=0;
1.849     albertel 2718: sub make_key {
                   2719:     my ($name,$id) = @_;
1.872     albertel 2720:     if (length($id) > 65 
                   2721: 	&& length(&escape($id)) > 200) {
                   2722: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2723:     }
1.849     albertel 2724:     return &escape($name.':'.$id);
                   2725: }
                   2726: 
1.599     albertel 2727: sub devalidate_cache_new {
                   2728:     my ($name,$id,$debug) = @_;
                   2729:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81  raeburn  2730:     my $remembered_id=$name.':'.$id;
1.849     albertel 2731:     $id=&make_key($name,$id);
1.599     albertel 2732:     $memcache->delete($id);
1.1172.2.81  raeburn  2733:     delete($remembered{$remembered_id});
                   2734:     delete($accessed{$remembered_id});
1.599     albertel 2735: }
                   2736: 
                   2737: sub is_cached_new {
                   2738:     my ($name,$id,$debug) = @_;
1.1172.2.81  raeburn  2739:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for 
                   2740:                                      # keys in %remembered hash, which persists for
                   2741:                                      # duration of request (no restriction on key length).
                   2742:     if (exists($remembered{$remembered_id})) {
                   2743: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2744: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2745: 	$hits++;
1.1172.2.81  raeburn  2746: 	return ($remembered{$remembered_id},1);
1.599     albertel 2747:     }
1.1172.2.81  raeburn  2748:     $id=&make_key($name,$id);
1.599     albertel 2749:     my $value = $memcache->get($id);
                   2750:     if (!(defined($value))) {
                   2751: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2752: 	return (undef,undef);
1.416     albertel 2753:     }
1.599     albertel 2754:     if ($value eq '__undef__') {
                   2755: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2756: 	$value=undef;
                   2757:     }
1.1172.2.81  raeburn  2758:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2759:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2760:     return ($value,1);
                   2761: }
                   2762: 
                   2763: sub do_cache_new {
                   2764:     my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81  raeburn  2765:     my $remembered_id=$name.':'.$id;
1.849     albertel 2766:     $id=&make_key($name,$id);
1.599     albertel 2767:     my $setvalue=$value;
                   2768:     if (!defined($setvalue)) {
                   2769: 	$setvalue='__undef__';
                   2770:     }
1.623     albertel 2771:     if (!defined($time) ) {
                   2772: 	$time=600;
                   2773:     }
1.599     albertel 2774:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2775:     my $result = $memcache->set($id,$setvalue,$time);
                   2776:     if (! $result) {
1.872     albertel 2777: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2778: 	$memcache->disconnect_all();
1.872     albertel 2779:     }
1.600     albertel 2780:     # need to make a copy of $value
1.1172.2.81  raeburn  2781:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2782:     return $value;
                   2783: }
                   2784: 
                   2785: sub make_room {
1.1172.2.81  raeburn  2786:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 2787: 
1.1172.2.81  raeburn  2788:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 2789:                                     : $value;
1.599     albertel 2790:     if ($to_remember<0) { return; }
1.1172.2.81  raeburn  2791:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2792:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2793:     my $to_kick;
                   2794:     my $max_time=0;
                   2795:     foreach my $other (keys(%accessed)) {
                   2796: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2797: 	    $to_kick=$other;
                   2798: 	    $max_time=&tv_interval($accessed{$other});
                   2799: 	}
                   2800:     }
                   2801:     delete($remembered{$to_kick});
                   2802:     delete($accessed{$to_kick});
                   2803:     $kicks++;
                   2804:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2805:     return;
                   2806: }
                   2807: 
1.599     albertel 2808: sub purge_remembered {
1.604     albertel 2809:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2810:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2811:     undef(%remembered);
                   2812:     undef(%accessed);
1.428     albertel 2813: }
1.70      www      2814: # ------------------------------------- Read an entry from a user's environment
                   2815: 
                   2816: sub userenvironment {
                   2817:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2818:     my $items;
                   2819:     foreach my $item (@what) {
                   2820:         $items.=&escape($item).'&';
                   2821:     }
                   2822:     $items=~s/\&$//;
1.70      www      2823:     my %returnhash=();
1.1009    raeburn  2824:     my $uhome = &homeserver($unam,$udom);
                   2825:     unless ($uhome eq 'no_host') {
                   2826:         my @answer=split(/\&/, 
                   2827:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2828:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2829:             return %returnhash;
                   2830:         }
1.1009    raeburn  2831:         my $i;
                   2832:         for ($i=0;$i<=$#what;$i++) {
                   2833: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2834:         }
1.70      www      2835:     }
                   2836:     return %returnhash;
1.1       albertel 2837: }
                   2838: 
1.617     albertel 2839: # ---------------------------------------------------------- Get a studentphoto
                   2840: sub studentphoto {
                   2841:     my ($udom,$unam,$ext) = @_;
                   2842:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2843:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2844:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2845:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2846:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2847:             } else {
                   2848:                 my ($result,$perm_reqd)=
1.707     albertel 2849: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2850:                 if ($result eq 'ok') {
                   2851:                     if (!($perm_reqd eq 'yes')) {
                   2852:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2853:                     }
                   2854:                 }
                   2855:             }
                   2856:         }
                   2857:     } else {
                   2858:         my ($result,$perm_reqd) = 
1.707     albertel 2859: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2860:         if ($result eq 'ok') {
                   2861:             if (!($perm_reqd eq 'yes')) {
                   2862:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2863:             }
                   2864:         }
                   2865:     }
                   2866:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2867: }
                   2868: 
                   2869: sub retrievestudentphoto {
                   2870:     my ($udom,$unam,$ext,$type) = @_;
                   2871:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2872:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2873:     if ($ret eq 'ok') {
                   2874:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2875:         if ($type eq 'thumbnail') {
                   2876:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2877:         }
                   2878:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2879:         return $tokenurl;
                   2880:     } else {
                   2881:         if ($type eq 'thumbnail') {
                   2882:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2883:         } else { 
                   2884:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2885:         }
1.617     albertel 2886:     }
                   2887: }
                   2888: 
1.263     www      2889: # -------------------------------------------------------------------- New chat
                   2890: 
                   2891: sub chatsend {
1.724     raeburn  2892:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2893:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2894:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2895:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2896:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2897: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2898: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2899: }
                   2900: 
                   2901: # ------------------------------------------ Find current version of a resource
                   2902: 
                   2903: sub getversion {
                   2904:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  2905:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2906:     return &currentversion(&filelocation('',$fname));
                   2907: }
                   2908: 
                   2909: sub currentversion {
                   2910:     my $fname=shift;
                   2911:     my $author=$fname;
                   2912:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2913:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2914:     my $home=&homeserver($uname,$udom);
1.292     www      2915:     if ($home eq 'no_host') { 
                   2916:         return -1; 
                   2917:     }
1.1112    www      2918:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2919:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2920: 	return -1;
                   2921:     }
1.1112    www      2922:     return $answer;
1.263     www      2923: }
                   2924: 
1.1111    www      2925: #
                   2926: # Return special version number of resource if set by override, empty otherwise
                   2927: #
                   2928: sub usedversion {
                   2929:     my $fname=shift;
                   2930:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2931:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2932:     if ($urlversion) { return $urlversion; }
                   2933:     return '';
                   2934: }
                   2935: 
1.1       albertel 2936: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2937: 
1.1       albertel 2938: sub subscribe {
                   2939:     my $fname=shift;
1.761     raeburn  2940:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2941:     $fname=~s/[\n\r]//g;
1.1       albertel 2942:     my $author=$fname;
                   2943:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2944:     my ($udom,$uname)=split(/\//,$author);
                   2945:     my $home=homeserver($uname,$udom);
1.335     albertel 2946:     if ($home eq 'no_host') {
                   2947:         return 'not_found';
1.1       albertel 2948:     }
                   2949:     my $answer=reply("sub:$fname",$home);
1.64      www      2950:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2951: 	$answer.=' by '.$home;
                   2952:     }
1.1       albertel 2953:     return $answer;
                   2954: }
                   2955:     
1.8       www      2956: # -------------------------------------------------------------- Replicate file
                   2957: 
                   2958: sub repcopy {
                   2959:     my $filename=shift;
1.23      www      2960:     $filename=~s/\/+/\//g;
1.1142    raeburn  2961:     my $londocroot = $perlvar{'lonDocRoot'};
                   2962:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2963:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2964:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2965: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2966: 	return &repcopy_userfile($filename);
                   2967:     }
1.532     albertel 2968:     $filename=~s/[\n\r]//g;
1.8       www      2969:     my $transname="$filename.in.transfer";
1.828     www      2970: # FIXME: this should flock
1.607     raeburn  2971:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2972:     my $remoteurl=subscribe($filename);
1.64      www      2973:     if ($remoteurl =~ /^con_lost by/) {
                   2974: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2975:            return 'unavailable';
1.8       www      2976:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2977: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2978: 	   return 'not_found';
1.64      www      2979:     } elsif ($remoteurl =~ /^rejected by/) {
                   2980: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2981:            return 'forbidden';
1.20      www      2982:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2983:            return 'ok';
1.8       www      2984:     } else {
1.290     www      2985:         my $author=$filename;
                   2986:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2987:         my ($udom,$uname)=split(/\//,$author);
                   2988:         my $home=homeserver($uname,$udom);
                   2989:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2990:            my @parts=split(/\//,$filename);
                   2991:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2992:            if ($path ne "$londocroot/res") {
1.8       www      2993:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2994: 	       return 'bad_request';
1.8       www      2995:            }
                   2996:            my $count;
                   2997:            for ($count=5;$count<$#parts;$count++) {
                   2998:                $path.="/$parts[$count]";
                   2999:                if ((-e $path)!=1) {
                   3000: 		   mkdir($path,0777);
                   3001:                }
                   3002:            }
                   3003:            my $ua=new LWP::UserAgent;
                   3004:            my $request=new HTTP::Request('GET',"$remoteurl");
                   3005:            my $response=$ua->request($request,$transname);
                   3006:            if ($response->is_error()) {
                   3007: 	       unlink($transname);
                   3008:                my $message=$response->status_line;
1.672     albertel 3009:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      3010:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  3011:                return 'unavailable';
1.8       www      3012:            } else {
1.16      www      3013: 	       if ($remoteurl!~/\.meta$/) {
                   3014:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   3015:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   3016:                   if ($mresponse->is_error()) {
                   3017: 		      unlink($filename.'.meta');
                   3018:                       &logthis(
1.672     albertel 3019:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      3020:                   }
                   3021: 	       }
1.8       www      3022:                rename($transname,$filename);
1.607     raeburn  3023:                return 'ok';
1.8       www      3024:            }
1.290     www      3025:        }
1.8       www      3026:     }
1.330     www      3027: }
                   3028: 
                   3029: # ------------------------------------------------ Get server side include body
                   3030: sub ssi_body {
1.381     albertel 3031:     my ($filelink,%form)=@_;
1.606     matthew  3032:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3033:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3034:     }
1.953     www      3035:     my $output='';
                   3036:     my $response;
1.980     raeburn  3037:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3038:        ($output,$response)=&externalssi($filelink);
1.953     www      3039:     } else {
1.1004    droeschl 3040:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3041:        $filelink .= 'inhibitmenu=yes';
1.953     www      3042:        ($output,$response)=&ssi($filelink,%form);
                   3043:     }
1.778     albertel 3044:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3045:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3046:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3047:     if (wantarray) {
                   3048:         return ($output, $response);
                   3049:     } else {
                   3050:         return $output;
                   3051:     }
1.8       www      3052: }
                   3053: 
1.15      www      3054: # --------------------------------------------------------- Server Side Include
                   3055: 
1.782     albertel 3056: sub absolute_url {
                   3057:     my ($host_name) = @_;
                   3058:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3059:     if ($host_name eq '') {
                   3060: 	$host_name = $ENV{'SERVER_NAME'};
                   3061:     }
                   3062:     return $protocol.$host_name;
                   3063: }
                   3064: 
1.942     foxr     3065: #
                   3066: #   Server side include.
                   3067: # Parameters:
                   3068: #  fn     Possibly encrypted resource name/id.
                   3069: #  form   Hash that describes how the rendering should be done
                   3070: #         and other things.
1.944     foxr     3071: # Returns:
1.950     raeburn  3072: #   Scalar context: The content of the response.
                   3073: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3074: #     
1.15      www      3075: sub ssi {
                   3076: 
1.944     foxr     3077:     my ($fn,%form)=@_;
1.1172.2.100  raeburn  3078:     my ($request,$response);
1.711     albertel 3079: 
                   3080:     $form{'no_update_last_known'}=1;
1.895     albertel 3081:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3082:     if (%form) {
1.782     albertel 3083:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1172.2.58  raeburn  3084:       $request->content(join('&',map {
                   3085:             my $name = escape($_);
                   3086:             "$name=" . ( ref($form{$_}) eq 'ARRAY'
                   3087:             ? join("&$name=", map {escape($_) } @{$form{$_}})
                   3088:             : &escape($form{$_}) );
                   3089:         } keys(%form)));
1.23      www      3090:     } else {
1.782     albertel 3091:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      3092:     }
                   3093: 
1.15      www      3094:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.100  raeburn  3095: 
1.1172.2.101  raeburn  3096:     if (($env{'request.course.id'}) &&
                   3097:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
                   3098:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
                   3099:         ($form{'grade_symb'} ne '') &&
                   3100:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
                   3101:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
1.1172.2.100  raeburn  3102:         if (LWP::UserAgent->VERSION >= 5.834) {
                   3103:             my $ua=new LWP::UserAgent;
                   3104:             $ua->local_address('127.0.0.1');
                   3105:             $response = $ua->request($request);
                   3106:         } else {
                   3107:             {
                   3108:                 require LWP::Protocol::http;
                   3109:                 local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => '127.0.0.1');
                   3110:                 my $ua=new LWP::UserAgent;
                   3111:                 $response = $ua->request($request);
                   3112:                 @LWP::Protocol::http::EXTRA_SOCK_OPTS = ();
                   3113:             }
                   3114:         }
                   3115:     } else {
                   3116:         my $ua=new LWP::UserAgent;
                   3117:         $response = $ua->request($request);
                   3118:     }
1.944     foxr     3119:     if (wantarray) {
1.1172.2.3  raeburn  3120: 	return ($response->content, $response);
1.944     foxr     3121:     } else {
1.1172.2.3  raeburn  3122: 	return $response->content;
1.942     foxr     3123:     }
1.324     www      3124: }
                   3125: 
                   3126: sub externalssi {
                   3127:     my ($url)=@_;
                   3128:     my $ua=new LWP::UserAgent;
                   3129:     my $request=new HTTP::Request('GET',$url);
                   3130:     my $response=$ua->request($request);
1.954     raeburn  3131:     if (wantarray) {
                   3132:         return ($response->content, $response);
                   3133:     } else {
                   3134:         return $response->content;
                   3135:     }
1.15      www      3136: }
1.254     www      3137: 
1.1172.2.98  raeburn  3138: # If the local copy of a replicated resource is outdated, trigger a
                   3139: # connection from the homeserver to flush the delayed queue. If no update
                   3140: # happens, remove local copies of outdated resource (and corresponding
                   3141: # metadata file).
                   3142: 
                   3143: sub remove_stale_resfile {
                   3144:     my ($url) = @_;
                   3145:     my $removed;
                   3146:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3147:         my $audom = $1;
                   3148:         my $auname = $2;
                   3149:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
                   3150:             my $homeserver = &homeserver($auname,$audom);
                   3151:             unless (($homeserver eq 'no_host') ||
                   3152:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3153:                 my $fname = &filelocation('',$url);
                   3154:                 if (-e $fname) {
                   3155:                     my $ua=new LWP::UserAgent;
                   3156:                     $ua->timeout(5);
                   3157:                     my $protocol = $protocol{$homeserver};
                   3158:                     $protocol = 'http' if ($protocol ne 'https');
                   3159:                     my $hostname = &hostname($homeserver);
                   3160:                     if ($hostname) {
                   3161:                         my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
                   3162:                         my $request=new HTTP::Request('HEAD',$uri);
                   3163:                         my $response=$ua->request($request);
                   3164:                         if ($response->is_success()) {
                   3165:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3166:                             my $locmodtime = (stat($fname))[9];
                   3167:                             if ($locmodtime < $remmodtime) {
                   3168:                                 my $stale;
                   3169:                                 my $answer = &reply('pong',$homeserver);
                   3170:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3171:                                     sleep(0.2);
                   3172:                                     $locmodtime = (stat($fname))[9];
                   3173:                                     if ($locmodtime < $remmodtime) {
                   3174:                                         my $posstransfer = $fname.'.in.transfer';
                   3175:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3176:                                             $removed = 1;
                   3177:                                         } else {
                   3178:                                             $stale = 1;
                   3179:                                         }
                   3180:                                     } else {
                   3181:                                         $removed = 1;
                   3182:                                     }
                   3183:                                 } else {
                   3184:                                     $stale = 1;
                   3185:                                 }
                   3186:                                 if ($stale) {
                   3187:                                     unlink($fname);
                   3188:                                     if ($uri!~/\.meta$/) {
                   3189:                                         unlink($fname.'.meta');
                   3190:                                     }
                   3191:                                     &reply("unsub:$fname",$homeserver);
                   3192:                                     $removed = 1;
                   3193:                                 }
                   3194:                             }
                   3195:                         }
                   3196:                     }
                   3197:                 }
                   3198:             }
                   3199:         }
                   3200:     }
                   3201:     return $removed;
                   3202: }
                   3203: 
1.492     albertel 3204: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3205: 
                   3206: sub allowuploaded {
                   3207:     my ($srcurl,$url)=@_;
                   3208:     $url=&clutter(&declutter($url));
                   3209:     my $dir=$url;
                   3210:     $dir=~s/\/[^\/]+$//;
                   3211:     my %httpref=();
                   3212:     my $httpurl=&hreflocation('',$url);
                   3213:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3214:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3215: }
1.477     raeburn  3216: 
1.1172.2.13  raeburn  3217: #
                   3218: # Determine if the current user should be able to edit a particular resource,
                   3219: # when viewing in course context.
                   3220: # (a) When viewing resource used to determine if "Edit" item is included in
                   3221: #     Functions.
                   3222: # (b) When displaying folder contents in course editor, used to determine if
                   3223: #     "Edit" link will be displayed alongside resource.
                   3224: #
                   3225: #  input: six args -- filename (decluttered), course number, course domain,
                   3226: #                   url, symb (if registered) and group (if this is a group
                   3227: #                   item -- e.g., bulletin board, group page etc.).
                   3228: #  output: array of five scalars --
                   3229: #          $cfile -- url for file editing if editable on current server
                   3230: #          $home -- homeserver of resource (i.e., for author if published,
                   3231: #                                           or course if uploaded.).
                   3232: #          $switchserver --  1 if server switch will be needed.
                   3233: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   3234: #          $forceview -- 1 if icon/link should be to go to view mode
                   3235: #
                   3236: 
                   3237: sub can_edit_resource {
                   3238:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3239:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3240: #
                   3241: # For aboutme pages user can only edit his/her own.
                   3242: #
                   3243:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   3244:         my ($sdom,$sname) = ($1,$2);
                   3245:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3246:             $home = $env{'user.home'};
                   3247:             $cfile = $resurl;
                   3248:             if ($env{'form.forceedit'}) {
                   3249:                 $forceview = 1;
                   3250:             } else {
                   3251:                 $forceedit = 1;
                   3252:             }
                   3253:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3254:         } else {
                   3255:             return;
                   3256:         }
                   3257:     }
                   3258: 
                   3259:     if ($env{'request.course.id'}) {
                   3260:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3261:         if ($group ne '') {
                   3262: # if this is a group homepage or group bulletin board, check group privs
                   3263:             my $allowed = 0;
                   3264:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3265:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   3266:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3267:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3268:                     $allowed = 1;
                   3269:                 }
                   3270:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3271:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3272:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3273:                     $allowed = 1;
                   3274:                 }
                   3275:             }
                   3276:             if ($allowed) {
                   3277:                 $home=&homeserver($cnum,$cdom);
                   3278:                 if ($env{'form.forceedit'}) {
                   3279:                     $forceview = 1;
                   3280:                 } else {
                   3281:                     $forceedit = 1;
                   3282:                 }
                   3283:                 $cfile = $resurl;
                   3284:             } else {
                   3285:                 return;
                   3286:             }
                   3287:         } else {
1.1172.2.15  raeburn  3288:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3289:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3290:                     return;
                   3291:                 }
                   3292:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  3293: #
                   3294: # No edit allowed where CC has switched to student role.
                   3295: #
                   3296:                 return;
                   3297:             }
                   3298:         }
                   3299:     }
                   3300: 
                   3301:     if ($file ne '') {
                   3302:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   3303:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3304:                 $uploaded = 1;
                   3305:                 $incourse = 1;
                   3306:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3307:                     $cfile = &hreflocation('',$file);
                   3308:                     if ($env{'form.forceedit'}) {
                   3309:                         $forceview = 1;
                   3310:                     } else {
                   3311:                         $forceedit = 1;
                   3312:                     }
                   3313:                 }
                   3314:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3315:                 $incourse = 1;
                   3316:                 if ($env{'form.forceedit'}) {
                   3317:                     $forceview = 1;
                   3318:                 } else {
                   3319:                     $forceedit = 1;
                   3320:                 }
                   3321:                 $cfile = $resurl;
                   3322:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   3323:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3324:                     $incourse = 1;
                   3325:                     if ($env{'form.forceedit'}) {
                   3326:                         $forceview = 1;
                   3327:                     } else {
                   3328:                         $forceedit = 1;
                   3329:                     }
                   3330:                     $cfile = $resurl;
                   3331:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   3332:                     $incourse = 1;
                   3333:                     $cfile = $resurl.'/smpedit';
                   3334:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   3335:                     $incourse = 1;
                   3336:                     if ($env{'form.forceedit'}) {
                   3337:                         $forceview = 1;
                   3338:                     } else {
                   3339:                         $forceedit = 1;
                   3340:                     }
                   3341:                     $cfile = $resurl;
1.1172.2.15  raeburn  3342:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3343:                     $incourse = 1;
                   3344:                     if ($env{'form.forceedit'}) {
                   3345:                         $forceview = 1;
                   3346:                     } else {
                   3347:                         $forceedit = 1;
                   3348:                     }
                   3349:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3350:                 }
                   3351:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3352:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3353:                 if (&is_on_map($template)) {
                   3354:                     $incourse = 1;
                   3355:                     $forceview = 1;
                   3356:                     $cfile = $template;
                   3357:                 }
                   3358:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3359:                     $incourse = 1;
                   3360:                     if ($env{'form.forceedit'}) {
                   3361:                         $forceview = 1;
                   3362:                     } else {
                   3363:                         $forceedit = 1;
                   3364:                     }
                   3365:                     $cfile = $resurl;
                   3366:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3367:                 $incourse = 1;
                   3368:                 $forceview = 1;
                   3369:                 if ($symb) {
                   3370:                     my ($map,$id,$res)=&decode_symb($symb);
                   3371:                     $env{'request.symb'} = $symb;
                   3372:                     $cfile = &clutter($res);
                   3373:                 } else {
                   3374:                     $cfile = $env{'form.suppurl'};
                   3375:                     $cfile =~ s{^http://}{};
                   3376:                     $cfile = '/adm/wrapper/ext/'.$cfile;
                   3377:                 }
1.1172.2.31  raeburn  3378:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3379:                 if ($env{'form.forceedit'}) {
                   3380:                     $forceview = 1;
                   3381:                 } else {
                   3382:                     $forceedit = 1;
                   3383:                 }
                   3384:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3385:             }
                   3386:         }
                   3387:         if ($uploaded || $incourse) {
                   3388:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  3389:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  3390:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3391:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3392:             # Check that the user has permission to edit this resource
                   3393:             my $setpriv = 1;
                   3394:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3395:             if (defined($cfudom)) {
                   3396:                 $home=&homeserver($cfuname,$cfudom);
                   3397:                 $cfile=$file;
                   3398:             }
                   3399:         }
                   3400:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   3401:             (($home ne '') && ($home ne 'no_host'))) {
                   3402:             my @ids=&current_machine_ids();
                   3403:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3404:                 $switchserver=1;
                   3405:             }
                   3406:         }
                   3407:     }
                   3408:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3409: }
                   3410: 
                   3411: sub is_course_upload {
                   3412:     my ($file,$cnum,$cdom) = @_;
                   3413:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3414:     $uploadpath =~ s{^\/}{};
                   3415:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3416:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   3417:         return 1;
                   3418:     }
                   3419:     return;
                   3420: }
                   3421: 
                   3422: sub in_course {
                   3423:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3424:     if ($hideprivileged) {
                   3425:         my $skipuser;
1.1172.2.23  raeburn  3426:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3427:         my @possdoms = ($cdom);
                   3428:         if ($coursehash{'checkforpriv'}) {
                   3429:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   3430:         }
                   3431:         if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13  raeburn  3432:             $skipuser = 1;
                   3433:             if ($coursehash{'nothideprivileged'}) {
                   3434:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3435:                     my $user;
                   3436:                     if ($item =~ /:/) {
                   3437:                         $user = $item;
                   3438:                     } else {
                   3439:                         $user = join(':',split(/[\@]/,$item));
                   3440:                     }
                   3441:                     if ($user eq $uname.':'.$udom) {
                   3442:                         undef($skipuser);
                   3443:                         last;
                   3444:                     }
                   3445:                 }
                   3446:             }
                   3447:             if ($skipuser) {
                   3448:                 return 0;
                   3449:             }
                   3450:         }
                   3451:     }
                   3452:     $type ||= 'any';
                   3453:     if (!defined($cdom) || !defined($cnum)) {
                   3454:         my $cid  = $env{'request.course.id'};
                   3455:         $cdom = $env{'course.'.$cid.'.domain'};
                   3456:         $cnum = $env{'course.'.$cid.'.num'};
                   3457:     }
                   3458:     my $typesref;
                   3459:     if (($type eq 'any') || ($type eq 'all')) {
                   3460:         $typesref = ['active','previous','future'];
                   3461:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3462:         $typesref = [$type];
                   3463:     }
                   3464:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3465:                               $typesref,undef,[$cdom]);
                   3466:     my ($tmp) = keys(%roles);
                   3467:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3468:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3469:     if (@course_roles > 0) {
                   3470:         return 1;
                   3471:     }
                   3472:     return 0;
                   3473: }
                   3474: 
1.478     albertel 3475: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3476: # input: action, courseID, current domain, intended
1.637     raeburn  3477: #        path to file, source of file, instruction to parse file for objects,
                   3478: #        ref to hash for embedded objects,
                   3479: #        ref to hash for codebase of java objects.
1.1095    raeburn  3480: #        reference to scalar to accommodate mime type determined
                   3481: #          from File::MMagic if $parser = parse.
1.637     raeburn  3482: #
1.485     raeburn  3483: # output: url to file (if action was uploaddoc), 
                   3484: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3485: #
1.478     albertel 3486: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3487: # course.
1.477     raeburn  3488: #
1.478     albertel 3489: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3490: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3491: #          course's home server.
1.477     raeburn  3492: #
1.478     albertel 3493: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3494: #          be copied from $source (current location) to 
                   3495: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3496: #         and will then be copied to
                   3497: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3498: #         course's home server.
1.485     raeburn  3499: #
1.481     raeburn  3500: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3501: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3502: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3503: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3504: #         in course's home server.
1.637     raeburn  3505: #
1.477     raeburn  3506: 
                   3507: sub process_coursefile {
1.1095    raeburn  3508:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3509:         $mimetype)=@_;
1.477     raeburn  3510:     my $fetchresult;
1.638     albertel 3511:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3512:     if ($action eq 'propagate') {
1.638     albertel 3513:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3514: 			     $home);
1.481     raeburn  3515:     } else {
1.477     raeburn  3516:         my $fpath = '';
                   3517:         my $fname = $file;
1.478     albertel 3518:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3519:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3520:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3521:         if ($action eq 'copy') {
                   3522:             if ($source eq '') {
                   3523:                 $fetchresult = 'no source file';
                   3524:                 return $fetchresult;
                   3525:             } else {
                   3526:                 my $destination = $filepath.'/'.$fname;
                   3527:                 rename($source,$destination);
                   3528:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3529:                                  $home);
1.481     raeburn  3530:             }
                   3531:         } elsif ($action eq 'uploaddoc') {
1.1172.2.96  raeburn  3532:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3533:             print $fh $env{'form.'.$source};
1.481     raeburn  3534:             close($fh);
1.637     raeburn  3535:             if ($parser eq 'parse') {
1.1024    raeburn  3536:                 my $mm = new File::MMagic;
1.1095    raeburn  3537:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3538:                 if ($type eq 'text/html') {
1.1024    raeburn  3539:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3540:                     unless ($parse_result eq 'ok') {
                   3541:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3542:                     }
1.637     raeburn  3543:                 }
1.1095    raeburn  3544:                 if (ref($mimetype)) {
                   3545:                     $$mimetype = $type;
                   3546:                 } 
1.637     raeburn  3547:             }
1.477     raeburn  3548:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3549:                                  $home);
1.481     raeburn  3550:             if ($fetchresult eq 'ok') {
                   3551:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3552:             } else {
                   3553:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3554:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3555:                 return '/adm/notfound.html';
                   3556:             }
1.477     raeburn  3557:         }
                   3558:     }
1.485     raeburn  3559:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3560:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3561:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3562:     }
                   3563:     return $fetchresult;
                   3564: }
                   3565: 
1.637     raeburn  3566: sub build_filepath {
                   3567:     my ($fpath) = @_;
                   3568:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3569:     unless ($fpath eq '') {
                   3570:         my @parts=split('/',$fpath);
                   3571:         foreach my $part (@parts) {
                   3572:             $filepath.= '/'.$part;
                   3573:             if ((-e $filepath)!=1) {
                   3574:                 mkdir($filepath,0777);
                   3575:             }
                   3576:         }
                   3577:     }
                   3578:     return $filepath;
                   3579: }
                   3580: 
                   3581: sub store_edited_file {
1.638     albertel 3582:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3583:     my $file = $primary_url;
                   3584:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3585:     my $fpath = '';
                   3586:     my $fname = $file;
                   3587:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3588:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3589:     my $filepath = &build_filepath($fpath);
1.1172.2.96  raeburn  3590:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  3591:     print $fh $content;
                   3592:     close($fh);
1.638     albertel 3593:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3594:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3595: 			  $home);
1.637     raeburn  3596:     if ($$fetchresult eq 'ok') {
                   3597:         return '/uploaded/'.$fpath.'/'.$fname;
                   3598:     } else {
1.638     albertel 3599:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3600: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3601:         return '/adm/notfound.html';
                   3602:     }
                   3603: }
                   3604: 
1.531     albertel 3605: sub clean_filename {
1.831     albertel 3606:     my ($fname,$args)=@_;
1.315     www      3607: # Replace Windows backslashes by forward slashes
1.257     www      3608:     $fname=~s/\\/\//g;
1.831     albertel 3609:     if (!$args->{'keep_path'}) {
                   3610:         # Get rid of everything but the actual filename
                   3611: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3612:     }
1.315     www      3613: # Replace spaces by underscores
                   3614:     $fname=~s/\s+/\_/g;
1.1172.2.110  raeburn  3615: # Transliterate non-ascii text to ascii
                   3616:     my $lang = &Apache::lonlocal::current_language();
                   3617:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315     www      3618: # Replace all other weird characters by nothing
1.831     albertel 3619:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3620: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3621: # numbers
                   3622:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3623:     return $fname;
                   3624: }
1.1172.2.110  raeburn  3625: 
1.1051    raeburn  3626: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3627: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3628: # image with the same aspect ratio as the original, but with dimensions which do 
                   3629: # not exceed $resizewidth and $resizeheight.
                   3630:  
1.984     neumanie 3631: sub resizeImage {
1.1051    raeburn  3632:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3633:     my $ima = Image::Magick->new;
                   3634:     my $resized;
                   3635:     if (-e $img_path) {
                   3636:         $ima->Read($img_path);
                   3637:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3638:             my $width = $ima->Get('width');
                   3639:             my $height = $ima->Get('height');
                   3640:             if ($width > $resizewidth) {
                   3641: 	        my $factor = $width/$resizewidth;
                   3642:                 my $newheight = $height/$factor;
                   3643:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3644:                 $resized = 1;
                   3645:             }
                   3646:         }
                   3647:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3648:             my $width = $ima->Get('width');
                   3649:             my $height = $ima->Get('height');
                   3650:             if ($height > $resizeheight) {
                   3651:                 my $factor = $height/$resizeheight;
                   3652:                 my $newwidth = $width/$factor;
                   3653:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3654:                 $resized = 1;
                   3655:             }
                   3656:         }
                   3657:         if ($resized) {
                   3658:             $ima->Write($img_path);
                   3659:         }
                   3660:     }
                   3661:     return;
1.977     amueller 3662: }
                   3663: 
1.608     albertel 3664: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3665: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3666: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3667: #        $context - possible values: coursedoc, existingfile, overwrite, 
1.1172.2.109  raeburn  3668: #                                    canceloverwrite, scantron or ''. 
1.1090    raeburn  3669: #                   if 'coursedoc': upload to the current course
                   3670: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3671: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3672: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3673: #        $subdir - directory in userfile to store the file into
1.1172.2.109  raeburn  3674: #        $parser - instruction to parse file for objects ($parser = parse) or
                   3675: #                  if context is 'scantron', $parser is hashref of csv column mapping
                   3676: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
                   3677: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858     raeburn  3678: #        $allfiles - reference to hash for embedded objects
                   3679: #        $codebase - reference to hash for codebase of java objects
                   3680: #        $desuname - username for permanent storage of uploaded file
                   3681: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3682: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3683: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3684: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3685: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3686: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3687: #                    from File::MMagic.
1.858     raeburn  3688: # 
1.686     albertel 3689: # output: url of file in userspace, or error: <message> 
                   3690: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3691: 
1.531     albertel 3692: sub userfileupload {
1.1090    raeburn  3693:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3694:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3695:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3696:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3697:     $fname=&clean_filename($fname);
1.1090    raeburn  3698:     # See if there is anything left
1.257     www      3699:     unless ($fname) { return 'error: no uploaded file'; }
1.1172.2.110  raeburn  3700:     # If filename now begins with a . prepend unix timestamp _ milliseconds
                   3701:     if ($fname =~ /^\./) {
                   3702:         my ($s,$usec) = &gettimeofday();
                   3703:         while (length($usec) < 6) {
                   3704:             $usec = '0'.$usec;
                   3705:         }
                   3706:         $fname = $s.'_'.substr($usec,0,3).$fname;
                   3707:     }
1.1090    raeburn  3708:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3709:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3710:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3711:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3712:         my $now = time;
1.1090    raeburn  3713:         my $filepath;
1.1095    raeburn  3714:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3715:              $filepath = 'tmp/helprequests/'.$now;
                   3716:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3717:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3718:                          '_'.$env{'user.domain'}.'/pending';
                   3719:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3720:             my ($docuname,$docudom);
1.1172.2.96  raeburn  3721:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  3722:                 $docudom = $destudom;
                   3723:             } else {
                   3724:                 $docudom = $env{'user.domain'};
                   3725:             }
1.1172.2.96  raeburn  3726:             if ($destuname =~ /^$match_username$/) { 
1.1090    raeburn  3727:                 $docuname = $destuname;
                   3728:             } else {
                   3729:                 $docuname = $env{'user.name'};
                   3730:             }
                   3731:             if (exists($env{'form.group'})) {
                   3732:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3733:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3734:             }
                   3735:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3736:             if ($context eq 'canceloverwrite') {
                   3737:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3738:                 if (-e  $tempfile) {
                   3739:                     my @info = stat($tempfile);
                   3740:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3741:                         unlink($tempfile);
                   3742:                     }
                   3743:                 }
                   3744:                 return;
1.523     raeburn  3745:             }
                   3746:         }
1.1090    raeburn  3747:         # Create the directory if not present
1.741     raeburn  3748:         my @parts=split(/\//,$filepath);
                   3749:         my $fullpath = $perlvar{'lonDaemons'};
                   3750:         for (my $i=0;$i<@parts;$i++) {
                   3751:             $fullpath .= '/'.$parts[$i];
                   3752:             if ((-e $fullpath)!=1) {
                   3753:                 mkdir($fullpath,0777);
                   3754:             }
                   3755:         }
1.1172.2.96  raeburn  3756:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  3757:         print $fh $env{'form.'.$formname};
                   3758:         close($fh);
1.1090    raeburn  3759:         if ($context eq 'existingfile') {
                   3760:             my @info = stat($fullpath.'/'.$fname);
                   3761:             return ($fullpath.'/'.$fname,$info[9]);
                   3762:         } else {
                   3763:             return $fullpath.'/'.$fname;
                   3764:         }
1.523     raeburn  3765:     }
1.995     raeburn  3766:     if ($subdir eq 'scantron') {
                   3767:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3768:     } else {
1.995     raeburn  3769:         $fname="$subdir/$fname";
                   3770:     }
1.1090    raeburn  3771:     if ($context eq 'coursedoc') {
1.638     albertel 3772: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3773: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3774:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3775:             return &finishuserfileupload($docuname,$docudom,
                   3776: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3777: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3778:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3779:         } else {
1.1172.2.21  raeburn  3780:             if ($env{'form.folder'}) {
                   3781:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3782:             }
1.638     albertel 3783:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3784: 				       $fname,$formname,$parser,
1.1095    raeburn  3785: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3786:         }
1.719     banghart 3787:     } elsif (defined($destuname)) {
                   3788:         my $docuname=$destuname;
                   3789:         my $docudom=$destudom;
1.860     raeburn  3790: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3791: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3792:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3793:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3794:     } else {
1.638     albertel 3795:         my $docuname=$env{'user.name'};
                   3796:         my $docudom=$env{'user.domain'};
1.1172.2.23  raeburn  3797:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3798:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3799:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3800:         }
1.860     raeburn  3801: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3802: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3803:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3804:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3805:     }
1.271     www      3806: }
                   3807: 
                   3808: sub finishuserfileupload {
1.860     raeburn  3809:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3810:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3811:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3812:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3813:   
1.860     raeburn  3814:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3815:     $file=$fname;
                   3816:     if ($fname=~m|/|) {
                   3817:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3818: 	$path.=$fnamepath.'/';
                   3819:     }
1.259     www      3820:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3821:     my $count;
                   3822:     for ($count=4;$count<=$#parts;$count++) {
                   3823:         $filepath.="/$parts[$count]";
                   3824:         if ((-e $filepath)!=1) {
                   3825: 	    mkdir($filepath,0777);
                   3826:         }
                   3827:     }
1.984     neumanie 3828: 
1.258     www      3829: # Save the file
                   3830:     {
1.1172.2.96  raeburn  3831: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 3832: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3833: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3834: 	    return '/adm/notfound.html';
                   3835: 	}
1.1090    raeburn  3836:         if ($context eq 'overwrite') {
1.1117    foxr     3837:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3838:             my $target = $filepath.'/'.$file;
                   3839:             if (-e $source) {
                   3840:                 my @info = stat($source);
                   3841:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3842:                     unless (&File::Copy::move($source,$target)) {
                   3843:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3844:                         return "Moving from $source failed";
                   3845:                     }
                   3846:                 } else {
                   3847:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3848:                 }
                   3849:             } else {
                   3850:                 return "Temporary file: $source missing";
                   3851:             }
                   3852:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3853: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3854: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3855: 	    return '/adm/notfound.html';
                   3856: 	}
1.570     albertel 3857: 	close(FH);
1.1051    raeburn  3858:         if ($resizewidth && $resizeheight) {
                   3859:             my $mm = new File::MMagic;
                   3860:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3861:             if ($mime_type =~ m{^image/}) {
                   3862: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3863:             }  
1.977     amueller 3864: 	}
1.258     www      3865:     }
1.1152    raeburn  3866:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3867:         if (ref($mimetype)) {
                   3868:             if ($$mimetype eq '') {
                   3869:                 my $mm = new File::MMagic;
                   3870:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3871:                 $$mimetype = $type;
                   3872:             }
                   3873:         }
                   3874:     }
1.1172.2.109  raeburn  3875:     if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152    raeburn  3876:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3877:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3878:                                                        $allfiles,$codebase);
                   3879:             unless ($parse_result eq 'ok') {
                   3880:                 &logthis('Failed to parse '.$filepath.$file.
                   3881: 	   	         ' for embedded media: '.$parse_result); 
                   3882:             }
1.637     raeburn  3883:         }
1.1172.2.109  raeburn  3884:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
                   3885:         my $format = $env{'form.scantron_format'};
                   3886:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637     raeburn  3887:     }
1.860     raeburn  3888:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3889:         my $input = $filepath.'/'.$file;
                   3890:         my $output = $filepath.'/'.'tn-'.$file;
                   3891:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1172.2.96  raeburn  3892:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   3893:         system({$args[0]} @args);
1.860     raeburn  3894:         if (-e $filepath.'/'.'tn-'.$file) {
                   3895:             $fetchthumb  = 1; 
                   3896:         }
                   3897:     }
1.858     raeburn  3898:  
1.259     www      3899: # Notify homeserver to grep it
                   3900: #
1.984     neumanie 3901:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3902:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3903:     if ($fetchresult eq 'ok') {
1.860     raeburn  3904:         if ($fetchthumb) {
                   3905:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3906:             if ($thumbresult ne 'ok') {
                   3907:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3908:                          $docuhome.': '.$thumbresult);
                   3909:             }
                   3910:         }
1.259     www      3911: #
1.258     www      3912: # Return the URL to it
1.494     albertel 3913:         return '/uploaded/'.$path.$file;
1.263     www      3914:     } else {
1.494     albertel 3915:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3916: 		 ': '.$fetchresult);
1.263     www      3917:         return '/adm/notfound.html';
1.858     raeburn  3918:     }
1.493     albertel 3919: }
                   3920: 
1.637     raeburn  3921: sub extract_embedded_items {
1.961     raeburn  3922:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3923:     my @state = ();
1.1164    raeburn  3924:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3925:     my %javafiles = (
                   3926:                       codebase => '',
                   3927:                       code => '',
                   3928:                       archive => ''
                   3929:                     );
                   3930:     my %mediafiles = (
                   3931:                       src => '',
                   3932:                       movie => '',
                   3933:                      );
1.648     raeburn  3934:     my $p;
                   3935:     if ($content) {
                   3936:         $p = HTML::LCParser->new($content);
                   3937:     } else {
1.961     raeburn  3938:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3939:     }
1.641     albertel 3940:     while (my $t=$p->get_token()) {
1.640     albertel 3941: 	if ($t->[0] eq 'S') {
                   3942: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3943: 	    push(@state, $tagname);
1.648     raeburn  3944:             if (lc($tagname) eq 'allow') {
                   3945:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3946:             }
1.640     albertel 3947: 	    if (lc($tagname) eq 'img') {
                   3948: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3949: 	    }
1.886     albertel 3950: 	    if (lc($tagname) eq 'a') {
1.1172.2.24  raeburn  3951:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
                   3952: 		    &add_filetype($allfiles,$attr->{'href'},'href');
                   3953:                 }
1.886     albertel 3954: 	    }
1.645     raeburn  3955:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3956:                 my $src;
1.645     raeburn  3957:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3958:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3959:                 } else {
1.1164    raeburn  3960:                     if ($attr->{'src'} ne '') {
                   3961:                         $src = $attr->{'src'};
                   3962:                         &add_filetype($allfiles,$src,'src');
                   3963:                     }
                   3964:                 }
                   3965:                 my $text = $p->get_trimmed_text();
                   3966:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3967:                     my @swfargs = split(/,/,$1);
                   3968:                     foreach my $item (@swfargs) {
                   3969:                         $item =~ s/["']//g;
                   3970:                         $item =~ s/^\s+//;
                   3971:                         $item =~ s/\s+$//;
                   3972:                     }
                   3973:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3974:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3975:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3976:                         } else {
                   3977:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3978:                         }
                   3979:                     }
1.645     raeburn  3980:                 }
                   3981:             }
                   3982:             if (lc($tagname) eq 'link') {
                   3983:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3984:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3985:                 }
                   3986:             }
1.640     albertel 3987: 	    if (lc($tagname) eq 'object' ||
                   3988: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3989: 		foreach my $item (keys(%javafiles)) {
                   3990: 		    $javafiles{$item} = '';
                   3991: 		}
1.1164    raeburn  3992:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3993:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3994:                 }
1.640     albertel 3995: 	    }
                   3996: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3997: 		my $name = lc($attr->{'name'});
                   3998: 		foreach my $item (keys(%javafiles)) {
                   3999: 		    if ($name eq $item) {
                   4000: 			$javafiles{$item} = $attr->{'value'};
                   4001: 			last;
                   4002: 		    }
                   4003: 		}
1.1164    raeburn  4004:                 my $pathfrom;
1.640     albertel 4005: 		foreach my $item (keys(%mediafiles)) {
                   4006: 		    if ($name eq $item) {
1.1164    raeburn  4007:                         $pathfrom = $attr->{'value'};
                   4008:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   4009: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 4010: 			last;
                   4011: 		    }
                   4012: 		}
1.1164    raeburn  4013:                 if ($name eq 'flashvars') {
                   4014:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   4015:                 }
                   4016:                 if ($pathfrom ne '') {
                   4017:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   4018:                                          $pathfrom);
                   4019:                 }
1.640     albertel 4020: 	    }
                   4021: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   4022: 		foreach my $item (keys(%javafiles)) {
                   4023: 		    if ($attr->{$item}) {
                   4024: 			$javafiles{$item} = $attr->{$item};
                   4025: 			last;
                   4026: 		    }
                   4027: 		}
                   4028: 		foreach my $item (keys(%mediafiles)) {
                   4029: 		    if ($attr->{$item}) {
                   4030: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4031: 			last;
                   4032: 		    }
                   4033: 		}
1.1164    raeburn  4034:                 if (lc($tagname) eq 'embed') {
                   4035:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4036:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4037:                                              $attr->{'src'});
                   4038:                     }
                   4039:                 }
1.640     albertel 4040: 	    }
1.1172.2.35  raeburn  4041:             if (lc($tagname) eq 'iframe') {
                   4042:                 my $src = $attr->{'src'} ;
                   4043:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4044:                     &add_filetype($allfiles,$src,'src');
                   4045:                 } elsif ($src =~ m{^/}) {
                   4046:                     if ($env{'request.course.id'}) {
                   4047:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4048:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4049:                         my $url = &hreflocation('',$fullpath);
                   4050:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4051:                             my $relpath = $1;
                   4052:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4053:                                 &add_filetype($allfiles,$1,'src');
                   4054:                             }
                   4055:                         }
                   4056:                     }
                   4057:                 }
                   4058:             }
1.1164    raeburn  4059:             if ($t->[4] =~ m{/>$}) {
1.1172.2.35  raeburn  4060:                 pop(@state);
1.1164    raeburn  4061:             }
1.640     albertel 4062: 	} elsif ($t->[0] eq 'E') {
                   4063: 	    my ($tagname) = ($t->[1]);
                   4064: 	    if ($javafiles{'codebase'} ne '') {
                   4065: 		$javafiles{'codebase'} .= '/';
                   4066: 	    }  
                   4067: 	    if (lc($tagname) eq 'applet' ||
                   4068: 		lc($tagname) eq 'object' ||
                   4069: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4070: 		) {
                   4071: 		foreach my $item (keys(%javafiles)) {
                   4072: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4073: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4074: 			&add_filetype($allfiles,$file,$item);
                   4075: 		    }
                   4076: 		}
                   4077: 	    } 
                   4078: 	    pop @state;
                   4079: 	}
                   4080:     }
1.1164    raeburn  4081:     foreach my $id (sort(keys(%flashvars))) {
                   4082:         if ($shockwave{$id} ne '') {
                   4083:             my @pairs = split(/\&/,$flashvars{$id});
                   4084:             foreach my $pair (@pairs) {
                   4085:                 my ($key,$value) = split(/\=/,$pair);
                   4086:                 if ($key eq 'thumb') {
                   4087:                     &add_filetype($allfiles,$value,$key);
                   4088:                 } elsif ($key eq 'content') {
                   4089:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4090:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4091:                     if ($ext ne '') {
                   4092:                         &add_filetype($allfiles,$path.$value,$ext);
                   4093:                     }
                   4094:                 }
                   4095:             }
                   4096:         }
                   4097:     }
1.637     raeburn  4098:     return 'ok';
                   4099: }
                   4100: 
1.639     albertel 4101: sub add_filetype {
                   4102:     my ($allfiles,$file,$type)=@_;
                   4103:     if (exists($allfiles->{$file})) {
                   4104: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4105: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4106: 	}
                   4107:     } else {
                   4108: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4109:     }
                   4110: }
                   4111: 
1.1164    raeburn  4112: sub embedded_dependency {
                   4113:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4114:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4115:         if (($identifier ne '') &&
                   4116:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4117:             ($pathfrom ne '')) {
                   4118:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4119:             foreach my $dep (@{$related->{$identifier}}) {
                   4120:                 &add_filetype($allfiles,$path.$dep,'object');
                   4121:             }
                   4122:         }
                   4123:     }
                   4124:     return;
                   4125: }
                   4126: 
1.1172.2.109  raeburn  4127: sub bubblesheet_converter {
                   4128:     my ($cdom,$fullpath,$config,$format) = @_;
                   4129:     if ((&domain($cdom) ne '') &&
                   4130:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
                   4131:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
                   4132:         my (%csvcols,%csvoptions);
                   4133:         if (ref($config->{'fields'}) eq 'HASH') {
                   4134:             %csvcols = %{$config->{'fields'}};
                   4135:         }
                   4136:         if (ref($config->{'options'}) eq 'HASH') {
                   4137:             %csvoptions = %{$config->{'options'}};
                   4138:         }
                   4139:         my %csvbynum = reverse(%csvcols);
                   4140:         my %scantronconf = &get_scantron_config($format,$cdom);
                   4141:         if (keys(%scantronconf)) {
                   4142:             my %bynum = (
                   4143:                           $scantronconf{CODEstart} => 'CODEstart',
                   4144:                           $scantronconf{IDstart}   => 'IDstart',
                   4145:                           $scantronconf{PaperID}   => 'PaperID',
                   4146:                           $scantronconf{FirstName} => 'FirstName',
                   4147:                           $scantronconf{LastName}  => 'LastName',
                   4148:                           $scantronconf{Qstart}    => 'Qstart',
                   4149:                         );
                   4150:             my @ordered;
                   4151:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
                   4152:                 push(@ordered,$bynum{$item});
                   4153:             }
                   4154:             my %mapstart = (
                   4155:                               CODEstart => 'CODE',
                   4156:                               IDstart   => 'ID',
                   4157:                               PaperID   => 'PaperID',
                   4158:                               FirstName => 'FirstName',
                   4159:                               LastName  => 'LastName',
                   4160:                               Qstart    => 'FirstQuestion',
                   4161:                            );
                   4162:             my %maplength = (
                   4163:                               CODEstart => 'CODElength',
                   4164:                               IDstart   => 'IDlength',
                   4165:                               PaperID   => 'PaperIDlength',
                   4166:                               FirstName => 'FirstNamelength',
                   4167:                               LastName  => 'LastNamelength',
                   4168:             );
                   4169:             if (open(my $fh,'<',$fullpath)) {
                   4170:                 my $output;
                   4171:                 my %lettdig = &letter_to_digits();
                   4172:                 my %diglett = reverse(%lettdig);
                   4173:                 my $numletts = scalar(keys(%lettdig));
                   4174:                 my $num = 0;
                   4175:                 while (my $line=<$fh>) {
                   4176:                     $num ++;
                   4177:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
                   4178:                     $line =~ s{[\r\n]+$}{};
                   4179:                     my %found;
                   4180:                     my @values = split(/,/,$line);
                   4181:                     my ($qstart,$record);
                   4182:                     for (my $i=0; $i<@values; $i++) {
                   4183:                         if ((($qstart ne '') && ($i > $qstart)) ||
                   4184:                             ($csvbynum{$i} eq 'FirstQuestion')) {
                   4185:                             if ($values[$i] eq '') {
                   4186:                                 $values[$i] = $scantronconf{'Qoff'};
                   4187:                             } elsif ($scantronconf{'Qon'} eq 'number') {
                   4188:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4189:                                     $values[$i] = $lettdig{uc($values[$i])};
                   4190:                                 }
                   4191:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
                   4192:                                 if ($values[$i] =~ /^[0-9]$/) {
                   4193:                                     $values[$i] = $diglett{$values[$i]};
                   4194:                                 }
                   4195:                             } else {
                   4196:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
                   4197:                                     my $digit;
                   4198:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4199:                                         $digit = $lettdig{uc($values[$i])}-1;
                   4200:                                         if ($values[$i] eq 'J') {
                   4201:                                             $digit += $numletts;
                   4202:                                         }
                   4203:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
                   4204:                                         $digit = $values[$i]-1;
                   4205:                                         if ($values[$i] eq '0') {
                   4206:                                             $digit += $numletts;
                   4207:                                         }
                   4208:                                     }
                   4209:                                     my $qval='';
                   4210:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
                   4211:                                         if ($j == $digit) {
                   4212:                                             $qval .= $scantronconf{'Qon'};
                   4213:                                         } else {
                   4214:                                             $qval .= $scantronconf{'Qoff'};
                   4215:                                         }
                   4216:                                     }
                   4217:                                     $values[$i] = $qval;
                   4218:                                 }
                   4219:                             }
                   4220:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
                   4221:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
                   4222:                             }
                   4223:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
                   4224:                             if ($numblank > 0) {
                   4225:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
                   4226:                             }
                   4227:                             if ($csvbynum{$i} eq 'FirstQuestion') {
                   4228:                                 $qstart = $i;
                   4229:                                 $found{$csvbynum{$i}} = $values[$i];
                   4230:                             } else {
                   4231:                                 $found{'FirstQuestion'} .= $values[$i];
                   4232:                             }
                   4233:                         } elsif (exists($csvbynum{$i})) {
                   4234:                             if ($csvoptions{'rem'}) {
                   4235:                                 $values[$i] =~ s/^\s+//;
                   4236:                             }
                   4237:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
                   4238:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
                   4239:                                     $values[$i] = '0'.$values[$i];
                   4240:                                 }
                   4241:                             }
                   4242:                             $found{$csvbynum{$i}} = $values[$i];
                   4243:                         }
                   4244:                     }
                   4245:                     foreach my $item (@ordered) {
                   4246:                         my $currlength = 1+length($record);
                   4247:                         my $numspaces = $scantronconf{$item} - $currlength;
                   4248:                         if ($numspaces > 0) {
                   4249:                             $record .= (' ' x $numspaces);
                   4250:                         }
                   4251:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
                   4252:                             unless ($item eq 'Qstart') {
                   4253:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
                   4254:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
                   4255:                                 }
                   4256:                             }
                   4257:                             $record .= $found{$mapstart{$item}};
                   4258:                         }
                   4259:                     }
                   4260:                     $output .= "$record\n";
                   4261:                 }
                   4262:                 close($fh);
                   4263:                 if ($output) {
                   4264:                     if (open(my $fh,'>',$fullpath)) {
                   4265:                         print $fh $output;
                   4266:                         close($fh);
                   4267:                     }
                   4268:                 }
                   4269:             }
                   4270:         }
                   4271:         return;
                   4272:     }
                   4273: }
                   4274: 
                   4275: sub letter_to_digits {
                   4276:     my %lettdig = (
                   4277:                     A => 1,
                   4278:                     B => 2,
                   4279:                     C => 3,
                   4280:                     D => 4,
                   4281:                     E => 5,
                   4282:                     F => 6,
                   4283:                     G => 7,
                   4284:                     H => 8,
                   4285:                     I => 9,
                   4286:                     J => 0,
                   4287:                   );
                   4288:     return %lettdig;
                   4289: }
                   4290: 
                   4291: sub get_scantron_config {
                   4292:     my ($which,$cdom) = @_;
                   4293:     my @lines = &get_scantronformat_file($cdom);
                   4294:     my %config;
                   4295:     #FIXME probably should move to XML it has already gotten a bit much now
                   4296:     foreach my $line (@lines) {
                   4297:         my ($name,$descrip)=split(/:/,$line);
                   4298:         if ($name ne $which ) { next; }
                   4299:         chomp($line);
                   4300:         my @config=split(/:/,$line);
                   4301:         $config{'name'}=$config[0];
                   4302:         $config{'description'}=$config[1];
                   4303:         $config{'CODElocation'}=$config[2];
                   4304:         $config{'CODEstart'}=$config[3];
                   4305:         $config{'CODElength'}=$config[4];
                   4306:         $config{'IDstart'}=$config[5];
                   4307:         $config{'IDlength'}=$config[6];
                   4308:         $config{'Qstart'}=$config[7];
                   4309:         $config{'Qlength'}=$config[8];
                   4310:         $config{'Qoff'}=$config[9];
                   4311:         $config{'Qon'}=$config[10];
                   4312:         $config{'PaperID'}=$config[11];
                   4313:         $config{'PaperIDlength'}=$config[12];
                   4314:         $config{'FirstName'}=$config[13];
                   4315:         $config{'FirstNamelength'}=$config[14];
                   4316:         $config{'LastName'}=$config[15];
                   4317:         $config{'LastNamelength'}=$config[16];
                   4318:         $config{'BubblesPerRow'}=$config[17];
                   4319:         last;
                   4320:     }
                   4321:     return %config;
                   4322: }
                   4323: 
                   4324: sub get_scantronformat_file {
                   4325:     my ($cdom) = @_;
                   4326:     if ($cdom eq '') {
                   4327:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4328:     }
                   4329:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
                   4330:     my $gottab = 0;
                   4331:     my @lines;
                   4332:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   4333:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   4334:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   4335:             if ($formatfile ne '-1') {
                   4336:                 @lines = split("\n",$formatfile,-1);
                   4337:                 $gottab = 1;
                   4338:             }
                   4339:         }
                   4340:     }
                   4341:     if (!$gottab) {
                   4342:         my $confname = $cdom.'-domainconfig';
                   4343:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   4344:         my $formatfile = &getfile($default);
                   4345:         if ($formatfile ne '-1') {
                   4346:             @lines = split("\n",$formatfile,-1);
                   4347:             $gottab = 1;
                   4348:         }
                   4349:     }
                   4350:     if (!$gottab) {
                   4351:         my @domains = &current_machine_domains();
                   4352:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   4353:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
                   4354:                 @lines = <$fh>;
                   4355:                 close($fh);
                   4356:             }
                   4357:         } else {
                   4358:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
                   4359:                 @lines = <$fh>;
                   4360:                 close($fh);
                   4361:             }
                   4362:         }
                   4363:     }
                   4364:     return @lines;
                   4365: }
                   4366: 
1.493     albertel 4367: sub removeuploadedurl {
1.984     neumanie 4368:     my ($url)=@_;	
                   4369:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4370:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4371: }
                   4372: 
                   4373: sub removeuserfile {
                   4374:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4375:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4376:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4377:     if ($result eq 'ok') {	
1.798     raeburn  4378:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4379:             my $metafile = $fname.'.meta';
                   4380:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4381: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4382:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4383:             my $sqlresult = 
1.823     albertel 4384:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4385:                                         'portfolio_metadata',$group,
                   4386:                                         'delete');
1.798     raeburn  4387:         }
                   4388:     }
                   4389:     return $result;
1.257     www      4390: }
1.15      www      4391: 
1.530     albertel 4392: sub mkdiruserfile {
                   4393:     my ($docuname,$docudom,$dir)=@_;
                   4394:     my $home=&homeserver($docuname,$docudom);
                   4395:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4396: }
                   4397: 
1.531     albertel 4398: sub renameuserfile {
                   4399:     my ($docuname,$docudom,$old,$new)=@_;
                   4400:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4401:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4402:                         &escape("$old").':'.&escape("$new"),$home);
                   4403:     if ($result eq 'ok') {
                   4404:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4405:             my $oldmeta = $old.'.meta';
                   4406:             my $newmeta = $new.'.meta';
                   4407:             my $metaresult = 
                   4408:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4409: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4410:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4411:             my $sqlresult = 
1.823     albertel 4412:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4413:                                         'portfolio_metadata',$group,
                   4414:                                         'delete');
1.798     raeburn  4415:         }
                   4416:     }
                   4417:     return $result;
1.531     albertel 4418: }
                   4419: 
1.14      www      4420: # ------------------------------------------------------------------------- Log
                   4421: 
                   4422: sub log {
                   4423:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4424:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4425: }
                   4426: 
                   4427: # ------------------------------------------------------------------ Course Log
1.352     www      4428: #
                   4429: # This routine flushes several buffers of non-mission-critical nature
                   4430: #
1.157     www      4431: 
                   4432: sub flushcourselogs {
1.352     www      4433:     &logthis('Flushing log buffers');
                   4434: #
                   4435: # course logs
                   4436: # This is a log of all transactions in a course, which can be used
                   4437: # for data mining purposes
                   4438: #
                   4439: # It also collects the courseid database, which lists last transaction
                   4440: # times and course titles for all courseids
                   4441: #
                   4442:     my %courseidbuffer=();
1.921     raeburn  4443:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4444:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4445: 		          &escape($courselogs{$crsid}),
                   4446: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4447: 	    delete $courselogs{$crsid};
                   4448:         } else {
                   4449:             &logthis('Failed to flush log buffer for '.$crsid);
                   4450:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4451:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4452:                         " exceeded maximum size, deleting.</font>");
                   4453:                delete $courselogs{$crsid};
                   4454:             }
1.352     www      4455:         }
1.920     raeburn  4456:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4457:             'description' => $coursedescrbuf{$crsid},
                   4458:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4459:             'type'        => $coursetypebuf{$crsid},
                   4460:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4461:         };
1.191     harris41 4462:     }
1.352     www      4463: #
                   4464: # Write course id database (reverse lookup) to homeserver of courses 
                   4465: # Is used in pickcourse
                   4466: #
1.840     albertel 4467:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4468:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4469:                                     $courseidbuffer{$crs_home},
                   4470:                                     $crs_home,'timeonly');
1.352     www      4471:     }
                   4472: #
                   4473: # File accesses
                   4474: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4475: #
1.449     matthew  4476:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4477:         if ($entry =~ /___count$/) {
                   4478:             my ($dom,$name);
1.807     albertel 4479:             ($dom,$name,undef)=
1.811     albertel 4480: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4481:             if (! defined($dom) || $dom eq '' || 
                   4482:                 ! defined($name) || $name eq '') {
1.620     albertel 4483:                 my $cid = $env{'request.course.id'};
                   4484:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4485:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4486:             }
1.450     matthew  4487:             my $value = $accesshash{$entry};
                   4488:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4489:             my %temphash=($url => $value);
1.449     matthew  4490:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4491:             if ($result eq 'ok') {
                   4492:                 delete $accesshash{$entry};
                   4493:             }
                   4494:         } else {
1.811     albertel 4495:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4496:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4497:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4498:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4499:                 delete $accesshash{$entry};
                   4500:             }
1.185     www      4501:         }
1.191     harris41 4502:     }
1.352     www      4503: #
                   4504: # Roles
                   4505: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4506: #
1.800     albertel 4507:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4508:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4509: 	    split(/\:/,$entry);
                   4510:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4511:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4512:                 $rudom,$runame) eq 'ok') {
                   4513: 	    delete $userrolehash{$entry};
                   4514:         }
                   4515:     }
1.662     raeburn  4516: #
1.1172.2.90  raeburn  4517: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4518: #
                   4519:     my %domrolebuffer = ();
1.1000    raeburn  4520:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4521:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4522:         if ($domrolebuffer{$rudom}) {
                   4523:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4524:                       '='.&escape($domainrolehash{$entry});
                   4525:         } else {
                   4526:             $domrolebuffer{$rudom}.=&escape($entry).
                   4527:                       '='.&escape($domainrolehash{$entry});
                   4528:         }
                   4529:         delete $domainrolehash{$entry};
                   4530:     }
                   4531:     foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82  raeburn  4532:         my %servers;
                   4533:         if (defined(&domain($dom,'primary'))) {
                   4534:             my $primary=&domain($dom,'primary');
                   4535:             my $hostname=&hostname($primary);
                   4536:             $servers{$primary} = $hostname;
                   4537:         } else {
                   4538:             %servers = &get_servers($dom,'library');
                   4539:         }
1.841     albertel 4540: 	foreach my $tryserver (keys(%servers)) {
1.1172.2.82  raeburn  4541: 	    if (&reply('domroleput:'.$dom.':'.
                   4542: 	               $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4543: 	        last;
                   4544: 	    } else {
1.841     albertel 4545: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4546: 	    }
1.662     raeburn  4547:         }
                   4548:     }
1.186     www      4549:     $dumpcount++;
1.157     www      4550: }
                   4551: 
                   4552: sub courselog {
                   4553:     my $what=shift;
1.158     www      4554:     $what=time.':'.$what;
1.620     albertel 4555:     unless ($env{'request.course.id'}) { return ''; }
                   4556:     $coursedombuf{$env{'request.course.id'}}=
                   4557:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4558:     $coursenumbuf{$env{'request.course.id'}}=
                   4559:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4560:     $coursehombuf{$env{'request.course.id'}}=
                   4561:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4562:     $coursedescrbuf{$env{'request.course.id'}}=
                   4563:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4564:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4565:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4566:     $courseownerbuf{$env{'request.course.id'}}=
                   4567:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4568:     $coursetypebuf{$env{'request.course.id'}}=
                   4569:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4570:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4571: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4572:     } else {
1.620     albertel 4573: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4574:     }
1.620     albertel 4575:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4576: 	&flushcourselogs();
                   4577:     }
1.158     www      4578: }
                   4579: 
                   4580: sub courseacclog {
                   4581:     my $fnsymb=shift;
1.620     albertel 4582:     unless ($env{'request.course.id'}) { return ''; }
                   4583:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4584:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4585:         $what.=':POST';
1.583     matthew  4586:         # FIXME: Probably ought to escape things....
1.800     albertel 4587: 	foreach my $key (keys(%env)) {
                   4588:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4589:                 my $formitem = $1;
                   4590:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4591:                     $what.=':'.$formitem.'='.$env{$key};
                   4592:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   4593:                     $what.=':'.$formitem.'='.$env{$key};
                   4594:                 }
1.158     www      4595:             }
1.191     harris41 4596:         }
1.583     matthew  4597:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4598:         # FIXME: We should not be depending on a form parameter that someone
                   4599:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4600:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4601:             $what.= ':POST';
                   4602:             # FIXME: Probably ought to escape things....
                   4603:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4604:                                  'crsdiscuss') {
1.620     albertel 4605:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4606:             }
                   4607:         }
1.158     www      4608:     }
                   4609:     &courselog($what);
1.149     www      4610: }
                   4611: 
1.185     www      4612: sub countacc {
                   4613:     my $url=&declutter(shift);
1.458     matthew  4614:     return if (! defined($url) || $url eq '');
1.620     albertel 4615:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4616: #
                   4617: # Mark that this url was used in this course
                   4618: #
1.620     albertel 4619:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4620: #
                   4621: # Increase the access count for this resource in this child process
                   4622: #
1.281     www      4623:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4624:     $accesshash{$key}++;
1.185     www      4625: }
1.349     www      4626: 
1.361     www      4627: sub linklog {
                   4628:     my ($from,$to)=@_;
                   4629:     $from=&declutter($from);
                   4630:     $to=&declutter($to);
                   4631:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4632:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4633: }
1.1160    www      4634: 
                   4635: sub statslog {
                   4636:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4637:     if ($users<2) { return; }
                   4638:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4639:             'course'       => $env{'request.course.id'},
                   4640:             'sections'     => '"all"',
                   4641:             'num_students' => $users,
                   4642:             'part'         => $part,
                   4643:             'symb'         => $symb,
                   4644:             'mean_tries'   => $av_attempts,
                   4645:             'deg_of_diff'  => $degdiff});
                   4646:     foreach my $key (keys(%dynstore)) {
                   4647:         $accesshash{$key}=$dynstore{$key};
                   4648:     }
                   4649: }
1.361     www      4650:   
1.349     www      4651: sub userrolelog {
                   4652:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4653:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4654:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4655:        $userrolehash
                   4656:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4657:                     =$tend.':'.$tstart;
1.662     raeburn  4658:     }
1.1169    droeschl 4659:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4660:        $userrolehash
                   4661:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4662:                     =$tend.':'.$tstart;
                   4663:     }
1.1172.2.90  raeburn  4664:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4665:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4666:        $domainrolehash
                   4667:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4668:                     = $tend.':'.$tstart;
                   4669:     }
1.351     www      4670: }
                   4671: 
1.957     raeburn  4672: sub courserolelog {
                   4673:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  4674:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4675:         my $cdom = $1;
                   4676:         my $cnum = $2;
                   4677:         my $sec = $3;
                   4678:         my $namespace = 'rolelog';
                   4679:         my %storehash = (
                   4680:                            role    => $trole,
                   4681:                            start   => $tstart,
                   4682:                            end     => $tend,
                   4683:                            selfenroll => $selfenroll,
                   4684:                            context    => $context,
                   4685:                         );
                   4686:         if ($trole eq 'gr') {
                   4687:             $namespace = 'groupslog';
                   4688:             $storehash{'group'} = $sec;
                   4689:         } else {
                   4690:             $storehash{'section'} = $sec;
                   4691:         }
                   4692:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4693:                    $domain,$cnum,$cdom);
                   4694:         if (($trole ne 'st') || ($sec ne '')) {
                   4695:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4696:         }
                   4697:     }
                   4698:     return;
                   4699: }
                   4700: 
1.1172.2.9  raeburn  4701: sub domainrolelog {
                   4702:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4703:     if ($area =~ m{^/($match_domain)/$}) {
                   4704:         my $cdom = $1;
                   4705:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4706:         my $namespace = 'rolelog';
                   4707:         my %storehash = (
                   4708:                            role    => $trole,
                   4709:                            start   => $tstart,
                   4710:                            end     => $tend,
                   4711:                            context => $context,
                   4712:                         );
                   4713:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4714:                    $domain,$domconfiguser,$cdom);
                   4715:     }
                   4716:     return;
                   4717: 
                   4718: }
                   4719: 
                   4720: sub coauthorrolelog {
                   4721:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4722:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4723:         my $audom = $1;
                   4724:         my $auname = $2;
                   4725:         my $namespace = 'rolelog';
                   4726:         my %storehash = (
                   4727:                            role    => $trole,
                   4728:                            start   => $tstart,
                   4729:                            end     => $tend,
                   4730:                            context => $context,
                   4731:                         );
                   4732:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4733:                    $domain,$auname,$audom);
                   4734:     }
                   4735:     return;
                   4736: }
                   4737: 
1.351     www      4738: sub get_course_adv_roles {
1.948     raeburn  4739:     my ($cid,$codes) = @_;
1.620     albertel 4740:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4741:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4742:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4743:     my %nothide=();
1.800     albertel 4744:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4745:         if ($user !~ /:/) {
                   4746: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4747:         } else {
                   4748:             $nothide{$user}=1;
                   4749:         }
1.470     www      4750:     }
1.1172.2.23  raeburn  4751:     my @possdoms = ($coursehash{'domain'});
                   4752:     if ($coursehash{'checkforpriv'}) {
                   4753:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4754:     }
1.351     www      4755:     my %returnhash=();
                   4756:     my %dumphash=
                   4757:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4758:     my $now=time;
1.997     raeburn  4759:     my %privileged;
1.1000    raeburn  4760:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4761: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4762:         if (($tstart) && ($tstart<0)) { next; }
                   4763:         if (($tend) && ($tend<$now)) { next; }
                   4764:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4765:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4766: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  4767:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4768:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4769: 	if ($role eq 'cr') { next; }
1.948     raeburn  4770:         if ($codes) {
                   4771:             if ($section) { $role .= ':'.$section; }
                   4772:             if ($returnhash{$role}) {
                   4773:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4774:             } else {
                   4775:                 $returnhash{$role}=$username.':'.$domain;
                   4776:             }
1.351     www      4777:         } else {
1.988     raeburn  4778:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4779:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4780:             if ($returnhash{$key}) {
                   4781: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4782:             } else {
                   4783:                 $returnhash{$key}=$username.':'.$domain;
                   4784:             }
1.351     www      4785:         }
1.948     raeburn  4786:     }
1.400     www      4787:     return %returnhash;
                   4788: }
                   4789: 
                   4790: sub get_my_roles {
1.937     raeburn  4791:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4792:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4793:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4794:     my (%dumphash,%nothide);
1.1086    raeburn  4795:     if ($context eq 'userroles') {
1.1166    raeburn  4796:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4797:     } else {
1.1172.2.23  raeburn  4798:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4799:         if ($hidepriv) {
                   4800:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4801:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4802:                 if ($user !~ /:/) {
                   4803:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4804:                 } else {
                   4805:                     $nothide{$user} = 1;
                   4806:                 }
                   4807:             }
                   4808:         }
1.858     raeburn  4809:     }
1.400     www      4810:     my %returnhash=();
                   4811:     my $now=time;
1.999     raeburn  4812:     my %privileged;
1.800     albertel 4813:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4814:         my ($role,$tend,$tstart);
                   4815:         if ($context eq 'userroles') {
1.1149    raeburn  4816:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4817: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4818:         } else {
                   4819:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4820:         }
1.400     www      4821:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4822:         my $status = 'active';
1.939     raeburn  4823:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4824:             $status = 'previous';
                   4825:         } 
                   4826:         if (($tstart) && ($now<$tstart)) {
                   4827:             $status = 'future';
                   4828:         }
                   4829:         if (ref($types) eq 'ARRAY') {
                   4830:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4831:                 next;
                   4832:             } 
                   4833:         } else {
                   4834:             if ($status ne 'active') {
                   4835:                 next;
                   4836:             }
                   4837:         }
1.867     raeburn  4838:         my ($rolecode,$username,$domain,$section,$area);
                   4839:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  4840:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4841:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4842:         } else {
                   4843:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4844:         }
1.832     raeburn  4845:         if (ref($roledoms) eq 'ARRAY') {
                   4846:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4847:                 next;
                   4848:             }
                   4849:         }
                   4850:         if (ref($roles) eq 'ARRAY') {
                   4851:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4852:                 if ($role =~ /^cr\//) {
                   4853:                     if (!grep(/^cr$/,@{$roles})) {
                   4854:                         next;
                   4855:                     }
1.1104    raeburn  4856:                 } elsif ($role =~ /^gr\//) {
                   4857:                     if (!grep(/^gr$/,@{$roles})) {
                   4858:                         next;
                   4859:                     }
1.922     raeburn  4860:                 } else {
                   4861:                     next;
                   4862:                 }
1.832     raeburn  4863:             }
1.867     raeburn  4864:         }
1.937     raeburn  4865:         if ($hidepriv) {
1.1172.2.23  raeburn  4866:             my @privroles = ('dc','su');
1.999     raeburn  4867:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  4868:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4869:             } else {
1.1172.2.23  raeburn  4870:                 my $possdoms = [$domain];
                   4871:                 if (ref($roledoms) eq 'ARRAY') {
                   4872:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  4873:                 }
1.1172.2.23  raeburn  4874:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4875:                     if (!$nothide{$username.':'.$domain}) {
                   4876:                         next;
                   4877:                     }
                   4878:                 }
1.937     raeburn  4879:             }
                   4880:         }
1.933     raeburn  4881:         if ($withsec) {
                   4882:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4883:                 $tstart.':'.$tend;
                   4884:         } else {
                   4885:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4886:         }
1.832     raeburn  4887:     }
1.373     www      4888:     return %returnhash;
1.399     www      4889: }
                   4890: 
1.1172.2.89  raeburn  4891: sub get_all_adhocroles {
                   4892:     my ($dom) = @_;
                   4893:     my @roles_by_num = ();
                   4894:     my %domdefaults = &get_domain_defaults($dom);
                   4895:     my (%description,%access_in_dom,%access_info);
                   4896:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   4897:         my $count = 0;
                   4898:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   4899:         my %ordered;
                   4900:         foreach my $role (sort(keys(%domcurrent))) {
                   4901:             my ($order,$desc,$access_in_dom);
                   4902:             if (ref($domcurrent{$role}) eq 'HASH') {
                   4903:                 $order = $domcurrent{$role}{'order'};
                   4904:                 $desc = $domcurrent{$role}{'desc'};
                   4905:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   4906:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   4907:             }
                   4908:             if ($order eq '') {
                   4909:                 $order = $count;
                   4910:             }
                   4911:             $ordered{$order} = $role;
                   4912:             if ($desc ne '') {
                   4913:                 $description{$role} = $desc;
                   4914:             } else {
                   4915:                 $description{$role}= $role;
                   4916:             }
                   4917:             $count++;
                   4918:         }
                   4919:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   4920:             push(@roles_by_num,$ordered{$item});
                   4921:         }
                   4922:     }
                   4923:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   4924: }
                   4925: 
                   4926: sub get_my_adhocroles {
                   4927:     my ($cid,$checkreg) = @_;
                   4928:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   4929:     if ($env{'request.course.id'} eq $cid) {
                   4930:         $cdom = $env{'course.'.$cid.'.domain'};
                   4931:         $cnum = $env{'course.'.$cid.'.num'};
                   4932:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   4933:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   4934:         $cdom = $1;
                   4935:         $cnum = $2;
                   4936:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   4937:                                      $cdom,$cnum);
                   4938:     }
                   4939:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   4940:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   4941:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   4942:         if ($rosterhash{$user} ne '') {
                   4943:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   4944:             return ([],{}) if ($type eq 'auto');
                   4945:         }
                   4946:     }
                   4947:     if (($cdom ne '') && ($cnum ne ''))  {
1.1172.2.90  raeburn  4948:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89  raeburn  4949:             my $then=$env{'user.login.time'};
                   4950:             my $update=$env{'user.update.time'};
1.1172.2.90  raeburn  4951:             if (!$update) {
                   4952:                 $update = $then;
                   4953:             }
                   4954:             my @liveroles;
                   4955:             foreach my $role ('dh','da') {
                   4956:                 if ($env{"user.role.$role./$cdom/"}) {
                   4957:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
                   4958:                     my $limit = $update;
                   4959:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   4960:                         $limit = $then;
                   4961:                     }
                   4962:                     my $activerole = 1;
                   4963:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   4964:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   4965:                     if ($activerole) {
                   4966:                         push(@liveroles,$role);
                   4967:                     }
                   4968:                 }
                   4969:             }
                   4970:             if (@liveroles) {
1.1172.2.89  raeburn  4971:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
                   4972:                     my ($accessref,$accessinfo,%access_in_dom);
                   4973:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   4974:                     if (ref($roles_by_num) eq 'ARRAY') {
                   4975:                         if (@{$roles_by_num}) {
                   4976:                             my %settings;
                   4977:                             if ($env{'request.course.id'} eq $cid) {
                   4978:                                 foreach my $envkey (keys(%env)) {
                   4979:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   4980:                                         $settings{$1} = $env{$envkey};
                   4981:                                     }
                   4982:                                 }
                   4983:                             } else {
                   4984:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   4985:                             }
                   4986:                             my %setincrs;
                   4987:                             if ($settings{'internal.adhocaccess'}) {
                   4988:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   4989:                             }
                   4990:                             my @statuses;
                   4991:                             if ($env{'environment.inststatus'}) {
                   4992:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   4993:                             }
                   4994:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   4995:                             if (ref($accessref) eq 'HASH') {
                   4996:                                 %access_in_dom = %{$accessref};
                   4997:                             }
                   4998:                             foreach my $role (@{$roles_by_num}) {
                   4999:                                 my ($curraccess,@okstatus,@personnel);
                   5000:                                 if ($setincrs{$role}) {
                   5001:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   5002:                                     if ($curraccess eq 'status') {
                   5003:                                         @okstatus = split(/\&/,$rest);
                   5004:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5005:                                         @personnel = split(/\&/,$rest);
                   5006:                                     }
                   5007:                                 } else {
                   5008:                                     $curraccess = $access_in_dom{$role};
                   5009:                                     if (ref($accessinfo) eq 'HASH') {
                   5010:                                         if ($curraccess eq 'status') {
                   5011:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5012:                                                 @okstatus = @{$accessinfo->{$role}};
                   5013:                                             }
                   5014:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5015:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5016:                                                 @personnel = @{$accessinfo->{$role}};
                   5017:                                             }
                   5018:                                         }
                   5019:                                     }
                   5020:                                 }
                   5021:                                 if ($curraccess eq 'none') {
                   5022:                                     next;
                   5023:                                 } elsif ($curraccess eq 'all') {
                   5024:                                     push(@possroles,$role);
1.1172.2.90  raeburn  5025:                                 } elsif ($curraccess eq 'dh') {
                   5026:                                     if (grep(/^dh$/,@liveroles)) {
                   5027:                                         push(@possroles,$role);
                   5028:                                     } else {
                   5029:                                         next;
                   5030:                                     }
                   5031:                                 } elsif ($curraccess eq 'da') {
                   5032:                                     if (grep(/^da$/,@liveroles)) {
                   5033:                                         push(@possroles,$role);
                   5034:                                     } else {
                   5035:                                         next;
                   5036:                                     }
1.1172.2.89  raeburn  5037:                                 } elsif ($curraccess eq 'status') {
                   5038:                                     if (@okstatus) {
                   5039:                                         if (!@statuses) {
                   5040:                                             if (grep(/^default$/,@okstatus)) {
                   5041:                                                 push(@possroles,$role);
                   5042:                                             }
                   5043:                                         } else {
                   5044:                                             foreach my $status (@okstatus) {
                   5045:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   5046:                                                     push(@possroles,$role);
                   5047:                                                     last;
                   5048:                                                 }
                   5049:                                             }
                   5050:                                         }
                   5051:                                     }
                   5052:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5053:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   5054:                                         if ($curraccess eq 'exc') {
                   5055:                                             push(@possroles,$role);
                   5056:                                         }
                   5057:                                     } elsif ($curraccess eq 'inc') {
                   5058:                                         push(@possroles,$role);
                   5059:                                     }
                   5060:                                 }
                   5061:                             }
                   5062:                         }
                   5063:                     }
                   5064:                 }
                   5065:             }
                   5066:         }
                   5067:     }
                   5068:     unless (ref($description) eq 'HASH') {
                   5069:         if (ref($roles_by_num) eq 'ARRAY') {
                   5070:             my %desc;
                   5071:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   5072:             $description = \%desc;
                   5073:         } else {
                   5074:             $description = {};
                   5075:         }
                   5076:     }
                   5077:     return (\@possroles,$description);
                   5078: }
                   5079: 
1.399     www      5080: # ----------------------------------------------------- Frontpage Announcements
                   5081: #
                   5082: #
                   5083: 
                   5084: sub postannounce {
                   5085:     my ($server,$text)=@_;
1.844     albertel 5086:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      5087:     unless ($text=~/\w/) { $text=''; }
                   5088:     return &reply('setannounce:'.&escape($text),$server);
                   5089: }
                   5090: 
                   5091: sub getannounce {
1.448     albertel 5092: 
1.1172.2.96  raeburn  5093:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      5094: 	my $announcement='';
1.800     albertel 5095: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 5096: 	close($fh);
1.399     www      5097: 	if ($announcement=~/\w/) { 
                   5098: 	    return 
                   5099:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 5100:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      5101: 	} else {
                   5102: 	    return '';
                   5103: 	}
                   5104:     } else {
                   5105: 	return '';
                   5106:     }
1.351     www      5107: }
1.353     www      5108: 
                   5109: # ---------------------------------------------------------- Course ID routines
                   5110: # Deal with domain's nohist_courseid.db files
                   5111: #
                   5112: 
                   5113: sub courseidput {
1.921     raeburn  5114:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  5115:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  5116:     my $outcome;
                   5117:     if ($caller eq 'timeonly') {
                   5118:         my $cids = '';
                   5119:         foreach my $item (keys(%$storehash)) {
                   5120:             $cids.=&escape($item).'&';
                   5121:         }
                   5122:         $cids=~s/\&$//;
                   5123:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   5124:                           $coursehome);       
                   5125:     } else {
                   5126:         my $items = '';
                   5127:         foreach my $item (keys(%$storehash)) {
                   5128:             $items.= &escape($item).'='.
                   5129:                      &freeze_escape($$storehash{$item}).'&';
                   5130:         }
                   5131:         $items=~s/\&$//;
                   5132:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   5133:                           $coursehome);
1.918     raeburn  5134:     }
                   5135:     if ($outcome eq 'unknown_cmd') {
                   5136:         my $what;
                   5137:         foreach my $cid (keys(%$storehash)) {
                   5138:             $what .= &escape($cid).'=';
1.921     raeburn  5139:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  5140:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  5141:             }
                   5142:             $what =~ s/\:$/&/;
                   5143:         }
                   5144:         $what =~ s/\&$//;  
                   5145:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   5146:     } else {
                   5147:         return $outcome;
                   5148:     }
1.353     www      5149: }
                   5150: 
                   5151: sub courseiddump {
1.921     raeburn  5152:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  5153:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  5154:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38  raeburn  5155:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68  raeburn  5156:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  5157:     my $as_hash = 1;
                   5158:     my %returnhash;
                   5159:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 5160:     my %libserv = &all_library();
                   5161:     foreach my $tryserver (keys(%libserv)) {
                   5162:         if ( (  $hostidflag == 1 
                   5163: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5164: 	     || (!defined($hostidflag)) ) {
                   5165: 
1.918     raeburn  5166: 	    if (($domfilter eq '') ||
                   5167: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  5168:                 my $rep;
                   5169:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   5170:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   5171:                         join(":", (&host_domain($tryserver), $sincefilter,
                   5172:                                 &escape($descfilter), &escape($instcodefilter),
                   5173:                                 &escape($ownerfilter), &escape($coursefilter),
                   5174:                                 &escape($typefilter), &escape($regexp_ok),
                   5175:                                 $as_hash, &escape($selfenrollonly),
                   5176:                                 &escape($catfilter), $showhidden, $caller,
                   5177:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   5178:                                 &escape($createdbefore), &escape($createdafter),
1.1172.2.68  raeburn  5179:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5180:                                 $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22  raeburn  5181:                 } else {
                   5182:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5183:                              $sincefilter.':'.&escape($descfilter).':'.
                   5184:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5185:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5186:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5187:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5188:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5189:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5190:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68  raeburn  5191:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5192:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22  raeburn  5193:                 }
                   5194: 
1.918     raeburn  5195:                 my @pairs=split(/\&/,$rep);
                   5196:                 foreach my $item (@pairs) {
                   5197:                     my ($key,$value)=split(/\=/,$item,2);
                   5198:                     $key = &unescape($key);
                   5199:                     next if ($key =~ /^error: 2 /);
                   5200:                     my $result = &thaw_unescape($value);
                   5201:                     if (ref($result) eq 'HASH') {
                   5202:                         $returnhash{$key}=$result;
                   5203:                     } else {
1.921     raeburn  5204:                         my @responses = split(/:/,$value);
                   5205:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5206:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5207:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5208:                         }
1.1008    raeburn  5209:                     }
1.353     www      5210:                 }
                   5211:             }
                   5212:         }
                   5213:     }
                   5214:     return %returnhash;
                   5215: }
                   5216: 
1.1055    raeburn  5217: sub courselastaccess {
                   5218:     my ($cdom,$cnum,$hostidref) = @_;
                   5219:     my %returnhash;
                   5220:     if ($cdom && $cnum) {
                   5221:         my $chome = &homeserver($cnum,$cdom);
                   5222:         if ($chome ne 'no_host') {
                   5223:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5224:             &extract_lastaccess(\%returnhash,$rep);
                   5225:         }
                   5226:     } else {
                   5227:         if (!$cdom) { $cdom=''; }
                   5228:         my %libserv = &all_library();
                   5229:         foreach my $tryserver (keys(%libserv)) {
                   5230:             if (ref($hostidref) eq 'ARRAY') {
                   5231:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5232:             } 
                   5233:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5234:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5235:                 &extract_lastaccess(\%returnhash,$rep);
                   5236:             }
                   5237:         }
                   5238:     }
                   5239:     return %returnhash;
                   5240: }
                   5241: 
                   5242: sub extract_lastaccess {
                   5243:     my ($returnhash,$rep) = @_;
                   5244:     if (ref($returnhash) eq 'HASH') {
                   5245:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5246:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5247:                  $rep eq '') {
                   5248:             my @pairs=split(/\&/,$rep);
                   5249:             foreach my $item (@pairs) {
                   5250:                 my ($key,$value)=split(/\=/,$item,2);
                   5251:                 $key = &unescape($key);
                   5252:                 next if ($key =~ /^error: 2 /);
                   5253:                 $returnhash->{$key} = &thaw_unescape($value);
                   5254:             }
                   5255:         }
                   5256:     }
                   5257:     return;
                   5258: }
                   5259: 
1.658     raeburn  5260: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5261: 
                   5262: sub dcmailput {
1.685     raeburn  5263:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5264:     my $status = &Apache::lonnet::critical(
1.740     www      5265:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5266:        &escape($message),$server);
1.662     raeburn  5267:     return $status;
                   5268: }
                   5269: 
1.658     raeburn  5270: sub dcmaildump {
                   5271:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5272:     my %returnhash=();
1.846     albertel 5273: 
                   5274:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5275:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5276:                                                          &escape($enddate).':';
                   5277: 	my @esc_senders=map { &escape($_)} @$senders;
                   5278: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5279: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5280:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5281:             if (($key) && ($value)) {
                   5282:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5283:             }
                   5284:         }
                   5285:     }
                   5286:     return %returnhash;
                   5287: }
1.662     raeburn  5288: # ---------------------------------------------------------- Domain roles
                   5289: 
                   5290: sub get_domain_roles {
                   5291:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5292:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5293:         $startdate = '.';
                   5294:     }
1.1018    raeburn  5295:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5296:         $enddate = '.';
                   5297:     }
1.922     raeburn  5298:     my $rolelist;
                   5299:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  5300:         $rolelist = join('&',@{$roles});
1.922     raeburn  5301:     }
1.662     raeburn  5302:     my %personnel = ();
1.841     albertel 5303: 
                   5304:     my %servers = &get_servers($dom,'library');
                   5305:     foreach my $tryserver (keys(%servers)) {
                   5306: 	%{$personnel{$tryserver}}=();
                   5307: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5308: 					    &escape($startdate).':'.
                   5309: 					    &escape($enddate).':'.
                   5310: 					    &escape($rolelist), $tryserver))) {
                   5311: 	    my ($key,$value) = split(/\=/,$line,2);
                   5312: 	    if (($key) && ($value)) {
                   5313: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5314: 	    }
                   5315: 	}
1.662     raeburn  5316:     }
                   5317:     return %personnel;
                   5318: }
1.658     raeburn  5319: 
1.1172.2.89  raeburn  5320: sub get_active_domroles {
                   5321:     my ($dom,$roles) = @_;
                   5322:     return () unless (ref($roles) eq 'ARRAY');
                   5323:     my $now = time;
                   5324:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5325:     my %domroles;
                   5326:     foreach my $server (keys(%dompersonnel)) {
                   5327:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5328:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5329:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5330:         }
                   5331:     }
                   5332:     return %domroles;
                   5333: }
                   5334: 
1.1057    www      5335: # ----------------------------------------------------------- Interval timing 
1.149     www      5336: 
1.1153    www      5337: {
                   5338: # Caches needed for speedup of navmaps
                   5339: # We don't want to cache this for very long at all (5 seconds at most)
                   5340: # 
                   5341: # The user for whom we cache
                   5342: my $cachedkey='';
                   5343: # The cached times for this user
                   5344: my %cachedtimes=();
                   5345: # When this was last done
1.1172.2.66  raeburn  5346: my $cachedtime='';
1.1153    www      5347: 
                   5348: sub load_all_first_access {
1.1154    raeburn  5349:     my ($uname,$udom)=@_;
1.1156    www      5350:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2  raeburn  5351:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  5352:         return;
                   5353:     }
                   5354:     $cachedtime=time;
                   5355:     $cachedkey=$uname.':'.$udom;
                   5356:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5357: }
                   5358: 
1.504     albertel 5359: sub get_first_access {
1.1162    raeburn  5360:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 5361:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5362:     if ($argsymb) { $symb=$argsymb; }
                   5363:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5364:     if ($argmap) { $map = $argmap; }
1.926     albertel 5365:     if ($type eq 'course') {
                   5366: 	$res='course';
                   5367:     } elsif ($type eq 'map') {
1.588     albertel 5368: 	$res=&symbread($map);
                   5369:     } else {
                   5370: 	$res=$symb;
                   5371:     }
1.1153    www      5372:     &load_all_first_access($uname,$udom);
                   5373:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5374: }
                   5375: 
                   5376: sub set_first_access {
1.1162    raeburn  5377:     my ($type,$interval)=@_;
1.790     albertel 5378:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5379:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5380:     if ($type eq 'course') {
                   5381: 	$res='course';
                   5382:     } elsif ($type eq 'map') {
1.588     albertel 5383: 	$res=&symbread($map);
                   5384:     } else {
                   5385: 	$res=$symb;
                   5386:     }
1.1153    www      5387:     $cachedkey='';
1.1162    raeburn  5388:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1172.2.102  raeburn  5389:     if ($firstaccess) {
                   5390:         &logthis("First access time already set ($firstaccess) when attempting ".
                   5391:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
                   5392:                  "in $courseid");
                   5393:         return 'already_set';
                   5394:     } else {
1.1162    raeburn  5395:         my $start = time;
                   5396: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5397:                           $udom,$uname);
                   5398:         if ($putres eq 'ok') {
                   5399:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5400:                  $udom,$uname); 
                   5401:             &appenv(
                   5402:                      {
                   5403:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5404:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5405:                      }
                   5406:                   );
1.1172.2.97  raeburn  5407:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5408:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5409:             }
1.1172.2.102  raeburn  5410:         } elsif ($putres ne 'refused') {
                   5411:             &logthis("Result: $putres when attempting to set first access time ".
                   5412:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  5413:         }
                   5414:         return $putres;
1.505     albertel 5415:     }
                   5416:     return 'already_set';
1.504     albertel 5417: }
1.1153    www      5418: }
1.1172.2.32  raeburn  5419: 
                   5420: sub checkout {
                   5421:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   5422:     my $now=time;
                   5423:     my $lonhost=$perlvar{'lonHostID'};
                   5424:     my $infostr=&escape(
                   5425:                  'CHECKOUTTOKEN&'.
                   5426:                  $tuname.'&'.
                   5427:                  $tudom.'&'.
                   5428:                  $tcrsid.'&'.
                   5429:                  $symb.'&'.
                   5430:                  $now.'&'.$ENV{'REMOTE_ADDR'});
                   5431:     my $token=&reply('tmpput:'.$infostr,$lonhost);
                   5432:     if ($token=~/^error\:/) {
                   5433:         &logthis("<font color=\"blue\">WARNING: ".
                   5434:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5435:                  "</font>");
                   5436:         return '';
                   5437:     }
                   5438: 
                   5439:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   5440:     $token=~tr/a-z/A-Z/;
                   5441: 
                   5442:     my %infohash=('resource.0.outtoken' => $token,
                   5443:                   'resource.0.checkouttime' => $now,
                   5444:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
                   5445: 
                   5446:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5447:        return '';
                   5448:     } else {
                   5449:         &logthis("<font color=\"blue\">WARNING: ".
                   5450:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5451:                  "</font>");
                   5452:     }
                   5453: 
                   5454:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5455:                          &escape('Checkout '.$infostr.' - '.
                   5456:                                                  $token)) ne 'ok') {
                   5457:         return '';
                   5458:     } else {
                   5459:         &logthis("<font color=\"blue\">WARNING: ".
                   5460:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5461:                  "</font>");
                   5462:     }
                   5463:     return $token;
                   5464: }
                   5465: 
                   5466: # ------------------------------------------------------------ Check in an item
                   5467: 
                   5468: sub checkin {
                   5469:     my $token=shift;
                   5470:     my $now=time;
                   5471:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   5472:     $lonhost=~tr/A-Z/a-z/;
                   5473:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
                   5474:     $dtoken=~s/\W/\_/g;
                   5475:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                   5476:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   5477: 
                   5478:     unless (($tuname) && ($tudom)) {
                   5479:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   5480:         return '';
                   5481:     }
                   5482: 
                   5483:     unless (&allowed('mgr',$tcrsid)) {
                   5484:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   5485:                  $env{'user.name'}.' - '.$env{'user.domain'});
                   5486:         return '';
                   5487:     }
                   5488: 
                   5489:     my %infohash=('resource.0.intoken' => $token,
                   5490:                   'resource.0.checkintime' => $now,
                   5491:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
                   5492: 
                   5493:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5494:        return '';
                   5495:     }
                   5496: 
                   5497:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5498:                          &escape('Checkin - '.$token)) ne 'ok') {
                   5499:         return '';
                   5500:     }
                   5501: 
                   5502:     return ($symb,$tuname,$tudom,$tcrsid);
                   5503: }
                   5504: 
1.110     www      5505: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5506: 
                   5507: sub expirespread {
                   5508:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5509:     my $cid=$env{'request.course.id'}; 
1.110     www      5510:     if ($cid) {
                   5511:        my $now=time;
                   5512:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5513:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5514:                             $env{'course.'.$cid.'.num'}.
1.110     www      5515: 	        	    ':nohist_expirationdates:'.
                   5516:                             &escape($key).'='.$now,
1.620     albertel 5517:                             $env{'course.'.$cid.'.home'})
1.110     www      5518:     }
                   5519:     return 'ok';
1.14      www      5520: }
                   5521: 
1.109     www      5522: # ----------------------------------------------------- Devalidate Spreadsheets
                   5523: 
                   5524: sub devalidate {
1.325     www      5525:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5526:     my $cid=$env{'request.course.id'}; 
1.109     www      5527:     if ($cid) {
1.391     matthew  5528:         # delete the stored spreadsheets for
                   5529:         # - the student level sheet of this user in course's homespace
                   5530:         # - the assessment level sheet for this resource 
                   5531:         #   for this user in user's homespace
1.553     albertel 5532: 	# - current conditional state info
1.325     www      5533: 	my $key=$uname.':'.$udom.':';
1.109     www      5534:         my $status=
1.299     matthew  5535: 	    &del('nohist_calculatedsheets',
1.391     matthew  5536: 		 [$key.'studentcalc:'],
1.620     albertel 5537: 		 $env{'course.'.$cid.'.domain'},
                   5538: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5539: 		.' '.
                   5540: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5541: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5542:         unless ($status eq 'ok ok') {
                   5543:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5544:                     $uname.' at '.$udom.' for '.
1.109     www      5545: 		    $symb.': '.$status);
1.133     albertel 5546:         }
1.553     albertel 5547: 	&delenv('user.state.'.$cid);
1.109     www      5548:     }
                   5549: }
                   5550: 
1.265     albertel 5551: sub get_scalar {
                   5552:     my ($string,$end) = @_;
                   5553:     my $value;
                   5554:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5555: 	$value = $1;
                   5556:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5557: 	$value = $1;
                   5558:     }
                   5559:     return &unescape($value);
                   5560: }
                   5561: 
                   5562: sub array2str {
                   5563:   my (@array) = @_;
                   5564:   my $result=&arrayref2str(\@array);
                   5565:   $result=~s/^__ARRAY_REF__//;
                   5566:   $result=~s/__END_ARRAY_REF__$//;
                   5567:   return $result;
                   5568: }
                   5569: 
1.204     albertel 5570: sub arrayref2str {
                   5571:   my ($arrayref) = @_;
1.265     albertel 5572:   my $result='__ARRAY_REF__';
1.204     albertel 5573:   foreach my $elem (@$arrayref) {
1.265     albertel 5574:     if(ref($elem) eq 'ARRAY') {
                   5575:       $result.=&arrayref2str($elem).'&';
                   5576:     } elsif(ref($elem) eq 'HASH') {
                   5577:       $result.=&hashref2str($elem).'&';
                   5578:     } elsif(ref($elem)) {
                   5579:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5580:     } else {
                   5581:       $result.=&escape($elem).'&';
                   5582:     }
                   5583:   }
                   5584:   $result=~s/\&$//;
1.265     albertel 5585:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5586:   return $result;
                   5587: }
                   5588: 
1.168     albertel 5589: sub hash2str {
1.204     albertel 5590:   my (%hash) = @_;
                   5591:   my $result=&hashref2str(\%hash);
1.265     albertel 5592:   $result=~s/^__HASH_REF__//;
                   5593:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5594:   return $result;
                   5595: }
                   5596: 
                   5597: sub hashref2str {
                   5598:   my ($hashref)=@_;
1.265     albertel 5599:   my $result='__HASH_REF__';
1.800     albertel 5600:   foreach my $key (sort(keys(%$hashref))) {
                   5601:     if (ref($key) eq 'ARRAY') {
                   5602:       $result.=&arrayref2str($key).'=';
                   5603:     } elsif (ref($key) eq 'HASH') {
                   5604:       $result.=&hashref2str($key).'=';
                   5605:     } elsif (ref($key)) {
1.265     albertel 5606:       $result.='=';
1.800     albertel 5607:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5608:     } else {
1.1132    raeburn  5609: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5610:     }
                   5611: 
1.800     albertel 5612:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5613:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5614:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5615:       $result.=&hashref2str($hashref->{$key}).'&';
                   5616:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5617:        $result.='&';
1.800     albertel 5618:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5619:     } else {
1.800     albertel 5620:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5621:     }
                   5622:   }
1.168     albertel 5623:   $result=~s/\&$//;
1.265     albertel 5624:   $result .= '__END_HASH_REF__';
1.168     albertel 5625:   return $result;
                   5626: }
                   5627: 
                   5628: sub str2hash {
1.265     albertel 5629:     my ($string)=@_;
                   5630:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5631:     return %$hash;
                   5632: }
                   5633: 
                   5634: sub str2hashref {
1.168     albertel 5635:   my ($string) = @_;
1.265     albertel 5636: 
                   5637:   my %hash;
                   5638: 
                   5639:   if($string !~ /^__HASH_REF__/) {
                   5640:       if (! ($string eq '' || !defined($string))) {
                   5641: 	  $hash{'error'}='Not hash reference';
                   5642:       }
                   5643:       return (\%hash, $string);
                   5644:   }
                   5645: 
                   5646:   $string =~ s/^__HASH_REF__//;
                   5647: 
                   5648:   while($string !~ /^__END_HASH_REF__/) {
                   5649:       #key
                   5650:       my $key='';
                   5651:       if($string =~ /^__HASH_REF__/) {
                   5652:           ($key, $string)=&str2hashref($string);
                   5653:           if(defined($key->{'error'})) {
                   5654:               $hash{'error'}='Bad data';
                   5655:               return (\%hash, $string);
                   5656:           }
                   5657:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5658:           ($key, $string)=&str2arrayref($string);
                   5659:           if($key->[0] eq 'Array reference error') {
                   5660:               $hash{'error'}='Bad data';
                   5661:               return (\%hash, $string);
                   5662:           }
                   5663:       } else {
                   5664:           $string =~ s/^(.*?)=//;
1.267     albertel 5665: 	  $key=&unescape($1);
1.265     albertel 5666:       }
                   5667:       $string =~ s/^=//;
                   5668: 
                   5669:       #value
                   5670:       my $value='';
                   5671:       if($string =~ /^__HASH_REF__/) {
                   5672:           ($value, $string)=&str2hashref($string);
                   5673:           if(defined($value->{'error'})) {
                   5674:               $hash{'error'}='Bad data';
                   5675:               return (\%hash, $string);
                   5676:           }
                   5677:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5678:           ($value, $string)=&str2arrayref($string);
                   5679:           if($value->[0] eq 'Array reference error') {
                   5680:               $hash{'error'}='Bad data';
                   5681:               return (\%hash, $string);
                   5682:           }
                   5683:       } else {
                   5684: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5685:       }
                   5686:       $string =~ s/^&//;
                   5687: 
                   5688:       $hash{$key}=$value;
1.204     albertel 5689:   }
1.265     albertel 5690: 
                   5691:   $string =~ s/^__END_HASH_REF__//;
                   5692: 
                   5693:   return (\%hash, $string);
1.204     albertel 5694: }
                   5695: 
                   5696: sub str2array {
1.265     albertel 5697:     my ($string)=@_;
                   5698:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5699:     return @$array;
                   5700: }
                   5701: 
                   5702: sub str2arrayref {
1.204     albertel 5703:   my ($string) = @_;
1.265     albertel 5704:   my @array;
                   5705: 
                   5706:   if($string !~ /^__ARRAY_REF__/) {
                   5707:       if (! ($string eq '' || !defined($string))) {
                   5708: 	  $array[0]='Array reference error';
                   5709:       }
                   5710:       return (\@array, $string);
                   5711:   }
                   5712: 
                   5713:   $string =~ s/^__ARRAY_REF__//;
                   5714: 
                   5715:   while($string !~ /^__END_ARRAY_REF__/) {
                   5716:       my $value='';
                   5717:       if($string =~ /^__HASH_REF__/) {
                   5718:           ($value, $string)=&str2hashref($string);
                   5719:           if(defined($value->{'error'})) {
                   5720:               $array[0] ='Array reference error';
                   5721:               return (\@array, $string);
                   5722:           }
                   5723:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5724:           ($value, $string)=&str2arrayref($string);
                   5725:           if($value->[0] eq 'Array reference error') {
                   5726:               $array[0] ='Array reference error';
                   5727:               return (\@array, $string);
                   5728:           }
                   5729:       } else {
                   5730: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5731:       }
                   5732:       $string =~ s/^&//;
                   5733: 
                   5734:       push(@array, $value);
1.191     harris41 5735:   }
1.265     albertel 5736: 
                   5737:   $string =~ s/^__END_ARRAY_REF__//;
                   5738: 
                   5739:   return (\@array, $string);
1.168     albertel 5740: }
                   5741: 
1.167     albertel 5742: # -------------------------------------------------------------------Temp Store
                   5743: 
1.168     albertel 5744: sub tmpreset {
                   5745:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5746:   if (!$symb) {
                   5747:     $symb=&symbread();
1.620     albertel 5748:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5749:   }
                   5750:   $symb=escape($symb);
                   5751: 
1.620     albertel 5752:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5753:   $namespace=~s/\//\_/g;
                   5754:   $namespace=~s/\W//g;
                   5755: 
1.620     albertel 5756:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5757:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5758:   if ($domain eq 'public' && $stuname eq 'public') {
                   5759:       $stuname=$ENV{'REMOTE_ADDR'};
                   5760:   }
1.1117    foxr     5761:   my $path=LONCAPA::tempdir();
1.168     albertel 5762:   my %hash;
                   5763:   if (tie(%hash,'GDBM_File',
                   5764: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5765: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5766:     foreach my $key (keys(%hash)) {
1.180     albertel 5767:       if ($key=~ /:$symb/) {
1.168     albertel 5768: 	delete($hash{$key});
                   5769:       }
                   5770:     }
                   5771:   }
                   5772: }
                   5773: 
1.167     albertel 5774: sub tmpstore {
1.168     albertel 5775:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5776: 
                   5777:   if (!$symb) {
                   5778:     $symb=&symbread();
1.620     albertel 5779:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5780:   }
                   5781:   $symb=escape($symb);
                   5782: 
                   5783:   if (!$namespace) {
                   5784:     # I don't think we would ever want to store this for a course.
                   5785:     # it seems this will only be used if we don't have a course.
1.620     albertel 5786:     #$namespace=$env{'request.course.id'};
1.168     albertel 5787:     #if (!$namespace) {
1.620     albertel 5788:       $namespace=$env{'request.state'};
1.168     albertel 5789:     #}
                   5790:   }
                   5791:   $namespace=~s/\//\_/g;
                   5792:   $namespace=~s/\W//g;
1.620     albertel 5793:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5794:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5795:   if ($domain eq 'public' && $stuname eq 'public') {
                   5796:       $stuname=$ENV{'REMOTE_ADDR'};
                   5797:   }
1.168     albertel 5798:   my $now=time;
                   5799:   my %hash;
1.1117    foxr     5800:   my $path=LONCAPA::tempdir();
1.168     albertel 5801:   if (tie(%hash,'GDBM_File',
                   5802: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5803: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5804:     $hash{"version:$symb"}++;
                   5805:     my $version=$hash{"version:$symb"};
                   5806:     my $allkeys=''; 
                   5807:     foreach my $key (keys(%$storehash)) {
                   5808:       $allkeys.=$key.':';
1.591     albertel 5809:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5810:     }
                   5811:     $hash{"$version:$symb:timestamp"}=$now;
                   5812:     $allkeys.='timestamp';
                   5813:     $hash{"$version:keys:$symb"}=$allkeys;
                   5814:     if (untie(%hash)) {
                   5815:       return 'ok';
                   5816:     } else {
                   5817:       return "error:$!";
                   5818:     }
                   5819:   } else {
                   5820:     return "error:$!";
                   5821:   }
                   5822: }
1.167     albertel 5823: 
1.168     albertel 5824: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5825: 
1.168     albertel 5826: sub tmprestore {
                   5827:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5828: 
1.168     albertel 5829:   if (!$symb) {
                   5830:     $symb=&symbread();
1.620     albertel 5831:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5832:   }
                   5833:   $symb=escape($symb);
                   5834: 
1.620     albertel 5835:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5836: 
1.620     albertel 5837:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5838:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5839:   if ($domain eq 'public' && $stuname eq 'public') {
                   5840:       $stuname=$ENV{'REMOTE_ADDR'};
                   5841:   }
1.168     albertel 5842:   my %returnhash;
                   5843:   $namespace=~s/\//\_/g;
                   5844:   $namespace=~s/\W//g;
                   5845:   my %hash;
1.1117    foxr     5846:   my $path=LONCAPA::tempdir();
1.168     albertel 5847:   if (tie(%hash,'GDBM_File',
                   5848: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5849: 	  &GDBM_READER(),0640)) {
1.168     albertel 5850:     my $version=$hash{"version:$symb"};
                   5851:     $returnhash{'version'}=$version;
                   5852:     my $scope;
                   5853:     for ($scope=1;$scope<=$version;$scope++) {
                   5854:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5855:       my @keys=split(/:/,$vkeys);
                   5856:       my $key;
                   5857:       $returnhash{"$scope:keys"}=$vkeys;
                   5858:       foreach $key (@keys) {
1.591     albertel 5859: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   5860: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 5861:       }
                   5862:     }
1.168     albertel 5863:     if (!(untie(%hash))) {
                   5864:       return "error:$!";
                   5865:     }
                   5866:   } else {
                   5867:     return "error:$!";
                   5868:   }
                   5869:   return %returnhash;
1.167     albertel 5870: }
                   5871: 
1.9       www      5872: # ----------------------------------------------------------------------- Store
                   5873: 
                   5874: sub store {
1.1172.2.64  raeburn  5875:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5876:     my $home='';
                   5877: 
1.168     albertel 5878:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5879: 
1.213     www      5880:     $symb=&symbclean($symb);
1.122     albertel 5881:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5882: 
1.620     albertel 5883:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5884:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5885: 
                   5886:     &devalidate($symb,$stuname,$domain);
1.109     www      5887: 
                   5888:     $symb=escape($symb);
1.187     www      5889:     if (!$namespace) { 
1.620     albertel 5890:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5891:           return ''; 
                   5892:        } 
                   5893:     }
1.620     albertel 5894:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5895: 
                   5896:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5897:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   5898: 
1.12      www      5899:     my $namevalue='';
1.800     albertel 5900:     foreach my $key (keys(%$storehash)) {
                   5901:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5902:     }
1.12      www      5903:     $namevalue=~s/\&$//;
1.187     www      5904:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64  raeburn  5905:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      5906: }
                   5907: 
1.47      www      5908: # -------------------------------------------------------------- Critical Store
                   5909: 
                   5910: sub cstore {
1.1172.2.64  raeburn  5911:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5912:     my $home='';
                   5913: 
1.168     albertel 5914:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5915: 
1.213     www      5916:     $symb=&symbclean($symb);
1.122     albertel 5917:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5918: 
1.620     albertel 5919:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5920:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5921: 
                   5922:     &devalidate($symb,$stuname,$domain);
1.109     www      5923: 
                   5924:     $symb=escape($symb);
1.187     www      5925:     if (!$namespace) { 
1.620     albertel 5926:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5927:           return ''; 
                   5928:        } 
                   5929:     }
1.620     albertel 5930:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5931: 
                   5932:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5933:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 5934: 
1.47      www      5935:     my $namevalue='';
1.800     albertel 5936:     foreach my $key (keys(%$storehash)) {
                   5937:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5938:     }
1.47      www      5939:     $namevalue=~s/\&$//;
1.187     www      5940:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      5941:     return critical
1.1172.2.64  raeburn  5942:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      5943: }
                   5944: 
1.9       www      5945: # --------------------------------------------------------------------- Restore
                   5946: 
                   5947: sub restore {
1.124     www      5948:     my ($symb,$namespace,$domain,$stuname) = @_;
                   5949:     my $home='';
                   5950: 
1.168     albertel 5951:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5952: 
1.122     albertel 5953:     if (!$symb) {
1.1172.2.26  raeburn  5954:         return if ($namespace eq 'courserequests');
                   5955:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 5956:     } else {
1.1172.2.26  raeburn  5957:         unless ($namespace eq 'courserequests') {
                   5958:             $symb=&escape(&symbclean($symb));
                   5959:         }
1.122     albertel 5960:     }
1.188     www      5961:     if (!$namespace) { 
1.620     albertel 5962:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      5963:           return ''; 
                   5964:        } 
                   5965:     }
1.620     albertel 5966:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5967:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   5968:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 5969:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   5970: 
1.12      www      5971:     my %returnhash=();
1.800     albertel 5972:     foreach my $line (split(/\&/,$answer)) {
                   5973: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 5974:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 5975:     }
1.75      www      5976:     my $version;
                   5977:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 5978:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   5979:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 5980:        }
1.75      www      5981:     }
1.13      www      5982:     return %returnhash;
1.34      www      5983: }
                   5984: 
                   5985: # ---------------------------------------------------------- Course Description
1.1118    foxr     5986: #
                   5987: #  
1.34      www      5988: 
                   5989: sub coursedescription {
1.731     albertel 5990:     my ($courseid,$args)=@_;
1.34      www      5991:     $courseid=~s/^\///;
1.49      www      5992:     $courseid=~s/\_/\//g;
1.34      www      5993:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 5994:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 5995:     my $normalid=$cdomain.'_'.$cnum;
                   5996:     # need to always cache even if we get errors otherwise we keep 
                   5997:     # trying and trying and trying to get the course description.
                   5998:     my %envhash=();
                   5999:     my %returnhash=();
1.731     albertel 6000:     
                   6001:     my $expiretime=600;
                   6002:     if ($env{'request.course.id'} eq $normalid) {
                   6003: 	$expiretime=120;
                   6004:     }
                   6005: 
                   6006:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   6007:     if (!$args->{'freshen_cache'}
                   6008: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   6009: 	foreach my $key (keys(%env)) {
                   6010: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   6011: 	    my ($setting) = $1;
                   6012: 	    $returnhash{$setting} = $env{$key};
                   6013: 	}
                   6014: 	return %returnhash;
                   6015:     }
                   6016: 
1.1118    foxr     6017:     # get the data again
                   6018: 
1.731     albertel 6019:     if (!$args->{'one_time'}) {
                   6020: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   6021:     }
1.811     albertel 6022: 
1.34      www      6023:     if ($chome ne 'no_host') {
1.302     albertel 6024:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 6025:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     6026: 	   my $username = $env{'user.name'}; # Defult username
                   6027: 	   if(defined $args->{'user'}) {
                   6028: 	       $username = $args->{'user'};
                   6029: 	   }
1.129     albertel 6030:            $returnhash{'home'}= $chome;
                   6031: 	   $returnhash{'domain'} = $cdomain;
                   6032: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  6033:            if (!defined($returnhash{'type'})) {
                   6034:                $returnhash{'type'} = 'Course';
                   6035:            }
1.130     albertel 6036:            while (my ($name,$value) = each %returnhash) {
1.53      www      6037:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 6038:            }
1.270     www      6039:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     6040:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     6041: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      6042:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   6043:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   6044:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      6045:        }
                   6046:     }
1.731     albertel 6047:     if (!$args->{'one_time'}) {
1.949     raeburn  6048: 	&appenv(\%envhash);
1.731     albertel 6049:     }
1.302     albertel 6050:     return %returnhash;
1.461     www      6051: }
                   6052: 
1.1080    raeburn  6053: sub update_released_required {
                   6054:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   6055:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   6056:         $cid = $env{'request.course.id'};
                   6057:         $cdom = $env{'course.'.$cid.'.domain'};
                   6058:         $cnum = $env{'course.'.$cid.'.num'};
                   6059:         $chome = $env{'course.'.$cid.'.home'};
                   6060:     }
                   6061:     if ($needsrelease) {
                   6062:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   6063:         my $needsupdate;
                   6064:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   6065:             $needsupdate = 1;
                   6066:         } else {
                   6067:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   6068:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   6069:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   6070:                 $needsupdate = 1;
                   6071:             }
                   6072:         }
                   6073:         if ($needsupdate) {
                   6074:             my %needshash = (
                   6075:                              'internal.releaserequired' => $needsrelease,
                   6076:                             );
                   6077:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   6078:             if ($putresult eq 'ok') {
                   6079:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   6080:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6081:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   6082:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   6083:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   6084:                 }
                   6085:             }
                   6086:         }
                   6087:     }
                   6088:     return;
                   6089: }
                   6090: 
1.461     www      6091: # -------------------------------------------------See if a user is privileged
                   6092: 
                   6093: sub privileged {
1.1172.2.23  raeburn  6094:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 6095:     my $now = time;
1.1172.2.23  raeburn  6096:     my $roles;
                   6097:     if (ref($possroles) eq 'ARRAY') {
                   6098:         $roles = $possroles;
                   6099:     } else {
                   6100:         $roles = ['dc','su'];
                   6101:     }
                   6102:     if (ref($possdomains) eq 'ARRAY') {
                   6103:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   6104:         foreach my $dom (@{$possdomains}) {
                   6105:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   6106:                 (ref($privileged{$dom}) eq 'HASH')) {
                   6107:                 foreach my $role (@{$roles}) {
                   6108:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6109:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   6110:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   6111:                             return 1 unless (($end && $end < $now) ||
                   6112:                                              ($start && $start > $now));
                   6113:                         }
                   6114:                     }
                   6115:                 }
                   6116:             }
                   6117:         }
                   6118:     } else {
                   6119:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   6120:         my $now = time;
1.1170    droeschl 6121: 
1.1172.2.58  raeburn  6122:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 6123:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  6124:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   6125:                 return 1 unless ($tend && $tend < $now)
                   6126:                         or ($tstart && $tstart > $now);
1.1170    droeschl 6127:             }
1.1172.2.23  raeburn  6128:         }
                   6129:     }
1.461     www      6130:     return 0;
1.9       www      6131: }
1.1       albertel 6132: 
1.1172.2.23  raeburn  6133: sub privileged_by_domain {
                   6134:     my ($domains,$roles) = @_;
                   6135:     my %privileged = ();
                   6136:     my $cachetime = 60*60*24;
                   6137:     my $now = time;
                   6138:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   6139:         return %privileged;
                   6140:     }
                   6141:     foreach my $dom (@{$domains}) {
                   6142:         next if (ref($privileged{$dom}) eq 'HASH');
                   6143:         my $needroles;
                   6144:         foreach my $role (@{$roles}) {
                   6145:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   6146:             if (defined($cached)) {
                   6147:                 if (ref($result) eq 'HASH') {
                   6148:                     $privileged{$dom}{$role} = $result;
                   6149:                 }
                   6150:             } else {
                   6151:                 $needroles = 1;
                   6152:             }
                   6153:         }
                   6154:         if ($needroles) {
                   6155:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   6156:             $privileged{$dom} = {};
                   6157:             foreach my $server (keys(%dompersonnel)) {
                   6158:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   6159:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   6160:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   6161:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   6162:                         next if ($end && $end < $now);
                   6163:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   6164:                             $dompersonnel{$server}{$item};
                   6165:                     }
                   6166:                 }
                   6167:             }
                   6168:             if (ref($privileged{$dom}) eq 'HASH') {
                   6169:                 foreach my $role (@{$roles}) {
                   6170:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6171:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   6172:                     } else {
                   6173:                         my %hash = ();
                   6174:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   6175:                     }
                   6176:                 }
                   6177:             }
                   6178:         }
                   6179:     }
                   6180:     return %privileged;
                   6181: }
                   6182: 
1.103     harris41 6183: # -------------------------------------------------------- Get user privileges
1.11      www      6184: 
                   6185: sub rolesinit {
1.1169    droeschl 6186:     my ($domain, $username) = @_;
                   6187:     my %userroles = ('user.login.time' => time);
                   6188:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   6189: 
                   6190:     # firstaccess and timerinterval are related to timed maps/resources. 
                   6191:     # also, blocking can be triggered by an activating timer
                   6192:     # it's saved in the user's %env.
                   6193:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   6194:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   6195:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   6196:         %timerintchk, %timerintenv);
                   6197: 
1.1162    raeburn  6198:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 6199:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  6200:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   6201:     }
1.1169    droeschl 6202: 
1.1162    raeburn  6203:     foreach my $key (keys(%timerinterval)) {
                   6204:         my ($cid,$rest) = split(/\0/,$key);
                   6205:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   6206:     }
1.1169    droeschl 6207: 
1.11      www      6208:     my %allroles=();
1.1162    raeburn  6209:     my %allgroups=();
1.11      www      6210: 
1.1172.2.58  raeburn  6211:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 6212:         my $role = $rolesdump{$area};
                   6213:         $area =~ s/\_\w\w$//;
                   6214: 
                   6215:         my ($trole, $tend, $tstart, $group_privs);
                   6216: 
                   6217:         if ($role =~ /^cr/) {
                   6218:         # Custom role, defined by a user 
                   6219:         # e.g., user.role.cr/msu/smith/mynewrole
                   6220:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   6221:                 $trole = $1;
                   6222:                 ($tend, $tstart) = split('_', $2);
                   6223:             } else {
                   6224:                 $trole = $role;
                   6225:             }
                   6226:         } elsif ($role =~ m|^gr/|) {
                   6227:         # Role of member in a group, defined within a course/community
                   6228:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   6229:             ($trole, $tend, $tstart) = split(/_/, $role);
                   6230:             next if $tstart eq '-1';
                   6231:             ($trole, $group_privs) = split(/\//, $trole);
                   6232:             $group_privs = &unescape($group_privs);
                   6233:         } else {
                   6234:         # Just a normal role, defined in roles.tab
                   6235:             ($trole, $tend, $tstart) = split(/_/,$role);
                   6236:         }
                   6237: 
                   6238:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   6239:                  $username);
                   6240:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   6241: 
                   6242:         # role expired or not available yet?
                   6243:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   6244:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   6245: 
                   6246:         next if $area eq '' or $trole eq '';
                   6247: 
                   6248:         my $spec = "$trole.$area";
                   6249:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   6250: 
                   6251:         if ($trole =~ /^cr\//) {
                   6252:         # Custom role, defined by a user
                   6253:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6254:         } elsif ($trole eq 'gr') {
                   6255:         # Role of a member in a group, defined within a course/community
                   6256:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   6257:             next;
                   6258:         } else {
                   6259:         # Normal role, defined in roles.tab
                   6260:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6261:         }
                   6262: 
                   6263:         my $cid = $tdomain.'_'.$trest;
                   6264:         unless ($firstaccchk{$cid}) {
                   6265:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6266:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6267:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6268:                         $coursetimerstarts{$cid}{$item}; 
                   6269:                 }
                   6270:             }
                   6271:             $firstaccchk{$cid} = 1;
                   6272:         }
                   6273:         unless ($timerintchk{$cid}) {
                   6274:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6275:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6276:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6277:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6278:                 }
1.12      www      6279:             }
1.1169    droeschl 6280:             $timerintchk{$cid} = 1;
1.191     harris41 6281:         }
1.11      www      6282:     }
1.1169    droeschl 6283: 
1.1172.2.91  raeburn  6284:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6285:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6286:     $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91  raeburn  6287:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6288: 
1.1162    raeburn  6289:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6290: }
                   6291: 
1.567     raeburn  6292: sub set_arearole {
1.1172.2.19  raeburn  6293:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6294:     unless ($nolog) {
1.567     raeburn  6295: # log the associated role with the area
1.1172.2.19  raeburn  6296:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6297:     }
1.743     albertel 6298:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6299: }
                   6300: 
                   6301: sub custom_roleprivs {
                   6302:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6303:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40  raeburn  6304:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6305:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6306:         my ($rdummy,$roledef)=
                   6307:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6308:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6309:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6310:             if (defined($syspriv)) {
1.1043    raeburn  6311:                 if ($trest =~ /^$match_community$/) {
                   6312:                     $syspriv =~ s/bre\&S//; 
                   6313:                 }
1.567     raeburn  6314:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6315:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6316:             }
                   6317:             if ($tdomain ne '') {
                   6318:                 if (defined($dompriv)) {
                   6319:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6320:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6321:                 }
                   6322:                 if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89  raeburn  6323:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6324:                         my $rolename = $1;
                   6325:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6326:                     }
1.567     raeburn  6327:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6328:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6329:                 }
                   6330:             }
                   6331:         }
                   6332:     }
                   6333: }
                   6334: 
1.1172.2.89  raeburn  6335: sub course_adhocrole_privs {
                   6336:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6337:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6338:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6339:         my (%currprivs,%storeprivs);
                   6340:         foreach my $item (split(/:/,$coursepriv)) {
                   6341:             my ($priv,$restrict) = split(/\&/,$item);
                   6342:             $currprivs{$priv} = $restrict;
                   6343:         }
                   6344:         my (%possadd,%possremove,%full);
                   6345:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6346:             my ($priv,$restrict)=split(/\&/,$item);
                   6347:             $full{$priv} = $restrict;
                   6348:         }
                   6349:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   6350:              next if ($item eq '');
                   6351:              my ($rule,$rest) = split(/=/,$item);
                   6352:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   6353:              foreach my $priv (split(/:/,$rest)) {
                   6354:                  if ($priv ne '') {
                   6355:                      if ($rule eq 'off') {
                   6356:                          $possremove{$priv} = 1;
                   6357:                      } else {
                   6358:                          $possadd{$priv} = 1;
                   6359:                      }
                   6360:                  }
                   6361:              }
                   6362:          }
                   6363:          foreach my $priv (sort(keys(%full))) {
                   6364:              if (exists($currprivs{$priv})) {
                   6365:                  unless (exists($possremove{$priv})) {
                   6366:                      $storeprivs{$priv} = $currprivs{$priv};
                   6367:                  }
                   6368:              } elsif (exists($possadd{$priv})) {
                   6369:                  $storeprivs{$priv} = $full{$priv};
                   6370:              }
                   6371:          }
                   6372:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6373:      }
                   6374:      return $coursepriv;
                   6375: }
                   6376: 
1.678     raeburn  6377: sub group_roleprivs {
                   6378:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6379:     my $access = 1;
                   6380:     my $now = time;
                   6381:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6382:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6383:     if ($access) {
1.811     albertel 6384:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6385:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6386:     }
                   6387: }
1.567     raeburn  6388: 
                   6389: sub standard_roleprivs {
                   6390:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6391:     if (defined($pr{$trole.':s'})) {
                   6392:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6393:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6394:     }
                   6395:     if ($tdomain ne '') {
                   6396:         if (defined($pr{$trole.':d'})) {
                   6397:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6398:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6399:         }
                   6400:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6401:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6402:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6403:         }
                   6404:     }
                   6405: }
                   6406: 
                   6407: sub set_userprivs {
1.1064    raeburn  6408:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6409:     my $author=0;
                   6410:     my $adv=0;
1.1172.2.91  raeburn  6411:     my $rar=0;
1.678     raeburn  6412:     my %grouproles = ();
                   6413:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6414:         my @groupkeys; 
1.1000    raeburn  6415:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6416:             push(@groupkeys,$role);
                   6417:         }
                   6418:         if (ref($groups_roles) eq 'HASH') {
                   6419:             foreach my $key (keys(%{$groups_roles})) {
                   6420:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6421:                     push(@groupkeys,$key);
                   6422:                 }
                   6423:             }
                   6424:         }
                   6425:         if (@groupkeys > 0) {
                   6426:             foreach my $role (@groupkeys) {
                   6427:                 my ($trole,$area,$sec,$extendedarea);
                   6428:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6429:                     $trole = $1;
                   6430:                     $area = $2;
                   6431:                     $sec = $3;
                   6432:                     $extendedarea = $area.$sec;
                   6433:                     if (exists($$allgroups{$area})) {
                   6434:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6435:                             my $spec = $trole.'.'.$extendedarea;
                   6436:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6437:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6438:                         }
1.678     raeburn  6439:                     }
                   6440:                 }
                   6441:             }
                   6442:         }
                   6443:     }
1.800     albertel 6444:     foreach my $group (keys(%grouproles)) {
                   6445:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6446:     }
1.800     albertel 6447:     foreach my $role (keys(%{$allroles})) {
                   6448:         my %thesepriv;
1.941     raeburn  6449:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6450:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6451:             if ($item ne '') {
                   6452:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6453:                 if ($restrictions eq '') {
                   6454:                     $thesepriv{$privilege}='F';
                   6455:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6456:                     $thesepriv{$privilege}.=$restrictions;
                   6457:                 }
                   6458:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91  raeburn  6459:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6460:             }
                   6461:         }
                   6462:         my $thesestr='';
1.1104    raeburn  6463:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6464: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6465: 	}
                   6466:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6467:     }
1.1172.2.91  raeburn  6468:     return ($author,$adv,$rar);
1.567     raeburn  6469: }
                   6470: 
1.994     raeburn  6471: sub role_status {
1.1104    raeburn  6472:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6473:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40  raeburn  6474:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6475:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6476:         unless (!defined($$role) || $$role eq '') {
1.1172.2.40  raeburn  6477:             $$where = '/'.$two;
1.994     raeburn  6478:             $$trolecode=$$role.'.'.$$where;
                   6479:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6480:             $$tstatus='is';
1.1104    raeburn  6481:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6482:                 $$tstatus='future';
1.1034    raeburn  6483:                 if ($$tstart<$now) {
                   6484:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6485:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6486:                             my (%allroles,%allgroups,$group_privs,
                   6487:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6488:                             my %userroles = (
                   6489:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6490:                             );
1.1064    raeburn  6491:                             @rolecodes = ('cm'); 
1.1002    raeburn  6492:                             my $spec=$$role.'.'.$$where;
                   6493:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6494:                             if ($$role =~ /^cr\//) {
                   6495:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6496:                                 push(@rolecodes,'cr');
1.1002    raeburn  6497:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6498:                                 push(@rolecodes,$$role);
1.1002    raeburn  6499:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6500:                                                     $env{'user.name'});
1.1064    raeburn  6501:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6502:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6503:                                 $group_privs = &unescape($group_privs);
                   6504:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6505:                                 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  6506:                                 &get_groups_roles($tdomain,$trest,
                   6507:                                                   \%course_roles,\@rolecodes,
                   6508:                                                   \%groups_roles);
1.1002    raeburn  6509:                             } else {
1.1064    raeburn  6510:                                 push(@rolecodes,$$role);
1.1002    raeburn  6511:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6512:                             }
1.1172.2.91  raeburn  6513:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6514:                                                                    \%groups_roles);
1.1064    raeburn  6515:                             &appenv(\%userroles,\@rolecodes);
1.1172.2.92  raeburn  6516:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6517:                         }
                   6518:                     }
1.1034    raeburn  6519:                     $$tstatus = 'is';
1.1002    raeburn  6520:                 }
1.994     raeburn  6521:             }
                   6522:             if ($$tend) {
1.1104    raeburn  6523:                 if ($$tend<$update) {
1.994     raeburn  6524:                     $$tstatus='expired';
                   6525:                 } elsif ($$tend<$now) {
                   6526:                     $$tstatus='will_not';
                   6527:                 }
                   6528:             }
                   6529:         }
                   6530:     }
                   6531: }
                   6532: 
1.1104    raeburn  6533: sub get_groups_roles {
                   6534:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6535:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6536:                   (ref($rolecodes) eq 'ARRAY') && 
                   6537:                   (ref($groups_roles) eq 'HASH')); 
                   6538:     if (keys(%{$cdom_courseroles}) > 0) {
                   6539:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6540:         if ($cdom ne '' && $cnum ne '') {
                   6541:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6542:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6543:                     my $crsrole = $1;
                   6544:                     my $crssec = $2;
                   6545:                     if ($crsrole =~ /^cr/) {
                   6546:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6547:                             push(@{$rolecodes},'cr');
                   6548:                         }
                   6549:                     } else {
                   6550:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6551:                             push(@{$rolecodes},$crsrole);
                   6552:                         }
                   6553:                     }
                   6554:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6555:                     if ($crssec ne '') {
                   6556:                         $rolekey .= "/$crssec";
                   6557:                     }
                   6558:                     $rolekey .= './';
                   6559:                     $groups_roles->{$rolekey} = $rolecodes;
                   6560:                 }
                   6561:             }
                   6562:         }
                   6563:     }
                   6564:     return;
                   6565: }
                   6566: 
                   6567: sub delete_env_groupprivs {
                   6568:     my ($where,$courseroles,$possroles) = @_;
                   6569:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6570:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6571:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6572:         %{$courseroles->{$udom}} =
                   6573:             &get_my_roles('','','userroles',['active'],
                   6574:                           $possroles,[$udom],1);
                   6575:     }
                   6576:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6577:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6578:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6579:             my $area = '/'.$cdom.'/'.$cnum;
                   6580:             my $privkey = "user.priv.$crsrole.$area";
                   6581:             if ($crssec ne '') {
                   6582:                 $privkey .= '/'.$crssec;
                   6583:             }
                   6584:             $privkey .= ".$area/$group";
                   6585:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6586:         }
                   6587:     }
                   6588:     return;
                   6589: }
                   6590: 
1.994     raeburn  6591: sub check_adhoc_privs {
1.1172.2.86  raeburn  6592:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6593:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86  raeburn  6594:     if ($sec) {
                   6595:         $cckey .= '/'.$sec;
                   6596:     }
1.1172.2.9  raeburn  6597:     my $setprivs;
1.994     raeburn  6598:     if ($env{$cckey}) {
                   6599:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6600:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6601:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86  raeburn  6602:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6603:             $setprivs = 1;
1.994     raeburn  6604:         }
                   6605:     } else {
1.1172.2.87  raeburn  6606:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6607:         $setprivs = 1;
1.994     raeburn  6608:     }
1.1172.2.9  raeburn  6609:     return $setprivs;
1.994     raeburn  6610: }
                   6611: 
                   6612: sub set_adhoc_privileges {
1.1172.2.84  raeburn  6613: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86  raeburn  6614:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6615:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86  raeburn  6616:     if ($sec ne '') {
                   6617:         $area .= '/'.$sec;
                   6618:     }
1.994     raeburn  6619:     my $spec = $role.'.'.$area;
                   6620:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  6621:                                   $env{'user.name'},1);
1.1172.2.84  raeburn  6622:     my %rolehash = ();
1.1172.2.89  raeburn  6623:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6624:         my $rolename = $1;
1.1172.2.84  raeburn  6625:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89  raeburn  6626:         my %domdef = &get_domain_defaults($dcdom);
                   6627:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6628:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6629:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6630:             }
                   6631:         }
1.1172.2.84  raeburn  6632:     } else {
                   6633:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6634:     }
1.1172.2.91  raeburn  6635:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6636:     &appenv(\%userroles,[$role,'cm']);
1.1172.2.92  raeburn  6637:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088    raeburn  6638:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   6639:         &appenv( {'request.role'        => $spec,
                   6640:                   'request.role.domain' => $dcdom,
1.1172.2.89  raeburn  6641:                   'request.course.sec'  => $sec, 
1.1088    raeburn  6642:                  }
                   6643:                );
                   6644:         my $tadv=0;
                   6645:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6646:         &appenv({'request.role.adv'    => $tadv});
                   6647:     }
1.994     raeburn  6648: }
                   6649: 
1.12      www      6650: # --------------------------------------------------------------- get interface
                   6651: 
                   6652: sub get {
1.131     albertel 6653:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6654:    my $items='';
1.800     albertel 6655:    foreach my $item (@$storearr) {
                   6656:        $items.=&escape($item).'&';
1.191     harris41 6657:    }
1.12      www      6658:    $items=~s/\&$//;
1.620     albertel 6659:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6660:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6661:    my $uhome=&homeserver($uname,$udomain);
                   6662: 
1.133     albertel 6663:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6664:    my @pairs=split(/\&/,$rep);
1.273     albertel 6665:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6666:      return @pairs;
                   6667:    }
1.15      www      6668:    my %returnhash=();
1.42      www      6669:    my $i=0;
1.800     albertel 6670:    foreach my $item (@$storearr) {
                   6671:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6672:       $i++;
1.191     harris41 6673:    }
1.15      www      6674:    return %returnhash;
1.27      www      6675: }
                   6676: 
                   6677: # --------------------------------------------------------------- del interface
                   6678: 
                   6679: sub del {
1.133     albertel 6680:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6681:    my $items='';
1.800     albertel 6682:    foreach my $item (@$storearr) {
                   6683:        $items.=&escape($item).'&';
1.191     harris41 6684:    }
1.984     neumanie 6685: 
1.27      www      6686:    $items=~s/\&$//;
1.620     albertel 6687:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6688:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6689:    my $uhome=&homeserver($uname,$udomain);
                   6690:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6691: }
                   6692: 
                   6693: # -------------------------------------------------------------- dump interface
                   6694: 
1.1172.2.22  raeburn  6695: sub unserialize {
                   6696:     my ($rep, $escapedkeys) = @_;
                   6697: 
                   6698:     return {} if $rep =~ /^error/;
                   6699: 
                   6700:     my %returnhash=();
                   6701:     foreach my $item (split(/\&/,$rep)) {
                   6702:         my ($key, $value) = split(/=/, $item, 2);
                   6703:         $key = unescape($key) unless $escapedkeys;
                   6704:         next if $key =~ /^error: 2 /;
                   6705:         $returnhash{$key} = &thaw_unescape($value);
                   6706:     }
                   6707:     return \%returnhash;
                   6708: }
                   6709: 
                   6710: # see Lond::dump_with_regexp
                   6711: # if $escapedkeys hash keys won't get unescaped.
1.15      www      6712: sub dump {
1.1172.2.22  raeburn  6713:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 6714:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6715:     if (!$uname) { $uname=$env{'user.name'}; }
                   6716:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 6717: 
1.1172.2.55  raeburn  6718:     if ($regexp) {
                   6719:         $regexp=&escape($regexp);
                   6720:     } else {
                   6721:         $regexp='.';
                   6722:     }
1.1172.2.22  raeburn  6723:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   6724:         # user is hosted on this machine
1.1172.2.55  raeburn  6725:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  6726:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  6727:         return %{&unserialize($reply, $escapedkeys)};
                   6728:     }
1.1166    raeburn  6729:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 6730:     my @pairs=split(/\&/,$rep);
                   6731:     my %returnhash=();
1.1098    foxr     6732:     if (!($rep =~ /^error/ )) {
                   6733: 	foreach my $item (@pairs) {
                   6734: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  6735:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     6736: 	    next if ($key =~ /^error: 2 /);
                   6737: 	    $returnhash{$key}=&thaw_unescape($value);
                   6738: 	}
1.755     albertel 6739:     }
                   6740:     return %returnhash;
1.407     www      6741: }
                   6742: 
1.1098    foxr     6743: 
1.717     albertel 6744: # --------------------------------------------------------- dumpstore interface
                   6745: 
                   6746: sub dumpstore {
                   6747:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  6748:    # same as dump but keys must be escaped. They may contain colon separated
                   6749:    # lists of values that may themself contain colons (e.g. symbs).
                   6750:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 6751: }
                   6752: 
1.407     www      6753: # -------------------------------------------------------------- keys interface
                   6754: 
                   6755: sub getkeys {
                   6756:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 6757:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6758:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      6759:    my $uhome=&homeserver($uname,$udomain);
                   6760:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   6761:    my @keyarray=();
1.800     albertel 6762:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  6763:       next if ($key =~ /^error: 2 /);
1.800     albertel 6764:       push(@keyarray,&unescape($key));
1.407     www      6765:    }
                   6766:    return @keyarray;
1.318     matthew  6767: }
                   6768: 
1.319     matthew  6769: # --------------------------------------------------------------- currentdump
                   6770: sub currentdump {
1.328     matthew  6771:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 6772:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   6773:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   6774:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  6775:    my $uhome = &homeserver($sname,$sdom);
1.1172.2.50  raeburn  6776:    my $rep;
                   6777: 
                   6778:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   6779:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
                   6780:                    $courseid)));
                   6781:    } else {
                   6782:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6783:    }
                   6784: 
1.318     matthew  6785:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6786:    #
1.318     matthew  6787:    my %returnhash=();
1.319     matthew  6788:    #
                   6789:    if ($rep eq "unknown_cmd") { 
                   6790:        # an old lond will not know currentdump
                   6791:        # Do a dump and make it look like a currentdump
1.822     albertel 6792:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6793:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6794:        my %hash = @tmp;
                   6795:        @tmp=();
1.424     matthew  6796:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6797:    } else {
                   6798:        my @pairs=split(/\&/,$rep);
1.800     albertel 6799:        foreach my $pair (@pairs) {
                   6800:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6801:            my ($symb,$param) = split(/:/,$key);
                   6802:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6803:                                                         &thaw_unescape($value);
1.319     matthew  6804:        }
1.191     harris41 6805:    }
1.12      www      6806:    return %returnhash;
1.424     matthew  6807: }
                   6808: 
                   6809: sub convert_dump_to_currentdump{
                   6810:     my %hash = %{shift()};
                   6811:     my %returnhash;
                   6812:     # Code ripped from lond, essentially.  The only difference
                   6813:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6814:     # we might run in to problems with parameter names =~ /^v\./
                   6815:     while (my ($key,$value) = each(%hash)) {
                   6816:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6817: 	$symb  = &unescape($symb);
                   6818: 	$param = &unescape($param);
1.424     matthew  6819:         next if ($v eq 'version' || $symb eq 'keys');
                   6820:         next if (exists($returnhash{$symb}) &&
                   6821:                  exists($returnhash{$symb}->{$param}) &&
                   6822:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6823:         $returnhash{$symb}->{$param}=$value;
                   6824:         $returnhash{$symb}->{'v.'.$param}=$v;
                   6825:     }
                   6826:     #
                   6827:     # Remove all of the keys in the hashes which keep track of
                   6828:     # the version of the parameter.
                   6829:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   6830:         # use a foreach because we are going to delete from the hash.
                   6831:         foreach my $key (keys(%$param_hash)) {
                   6832:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   6833:         }
                   6834:     }
                   6835:     return \%returnhash;
1.12      www      6836: }
                   6837: 
1.627     albertel 6838: # ------------------------------------------------------ critical inc interface
                   6839: 
                   6840: sub cinc {
                   6841:     return &inc(@_,'critical');
                   6842: }
                   6843: 
1.449     matthew  6844: # --------------------------------------------------------------- inc interface
                   6845: 
                   6846: sub inc {
1.627     albertel 6847:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 6848:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6849:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  6850:     my $uhome=&homeserver($uname,$udomain);
                   6851:     my $items='';
                   6852:     if (! ref($store)) {
                   6853:         # got a single value, so use that instead
                   6854:         $items = &escape($store).'=&';
                   6855:     } elsif (ref($store) eq 'SCALAR') {
                   6856:         $items = &escape($$store).'=&';        
                   6857:     } elsif (ref($store) eq 'ARRAY') {
                   6858:         $items = join('=&',map {&escape($_);} @{$store});
                   6859:     } elsif (ref($store) eq 'HASH') {
                   6860:         while (my($key,$value) = each(%{$store})) {
                   6861:             $items.= &escape($key).'='.&escape($value).'&';
                   6862:         }
                   6863:     }
                   6864:     $items=~s/\&$//;
1.627     albertel 6865:     if ($critical) {
                   6866: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6867:     } else {
                   6868: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6869:     }
1.449     matthew  6870: }
                   6871: 
1.12      www      6872: # --------------------------------------------------------------- put interface
                   6873: 
                   6874: sub put {
1.134     albertel 6875:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6876:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6877:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6878:    my $uhome=&homeserver($uname,$udomain);
1.12      www      6879:    my $items='';
1.800     albertel 6880:    foreach my $item (keys(%$storehash)) {
                   6881:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6882:    }
1.12      www      6883:    $items=~s/\&$//;
1.134     albertel 6884:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      6885: }
                   6886: 
1.631     albertel 6887: # ------------------------------------------------------------ newput interface
                   6888: 
                   6889: sub newput {
                   6890:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   6891:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6892:    if (!$uname) { $uname=$env{'user.name'}; }
                   6893:    my $uhome=&homeserver($uname,$udomain);
                   6894:    my $items='';
                   6895:    foreach my $key (keys(%$storehash)) {
                   6896:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   6897:    }
                   6898:    $items=~s/\&$//;
                   6899:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   6900: }
                   6901: 
                   6902: # ---------------------------------------------------------  putstore interface
                   6903: 
1.524     raeburn  6904: sub putstore {
1.1172.2.59  raeburn  6905:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 6906:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6907:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  6908:    my $uhome=&homeserver($uname,$udomain);
                   6909:    my $items='';
1.715     albertel 6910:    foreach my $key (keys(%$storehash)) {
                   6911:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  6912:    }
1.715     albertel 6913:    $items=~s/\&$//;
1.716     albertel 6914:    my $esc_symb=&escape($symb);
                   6915:    my $esc_v=&escape($version);
1.715     albertel 6916:    my $reply =
1.716     albertel 6917:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 6918: 	      $uhome);
1.1172.2.59  raeburn  6919:    if (($tolog) && ($reply eq 'ok')) {
                   6920:        my $namevalue='';
                   6921:        foreach my $key (keys(%{$storehash})) {
                   6922:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   6923:        }
                   6924:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   6925:                      '&host='.&escape($perlvar{'lonHostID'}).
                   6926:                      '&version='.$esc_v.
                   6927:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   6928:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   6929:    }
1.715     albertel 6930:    if ($reply eq 'unknown_cmd') {
1.716     albertel 6931:        # gfall back to way things use to be done
1.715     albertel 6932:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   6933: 			    $uname);
1.524     raeburn  6934:    }
1.715     albertel 6935:    return $reply;
                   6936: }
                   6937: 
                   6938: sub old_putstore {
1.716     albertel 6939:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   6940:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6941:     if (!$uname) { $uname=$env{'user.name'}; }
                   6942:     my $uhome=&homeserver($uname,$udomain);
                   6943:     my %newstorehash;
1.800     albertel 6944:     foreach my $item (keys(%$storehash)) {
                   6945: 	my $key = $version.':'.&escape($symb).':'.$item;
                   6946: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 6947:     }
                   6948:     my $items='';
                   6949:     my %allitems = ();
1.800     albertel 6950:     foreach my $item (keys(%newstorehash)) {
                   6951: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 6952: 	    my $key = $1.':keys:'.$2;
                   6953: 	    $allitems{$key} .= $3.':';
                   6954: 	}
1.800     albertel 6955: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 6956:     }
1.800     albertel 6957:     foreach my $item (keys(%allitems)) {
                   6958: 	$allitems{$item} =~ s/\:$//;
                   6959: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 6960:     }
                   6961:     $items=~s/\&$//;
                   6962:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  6963: }
                   6964: 
1.47      www      6965: # ------------------------------------------------------ critical put interface
                   6966: 
                   6967: sub cput {
1.134     albertel 6968:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6969:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6970:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6971:    my $uhome=&homeserver($uname,$udomain);
1.47      www      6972:    my $items='';
1.800     albertel 6973:    foreach my $item (keys(%$storehash)) {
                   6974:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6975:    }
1.47      www      6976:    $items=~s/\&$//;
1.134     albertel 6977:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6978: }
                   6979: 
                   6980: # -------------------------------------------------------------- eget interface
                   6981: 
                   6982: sub eget {
1.133     albertel 6983:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6984:    my $items='';
1.800     albertel 6985:    foreach my $item (@$storearr) {
                   6986:        $items.=&escape($item).'&';
1.191     harris41 6987:    }
1.12      www      6988:    $items=~s/\&$//;
1.620     albertel 6989:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6990:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6991:    my $uhome=&homeserver($uname,$udomain);
                   6992:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6993:    my @pairs=split(/\&/,$rep);
                   6994:    my %returnhash=();
1.42      www      6995:    my $i=0;
1.800     albertel 6996:    foreach my $item (@$storearr) {
                   6997:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6998:       $i++;
1.191     harris41 6999:    }
1.12      www      7000:    return %returnhash;
                   7001: }
                   7002: 
1.667     albertel 7003: # ------------------------------------------------------------ tmpput interface
                   7004: sub tmpput {
1.802     raeburn  7005:     my ($storehash,$server,$context)=@_;
1.667     albertel 7006:     my $items='';
1.800     albertel 7007:     foreach my $item (keys(%$storehash)) {
                   7008: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 7009:     }
                   7010:     $items=~s/\&$//;
1.802     raeburn  7011:     if (defined($context)) {
                   7012:         $items .= ':'.&escape($context);
                   7013:     }
1.667     albertel 7014:     return &reply("tmpput:$items",$server);
                   7015: }
                   7016: 
                   7017: # ------------------------------------------------------------ tmpget interface
                   7018: sub tmpget {
1.688     albertel 7019:     my ($token,$server)=@_;
                   7020:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7021:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 7022:     my %returnhash;
1.1172.2.85  raeburn  7023:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   7024:         return %returnhash;
                   7025:     }
1.667     albertel 7026:     foreach my $item (split(/\&/,$rep)) {
                   7027: 	my ($key,$value)=split(/=/,$item);
                   7028: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   7029:     }
                   7030:     return %returnhash;
                   7031: }
                   7032: 
1.1113    raeburn  7033: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 7034: sub tmpdel {
                   7035:     my ($token,$server)=@_;
                   7036:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7037:     return &reply("tmpdel:$token",$server);
                   7038: }
                   7039: 
1.1172.2.13  raeburn  7040: # ------------------------------------------------------------ get_timebased_id
                   7041: 
                   7042: sub get_timebased_id {
                   7043:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   7044:         $maxtries) = @_;
                   7045:     my ($newid,$error,$dellock);
                   7046:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   7047:         return ('','ok','invalid call to get suffix');
                   7048:     }
                   7049: 
                   7050: # set defaults for any optional args for which values were not supplied
                   7051:     if ($who eq '') {
                   7052:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   7053:     }
                   7054:     if (!$locktries) {
                   7055:         $locktries = 3;
                   7056:     }
                   7057:     if (!$maxtries) {
                   7058:         $maxtries = 10;
                   7059:     }
                   7060: 
                   7061:     if (($cdom eq '') || ($cnum eq '')) {
                   7062:         if ($env{'request.course.id'}) {
                   7063:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7064:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7065:         }
                   7066:         if (($cdom eq '') || ($cnum eq '')) {
                   7067:             return ('','ok','call to get suffix not in course context');
                   7068:         }
                   7069:     }
                   7070: 
                   7071: # construct locking item
                   7072:     my $lockhash = {
                   7073:                       $prefix."\0".'locked_'.$keyid => $who,
                   7074:                    };
                   7075:     my $tries = 0;
                   7076: 
                   7077: # attempt to get lock on nohist_$namespace file
                   7078:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7079:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   7080:         $tries ++;
                   7081:         sleep 1;
                   7082:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7083:     }
                   7084: 
                   7085: # attempt to get unique identifier, based on current timestamp
                   7086:     if ($gotlock eq 'ok') {
                   7087:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   7088:         my $id = time;
                   7089:         $newid = $id;
1.1172.2.56  raeburn  7090:         if ($idtype eq 'addcode') {
                   7091:             $newid .= &sixnum_code();
                   7092:         }
1.1172.2.13  raeburn  7093:         my $idtries = 0;
                   7094:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   7095:             if ($idtype eq 'concat') {
                   7096:                 $newid = $id.$idtries;
1.1172.2.56  raeburn  7097:             } elsif ($idtype eq 'addcode') {
                   7098:                 $newid = $newid.&sixnum_code();
1.1172.2.13  raeburn  7099:             } else {
                   7100:                 $newid ++;
                   7101:             }
                   7102:             $idtries ++;
                   7103:         }
                   7104:         if (!exists($inuse{$prefix."\0".$newid})) {
                   7105:             my %new_item =  (
                   7106:                               $prefix."\0".$newid => $who,
                   7107:                             );
                   7108:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   7109:                                                  $cdom,$cnum);
                   7110:             if ($putresult ne 'ok') {
                   7111:                 undef($newid);
                   7112:                 $error = 'error saving new item: '.$putresult;
                   7113:             }
                   7114:         } else {
1.1172.2.56  raeburn  7115:              undef($newid);
1.1172.2.13  raeburn  7116:              $error = ('error: no unique suffix available for the new item ');
                   7117:         }
                   7118: #  remove lock
                   7119:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   7120:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   7121:     } else {
                   7122:         $error = "error: could not obtain lockfile\n";
                   7123:         $dellock = 'ok';
1.1172.2.58  raeburn  7124:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   7125:             $dellock = 'nolock';
                   7126:         }
1.1172.2.13  raeburn  7127:     }
                   7128:     return ($newid,$dellock,$error);
                   7129: }
                   7130: 
1.1172.2.56  raeburn  7131: sub sixnum_code {
                   7132:     my $code;
                   7133:     for (0..6) {
                   7134:         $code .= int( rand(9) );
                   7135:     }
                   7136:     return $code;
                   7137: }
                   7138: 
1.765     albertel 7139: # -------------------------------------------------- portfolio access checking
                   7140: 
                   7141: sub portfolio_access {
1.1172.2.77  raeburn  7142:     my ($requrl,$clientip) = @_;
1.765     albertel 7143:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77  raeburn  7144:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  7145:     if ($result) {
                   7146:         my %setters;
                   7147:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7148:             my ($startblock,$endblock) =
                   7149:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   7150:             if ($startblock && $endblock) {
                   7151:                 return 'B';
                   7152:             }
                   7153:         } else {
                   7154:             my ($startblock,$endblock) =
                   7155:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   7156:             if ($startblock && $endblock) {
                   7157:                 return 'B';
                   7158:             }
                   7159:         }
                   7160:     }
1.765     albertel 7161:     if ($result eq 'ok') {
1.766     albertel 7162:        return 'F';
1.765     albertel 7163:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 7164:        return 'A';
1.765     albertel 7165:     }
1.766     albertel 7166:     return '';
1.765     albertel 7167: }
                   7168: 
                   7169: sub get_portfolio_access {
1.1172.2.77  raeburn  7170:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 7171: 
                   7172:     if (!ref($access_hash)) {
                   7173: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   7174: 	my %access_controls = &get_access_controls($current_perms,$group,
                   7175: 						   $file_name);
                   7176: 	$access_hash = $access_controls{$file_name};
                   7177:     }
                   7178: 
1.1172.2.77  raeburn  7179:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 7180:     my $now = time;
                   7181:     if (ref($access_hash) eq 'HASH') {
                   7182:         foreach my $key (keys(%{$access_hash})) {
                   7183:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7184:             if ($start > $now) {
                   7185:                 next;
                   7186:             }
                   7187:             if ($end && $end<$now) {
                   7188:                 next;
                   7189:             }
                   7190:             if ($scope eq 'public') {
                   7191:                 $public = $key;
                   7192:                 last;
                   7193:             } elsif ($scope eq 'guest') {
                   7194:                 $guest = $key;
                   7195:             } elsif ($scope eq 'domains') {
                   7196:                 push(@domains,$key);
                   7197:             } elsif ($scope eq 'users') {
                   7198:                 push(@users,$key);
                   7199:             } elsif ($scope eq 'course') {
                   7200:                 push(@courses,$key);
                   7201:             } elsif ($scope eq 'group') {
                   7202:                 push(@groups,$key);
1.1172.2.77  raeburn  7203:             } elsif ($scope eq 'ip') {
                   7204:                 push(@ips,$key);
1.765     albertel 7205:             }
                   7206:         }
                   7207:         if ($public) {
                   7208:             return 'ok';
1.1172.2.77  raeburn  7209:         } elsif (@ips > 0) {
                   7210:             my $allowed;
                   7211:             foreach my $ipkey (@ips) {
                   7212:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   7213:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   7214:                         $allowed = 1;
                   7215:                         last;
                   7216:                     }
                   7217:                 }
                   7218:             }
                   7219:             if ($allowed) {
                   7220:                 return 'ok';
                   7221:             }
1.765     albertel 7222:         }
                   7223:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7224:             if ($guest) {
                   7225:                 return $guest;
                   7226:             }
                   7227:         } else {
                   7228:             if (@domains > 0) {
                   7229:                 foreach my $domkey (@domains) {
                   7230:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   7231:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   7232:                             return 'ok';
                   7233:                         }
                   7234:                     }
                   7235:                 }
                   7236:             }
                   7237:             if (@users > 0) {
                   7238:                 foreach my $userkey (@users) {
1.865     raeburn  7239:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   7240:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   7241:                             if (ref($item) eq 'HASH') {
                   7242:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   7243:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   7244:                                     return 'ok';
                   7245:                                 }
                   7246:                             }
                   7247:                         }
                   7248:                     } 
1.765     albertel 7249:                 }
                   7250:             }
                   7251:             my %roleshash;
                   7252:             my @courses_and_groups = @courses;
                   7253:             push(@courses_and_groups,@groups); 
                   7254:             if (@courses_and_groups > 0) {
                   7255:                 my (%allgroups,%allroles); 
                   7256:                 my ($start,$end,$role,$sec,$group);
                   7257:                 foreach my $envkey (%env) {
1.1060    raeburn  7258:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7259:                         my $cid = $2.'_'.$3; 
                   7260:                         if ($1 eq 'gr') {
                   7261:                             $group = $4;
                   7262:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7263:                         } else {
                   7264:                             if ($4 eq '') {
                   7265:                                 $sec = 'none';
                   7266:                             } else {
                   7267:                                 $sec = $4;
                   7268:                             }
                   7269:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7270:                         }
1.811     albertel 7271:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7272:                         my $cid = $2.'_'.$3;
                   7273:                         if ($4 eq '') {
                   7274:                             $sec = 'none';
                   7275:                         } else {
                   7276:                             $sec = $4;
                   7277:                         }
                   7278:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7279:                     }
                   7280:                 }
                   7281:                 if (keys(%allroles) == 0) {
                   7282:                     return;
                   7283:                 }
                   7284:                 foreach my $key (@courses_and_groups) {
                   7285:                     my %content = %{$$access_hash{$key}};
                   7286:                     my $cnum = $content{'number'};
                   7287:                     my $cdom = $content{'domain'};
                   7288:                     my $cid = $cdom.'_'.$cnum;
                   7289:                     if (!exists($allroles{$cid})) {
                   7290:                         next;
                   7291:                     }    
                   7292:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7293:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7294:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7295:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7296:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7297:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7298:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7299:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7300:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7301:                                         if (grep/^all$/,@sections) {
                   7302:                                             return 'ok';
                   7303:                                         } else {
                   7304:                                             if (grep/^$sec$/,@sections) {
                   7305:                                                 return 'ok';
                   7306:                                             }
                   7307:                                         }
                   7308:                                     }
                   7309:                                 }
                   7310:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7311:                                     if (grep/^none$/,@groups) {
                   7312:                                         return 'ok';
                   7313:                                     }
                   7314:                                 } else {
                   7315:                                     if (grep/^all$/,@groups) {
                   7316:                                         return 'ok';
                   7317:                                     } 
                   7318:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7319:                                         if (grep/^$group$/,@groups) {
                   7320:                                             return 'ok';
                   7321:                                         }
                   7322:                                     }
                   7323:                                 } 
                   7324:                             }
                   7325:                         }
                   7326:                     }
                   7327:                 }
                   7328:             }
                   7329:             if ($guest) {
                   7330:                 return $guest;
                   7331:             }
                   7332:         }
                   7333:     }
                   7334:     return;
                   7335: }
                   7336: 
                   7337: sub course_group_datechecker {
                   7338:     my ($dates,$now,$status) = @_;
                   7339:     my ($start,$end) = split(/\./,$dates);
                   7340:     if (!$start && !$end) {
                   7341:         return 'ok';
                   7342:     }
                   7343:     if (grep/^active$/,@{$status}) {
                   7344:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7345:             return 'ok';
                   7346:         }
                   7347:     }
                   7348:     if (grep/^previous$/,@{$status}) {
                   7349:         if ($end > $now ) {
                   7350:             return 'ok';
                   7351:         }
                   7352:     }
                   7353:     if (grep/^future$/,@{$status}) {
                   7354:         if ($start > $now) {
                   7355:             return 'ok';
                   7356:         }
                   7357:     }
                   7358:     return; 
                   7359: }
                   7360: 
                   7361: sub parse_portfolio_url {
                   7362:     my ($url) = @_;
                   7363: 
                   7364:     my ($type,$udom,$unum,$group,$file_name);
                   7365:     
1.823     albertel 7366:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7367: 	$type = 1;
                   7368:         $udom = $1;
                   7369:         $unum = $2;
                   7370:         $file_name = $3;
1.823     albertel 7371:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7372: 	$type = 2;
                   7373:         $udom = $1;
                   7374:         $unum = $2;
                   7375:         $group = $3;
                   7376:         $file_name = $3.'/'.$4;
                   7377:     }
                   7378:     if (wantarray) {
                   7379: 	return ($type,$udom,$unum,$file_name,$group);
                   7380:     }
                   7381:     return $type;
                   7382: }
                   7383: 
                   7384: sub is_portfolio_url {
                   7385:     my ($url) = @_;
                   7386:     return scalar(&parse_portfolio_url($url));
                   7387: }
                   7388: 
1.798     raeburn  7389: sub is_portfolio_file {
                   7390:     my ($file) = @_;
1.820     raeburn  7391:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7392:         return 1;
                   7393:     }
                   7394:     return;
                   7395: }
                   7396: 
1.976     raeburn  7397: sub usertools_access {
1.1084    raeburn  7398:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7399:     my ($access,%tools);
                   7400:     if ($context eq '') {
                   7401:         $context = 'tools';
                   7402:     }
                   7403:     if ($context eq 'requestcourses') {
                   7404:         %tools = (
                   7405:                       official   => 1,
                   7406:                       unofficial => 1,
1.1006    raeburn  7407:                       community  => 1,
1.1172.2.37  raeburn  7408:                       textbook   => 1,
1.985     raeburn  7409:                  );
1.1172.2.9  raeburn  7410:     } elsif ($context eq 'requestauthor') {
                   7411:         %tools = (
                   7412:                       requestauthor => 1,
                   7413:                  );
1.985     raeburn  7414:     } else {
                   7415:         %tools = (
                   7416:                       aboutme   => 1,
                   7417:                       blog      => 1,
1.1172.2.6  raeburn  7418:                       webdav    => 1,
1.985     raeburn  7419:                       portfolio => 1,
                   7420:                  );
                   7421:     }
1.976     raeburn  7422:     return if (!defined($tools{$tool}));
                   7423: 
1.1172.2.35  raeburn  7424:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7425:         $udom = $env{'user.domain'};
                   7426:         $uname = $env{'user.name'};
                   7427:     }
                   7428: 
1.978     raeburn  7429:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7430:         if ($action ne 'reload') {
1.985     raeburn  7431:             if ($context eq 'requestcourses') {
                   7432:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  7433:             } elsif ($context eq 'requestauthor') {
                   7434:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7435:             } else {
                   7436:                 return $env{'environment.availabletools.'.$tool};
                   7437:             }
                   7438:         }
1.976     raeburn  7439:     }
                   7440: 
1.1172.2.9  raeburn  7441:     my ($toolstatus,$inststatus,$envkey);
                   7442:     if ($context eq 'requestauthor') {
                   7443:         $envkey = $context;
                   7444:     } else {
                   7445:         $envkey = $context.'.'.$tool;
                   7446:     }
1.976     raeburn  7447: 
1.985     raeburn  7448:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7449:          ($action ne 'reload')) {
1.1172.2.9  raeburn  7450:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7451:         $inststatus = $env{'environment.inststatus'};
                   7452:     } else {
1.1084    raeburn  7453:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  7454:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7455:             $inststatus = $userenvref->{'inststatus'};
                   7456:         } else {
1.1172.2.9  raeburn  7457:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7458:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7459:             $inststatus = $userenv{'inststatus'};
                   7460:         }
1.976     raeburn  7461:     }
                   7462: 
                   7463:     if ($toolstatus ne '') {
                   7464:         if ($toolstatus) {
                   7465:             $access = 1;
                   7466:         } else {
                   7467:             $access = 0;
                   7468:         }
                   7469:         return $access;
                   7470:     }
                   7471: 
1.1084    raeburn  7472:     my ($is_adv,%domdef);
                   7473:     if (ref($is_advref) eq 'HASH') {
                   7474:         $is_adv = $is_advref->{'is_adv'};
                   7475:     } else {
                   7476:         $is_adv = &is_advanced_user($udom,$uname);
                   7477:     }
                   7478:     if (ref($domdefref) eq 'HASH') {
                   7479:         %domdef = %{$domdefref};
                   7480:     } else {
                   7481:         %domdef = &get_domain_defaults($udom);
                   7482:     }
1.976     raeburn  7483:     if (ref($domdef{$tool}) eq 'HASH') {
                   7484:         if ($is_adv) {
                   7485:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7486:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7487:                     $access = 1;
                   7488:                 } else {
                   7489:                     $access = 0;
                   7490:                 }
                   7491:                 return $access;
                   7492:             }
                   7493:         }
                   7494:         if ($inststatus ne '') {
                   7495:             my ($hasaccess,$hasnoaccess);
                   7496:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7497:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7498:                     if ($domdef{$tool}{$affiliation}) {
                   7499:                         $hasaccess = 1;
                   7500:                     } else {
                   7501:                         $hasnoaccess = 1;
                   7502:                     }
                   7503:                 }
                   7504:             }
                   7505:             if ($hasaccess || $hasnoaccess) {
                   7506:                 if ($hasaccess) {
                   7507:                     $access = 1;
                   7508:                 } elsif ($hasnoaccess) {
                   7509:                     $access = 0; 
                   7510:                 }
                   7511:                 return $access;
                   7512:             }
                   7513:         } else {
                   7514:             if ($domdef{$tool}{'default'} ne '') {
                   7515:                 if ($domdef{$tool}{'default'}) {
                   7516:                     $access = 1;
                   7517:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7518:                     $access = 0;
                   7519:                 }
                   7520:                 return $access;
                   7521:             }
                   7522:         }
                   7523:     } else {
1.1172.2.6  raeburn  7524:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7525:             $access = 1;
                   7526:         } else {
                   7527:             $access = 0;
                   7528:         }
1.976     raeburn  7529:         return $access;
                   7530:     }
                   7531: }
                   7532: 
1.1050    raeburn  7533: sub is_course_owner {
                   7534:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7535:     if (($udom eq '') || ($uname eq '')) {
                   7536:         $udom = $env{'user.domain'};
                   7537:         $uname = $env{'user.name'};
                   7538:     }
                   7539:     unless (($udom eq '') || ($uname eq '')) {
                   7540:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7541:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7542:                 return 1;
                   7543:             } else {
                   7544:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7545:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7546:                     return 1;
                   7547:                 }
                   7548:             }
                   7549:         }
                   7550:     }
                   7551:     return;
                   7552: }
                   7553: 
1.976     raeburn  7554: sub is_advanced_user {
                   7555:     my ($udom,$uname) = @_;
1.1085    raeburn  7556:     if ($udom ne '' && $uname ne '') {
                   7557:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7558:             if (wantarray) {
                   7559:                 return ($env{'user.adv'},$env{'user.author'});
                   7560:             } else {
                   7561:                 return $env{'user.adv'};
                   7562:             }
1.1085    raeburn  7563:         }
                   7564:     }
1.976     raeburn  7565:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7566:     my %allroles;
1.1128    raeburn  7567:     my ($is_adv,$is_author);
1.976     raeburn  7568:     foreach my $role (keys(%roleshash)) {
                   7569:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7570:         my $area = '/'.$tdomain.'/'.$trest;
                   7571:         if ($sec ne '') {
                   7572:             $area .= '/'.$sec;
                   7573:         }
                   7574:         if (($area ne '') && ($trole ne '')) {
                   7575:             my $spec=$trole.'.'.$area;
                   7576:             if ($trole =~ /^cr\//) {
                   7577:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7578:             } elsif ($trole ne 'gr') {
                   7579:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7580:             }
1.1128    raeburn  7581:             if ($trole eq 'au') {
                   7582:                 $is_author = 1;
                   7583:             }
1.976     raeburn  7584:         }
                   7585:     }
                   7586:     foreach my $role (keys(%allroles)) {
                   7587:         last if ($is_adv);
                   7588:         foreach my $item (split(/:/,$allroles{$role})) {
                   7589:             if ($item ne '') {
                   7590:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7591:                 if ($privilege eq 'adv') {
                   7592:                     $is_adv = 1;
                   7593:                     last;
                   7594:                 }
                   7595:             }
                   7596:         }
                   7597:     }
1.1128    raeburn  7598:     if (wantarray) {
                   7599:         return ($is_adv,$is_author);
                   7600:     }
1.976     raeburn  7601:     return $is_adv;
                   7602: }
1.798     raeburn  7603: 
1.1035    raeburn  7604: sub check_can_request {
1.1036    raeburn  7605:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  7606:     my $canreq = 0;
                   7607:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7608:     my @options = ('approval','validate','autolimit');
                   7609:     my $optregex = join('|',@options);
                   7610:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7611:         foreach my $type (@{$types}) {
                   7612:             if (&usertools_access($env{'user.name'},
                   7613:                                   $env{'user.domain'},
                   7614:                                   $type,undef,'requestcourses')) {
                   7615:                 $canreq ++;
1.1036    raeburn  7616:                 if (ref($request_domains) eq 'HASH') {
                   7617:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   7618:                 }
1.1035    raeburn  7619:                 if ($dom eq $env{'user.domain'}) {
                   7620:                     $can_request->{$type} = 1;
                   7621:                 }
                   7622:             }
                   7623:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   7624:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7625:                 if (@curr > 0) {
1.1036    raeburn  7626:                     foreach my $item (@curr) {
                   7627:                         if (ref($request_domains) eq 'HASH') {
                   7628:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7629:                             if ($otherdom ne '') {
                   7630:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7631:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7632:                                         push(@{$request_domains->{$type}},$otherdom);
                   7633:                                     }
                   7634:                                 } else {
                   7635:                                     push(@{$request_domains->{$type}},$otherdom);
                   7636:                                 }
                   7637:                             }
                   7638:                         }
                   7639:                     }
                   7640:                     unless($dom eq $env{'user.domain'}) {
                   7641:                         $canreq ++;
1.1035    raeburn  7642:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7643:                             $can_request->{$type} = 1;
                   7644:                         }
                   7645:                     }
                   7646:                 }
                   7647:             }
                   7648:         }
                   7649:     }
                   7650:     return $canreq;
                   7651: }
                   7652: 
1.341     www      7653: # ---------------------------------------------- Custom access rule evaluation
                   7654: 
                   7655: sub customaccess {
                   7656:     my ($priv,$uri)=@_;
1.807     albertel 7657:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7658:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7659:     $udom = &LONCAPA::clean_domain($udom);
                   7660:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7661:     my $access=0;
1.800     albertel 7662:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7663: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7664: 	if ($type eq 'user') {
                   7665: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7666: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7667: 		if ($tdom) {
                   7668: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7669: 		}
1.896     albertel 7670: 		if ($tuname) {
                   7671: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7672: 		}
                   7673: 		$access=($effect eq 'allow');
                   7674: 		last;
                   7675: 	    }
                   7676: 	} else {
                   7677: 	    if ($role) {
                   7678: 		if ($role ne $urole) { next; }
                   7679: 	    }
                   7680: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7681: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7682: 		if ($tdom) {
                   7683: 		    if ($tdom ne $udom) { next; }
                   7684: 		}
                   7685: 		if ($tcrs) {
                   7686: 		    if ($tcrs ne $ucrs) { next; }
                   7687: 		}
                   7688: 		if ($tsec) {
                   7689: 		    if ($tsec ne $usec) { next; }
                   7690: 		}
                   7691: 		$access=($effect eq 'allow');
                   7692: 		last;
                   7693: 	    }
                   7694: 	    if ($realm eq '' && $role eq '') {
                   7695: 		$access=($effect eq 'allow');
                   7696: 	    }
1.402     bowersj2 7697: 	}
1.341     www      7698:     }
                   7699:     return $access;
                   7700: }
                   7701: 
1.103     harris41 7702: # ------------------------------------------------- Check for a user privilege
1.12      www      7703: 
                   7704: sub allowed {
1.1172.2.65  raeburn  7705:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 7706:     my $ver_orguri=$uri;
1.439     www      7707:     $uri=&deversion($uri);
1.152     www      7708:     my $orguri=$uri;
1.52      www      7709:     $uri=&declutter($uri);
1.809     raeburn  7710: 
1.810     raeburn  7711:     if ($priv eq 'evb') {
                   7712: # Evade communication block restrictions for specified role in a course
                   7713:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   7714:             return $1;
                   7715:         } else {
                   7716:             return;
                   7717:         }
                   7718:     }
                   7719: 
1.620     albertel 7720:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      7721: # Free bre access to adm and meta resources
1.775     albertel 7722:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 7723: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   7724: 	&& ($priv eq 'bre')) {
1.14      www      7725: 	return 'F';
1.159     www      7726:     }
                   7727: 
1.545     banghart 7728: # Free bre access to user's own portfolio contents
1.714     raeburn  7729:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  7730:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  7731: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  7732:         my %setters;
                   7733:         my ($startblock,$endblock) = 
                   7734:             &Apache::loncommon::blockcheck(\%setters,'port');
                   7735:         if ($startblock && $endblock) {
                   7736:             return 'B';
                   7737:         } else {
                   7738:             return 'F';
                   7739:         }
1.545     banghart 7740:     }
                   7741: 
1.762     raeburn  7742: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  7743:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   7744:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   7745:         if (exists($env{'request.course.id'})) {
                   7746:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7747:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7748:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   7749:                 my $courseprivid=$env{'request.course.id'};
                   7750:                 $courseprivid=~s/\_/\//;
                   7751:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   7752:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   7753:                     return $1; 
1.762     raeburn  7754:                 } else {
                   7755:                     if ($env{'request.course.sec'}) {
                   7756:                         $courseprivid.='/'.$env{'request.course.sec'};
                   7757:                     }
                   7758:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   7759:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   7760:                         return $2;
                   7761:                     }
1.714     raeburn  7762:                 }
                   7763:             }
                   7764:         }
                   7765:     }
                   7766: 
1.159     www      7767: # Free bre to public access
                   7768: 
                   7769:     if ($priv eq 'bre') {
1.238     www      7770:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 7771: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      7772:            return 'F'; 
                   7773:         }
1.238     www      7774:         if ($copyright eq 'priv') {
                   7775:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7776: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      7777: 		return '';
                   7778:             }
                   7779:         }
                   7780:         if ($copyright eq 'domain') {
                   7781:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7782: 	    unless (($env{'user.domain'} eq $1) ||
                   7783:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7784: 		return '';
                   7785:             }
1.262     matthew  7786:         }
1.620     albertel 7787:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7788:             # Library role, so allow browsing of resources in this domain.
                   7789:             return 'F';
1.238     www      7790:         }
1.341     www      7791:         if ($copyright eq 'custom') {
                   7792: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7793:         }
1.14      www      7794:     }
1.264     matthew  7795:     # Domain coordinator is trying to create a course
1.620     albertel 7796:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7797:         # uri is the requested domain in this case.
                   7798:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7799:         # a role of dc for the domain in question.
1.620     albertel 7800:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7801:     }
1.29      www      7802: 
1.52      www      7803:     my $thisallowed='';
                   7804:     my $statecond=0;
                   7805:     my $courseprivid='';
                   7806: 
1.1039    raeburn  7807:     my $ownaccess;
1.1043    raeburn  7808:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7809:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7810:         if ($uri eq '') {
                   7811:             $ownaccess = 1;
                   7812:         } else {
                   7813:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7814:                 my $udom = $env{'user.domain'};
                   7815:                 my $uname = $env{'user.name'};
                   7816:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7817:                     $ownaccess = 1;
1.1040    raeburn  7818:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7819:                     unless ($uri =~ m{\.\./}) {
                   7820:                         $ownaccess = 1;
                   7821:                     }
                   7822:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   7823:                     my $now = time;
                   7824:                     if ($uri =~ m{^([^/]+)/?$}) {
                   7825:                         my $adom = $1;
                   7826:                         foreach my $key (keys(%env)) {
1.1042    raeburn  7827:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  7828:                                 my ($start,$end) = split('.',$env{$key});
                   7829:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7830:                                     $ownaccess = 1;
                   7831:                                     last;
                   7832:                                 }
                   7833:                             }
                   7834:                         }
                   7835:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   7836:                         my $adom = $1;
                   7837:                         my $aname = $2;
1.1042    raeburn  7838:                         foreach my $role ('ca','aa') { 
                   7839:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   7840:                                 my ($start,$end) =
                   7841:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   7842:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7843:                                     $ownaccess = 1;
                   7844:                                     last;
                   7845:                                 }
1.1039    raeburn  7846:                             }
                   7847:                         }
                   7848:                     }
                   7849:                 }
                   7850:             }
                   7851:         }
                   7852:     }
                   7853: 
1.52      www      7854: # Course
                   7855: 
1.620     albertel 7856:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7857:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7858:             $thisallowed.=$1;
                   7859:         }
1.52      www      7860:     }
1.29      www      7861: 
1.52      www      7862: # Domain
                   7863: 
1.620     albertel 7864:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 7865:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7866:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7867:             $thisallowed.=$1;
                   7868:         }
1.12      www      7869:     }
1.52      www      7870: 
1.1141    raeburn  7871: # User who is not author or co-author might still be able to edit
                   7872: # resource of an author in the domain (e.g., if Domain Coordinator).
                   7873:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   7874:         (&allowed('mdc',$env{'request.course.id'}))) {
                   7875:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   7876:             $thisallowed.=$1;
                   7877:         }
                   7878:     }
                   7879: 
1.52      www      7880: # Course: uri itself is a course
1.66      www      7881:     my $courseuri=$uri;
                   7882:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      7883:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      7884: 
1.620     albertel 7885:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 7886:        =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.115! raeburn  7887:         if ($priv eq 'mip') {
        !          7888:             my $rem = $1;
        !          7889:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
        !          7890:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
        !          7891:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
        !          7892:                 if ($cdom ne '') {
        !          7893:                     my %passwdconf = &get_passwdconf($cdom);
        !          7894:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
        !          7895:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
        !          7896:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
        !          7897:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
        !          7898:                                 unless (@inststatuses) {
        !          7899:                                     @inststatuses = ('default');
        !          7900:                                 }
        !          7901:                                 foreach my $status (@inststatuses) {
        !          7902:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
        !          7903:                                         $thisallowed.=$rem;
        !          7904:                                     }
        !          7905:                                 }
        !          7906:                             }
        !          7907:                         }
        !          7908:                     }
        !          7909:                 }
        !          7910:             }
        !          7911:         } else {
        !          7912:             unless (($priv eq 'bro') && (!$ownaccess)) {
        !          7913:                 $thisallowed.=$1;
        !          7914:             }
1.1039    raeburn  7915:         }
1.12      www      7916:     }
1.29      www      7917: 
1.665     albertel 7918: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 7919: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 7920:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 7921: 	$thisallowed='';
1.671     raeburn  7922:         my ($match)=&is_on_map($uri);
                   7923:         if ($match) {
                   7924:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   7925:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65  raeburn  7926:                 my $value = $1;
                   7927:                 if ($noblockcheck) {
                   7928:                     $thisallowed.=$value;
1.1162    raeburn  7929:                 } else {
1.1172.2.65  raeburn  7930:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7931:                     if (@blockers > 0) {
                   7932:                         $thisallowed = 'B';
                   7933:                     } else {
                   7934:                         $thisallowed.=$value;
                   7935:                     }
1.1162    raeburn  7936:                 }
1.671     raeburn  7937:             }
                   7938:         } else {
1.705     albertel 7939:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  7940:             if ($refuri) {
                   7941:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  7942:                     $thisallowed='F';
1.671     raeburn  7943:                 } else {
                   7944:                     $refuri=&declutter($refuri);
                   7945:                     my ($match) = &is_on_map($refuri);
                   7946:                     if ($match) {
1.1172.2.65  raeburn  7947:                         if ($noblockcheck) {
1.1162    raeburn  7948:                             $thisallowed='F';
1.1172.2.65  raeburn  7949:                         } else {
                   7950:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7951:                             if (@blockers > 0) {
                   7952:                                 $thisallowed = 'B';
                   7953:                             } else {
                   7954:                                 $thisallowed='F';
                   7955:                             }
1.1162    raeburn  7956:                         }
1.671     raeburn  7957:                     }
1.669     raeburn  7958:                 }
1.671     raeburn  7959:             }
                   7960:         }
1.314     www      7961:     }
1.492     albertel 7962: 
1.766     albertel 7963:     if ($priv eq 'bre'
                   7964: 	&& $thisallowed ne 'F' 
                   7965: 	&& $thisallowed ne '2'
                   7966: 	&& &is_portfolio_url($uri)) {
1.1172.2.77  raeburn  7967: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 7968:     }
                   7969:     
1.52      www      7970: # Full access at system, domain or course-wide level? Exit.
1.29      www      7971:     if ($thisallowed=~/F/) {
                   7972: 	return 'F';
                   7973:     }
                   7974: 
1.52      www      7975: # If this is generating or modifying users, exit with special codes
1.29      www      7976: 
1.643     www      7977:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   7978: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 7979: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      7980: # no author name given, so this just checks on the general right to make a co-author in this domain
                   7981: 	    unless ($auname) { return $thisallowed; }
                   7982: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 7983: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   7984: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   7985: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   7986: 	}
1.52      www      7987: 	return $thisallowed;
                   7988:     }
                   7989: #
1.103     harris41 7990: # Gathered so far: system, domain and course wide privileges
1.52      www      7991: #
                   7992: # Course: See if uri or referer is an individual resource that is part of 
                   7993: # the course
                   7994: 
1.620     albertel 7995:     if ($env{'request.course.id'}) {
1.232     www      7996: 
1.1172.2.115! raeburn  7997: # If this is modifying password (internal auth) domains must match for user and user's role.
        !          7998: 
        !          7999:         if ($priv eq 'mip') {
        !          8000:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
        !          8001:                 return $thisallowed;
        !          8002:             } else {
        !          8003:                 return '';
        !          8004:             }
        !          8005:         }
        !          8006: 
1.620     albertel 8007:        $courseprivid=$env{'request.course.id'};
                   8008:        if ($env{'request.course.sec'}) {
                   8009:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      8010:        }
                   8011:        $courseprivid=~s/\_/\//;
                   8012:        my $checkreferer=1;
1.232     www      8013:        my ($match,$cond)=&is_on_map($uri);
                   8014:        if ($match) {
                   8015:            $statecond=$cond;
1.620     albertel 8016:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8017:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8018:                my $value = $1;
                   8019:                if ($priv eq 'bre') {
1.1172.2.65  raeburn  8020:                    if ($noblockcheck) {
1.1162    raeburn  8021:                        $thisallowed.=$value;
1.1172.2.65  raeburn  8022:                    } else {
                   8023:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   8024:                        if (@blockers > 0) {
                   8025:                            $thisallowed = 'B';
                   8026:                        } else {
                   8027:                            $thisallowed.=$value;
                   8028:                        }
1.1162    raeburn  8029:                    }
                   8030:                } else {
                   8031:                    $thisallowed.=$value;
                   8032:                }
1.52      www      8033:                $checkreferer=0;
                   8034:            }
1.29      www      8035:        }
1.83      www      8036:        
1.148     www      8037:        if ($checkreferer) {
1.620     albertel 8038: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      8039:             unless ($refuri) {
1.800     albertel 8040:                 foreach my $key (keys(%env)) {
                   8041: 		    if ($key=~/^httpref\..*\*/) {
                   8042: 			my $pattern=$key;
1.156     www      8043:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      8044:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   8045:                         $pattern=~s/\//\\\//g;
1.152     www      8046:                         if ($orguri=~/$pattern/) {
1.800     albertel 8047: 			    $refuri=$env{$key};
1.148     www      8048:                         }
                   8049:                     }
1.191     harris41 8050:                 }
1.148     www      8051:             }
1.232     www      8052: 
1.148     www      8053:          if ($refuri) { 
1.152     www      8054: 	  $refuri=&declutter($refuri);
1.232     www      8055:           my ($match,$cond)=&is_on_map($refuri);
                   8056:             if ($match) {
                   8057:               my $refstatecond=$cond;
1.620     albertel 8058:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8059:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8060:                   my $value = $1;
                   8061:                   if ($priv eq 'bre') {
1.1172.2.65  raeburn  8062:                       if ($noblockcheck) {
1.1162    raeburn  8063:                           $thisallowed.=$value;
1.1172.2.65  raeburn  8064:                       } else {
                   8065:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   8066:                           if (@blockers > 0) {
                   8067:                               $thisallowed = 'B';
                   8068:                           } else {
                   8069:                               $thisallowed.=$value;
                   8070:                           }
1.1162    raeburn  8071:                       }
                   8072:                   } else {
                   8073:                       $thisallowed.=$value;
                   8074:                   }
1.53      www      8075:                   $uri=$refuri;
                   8076:                   $statecond=$refstatecond;
1.52      www      8077:               }
                   8078:           }
1.148     www      8079:         }
1.29      www      8080:        }
1.52      www      8081:    }
1.29      www      8082: 
1.52      www      8083: #
1.103     harris41 8084: # Gathered now: all privileges that could apply, and condition number
1.52      www      8085: # 
                   8086: #
                   8087: # Full or no access?
                   8088: #
1.29      www      8089: 
1.52      www      8090:     if ($thisallowed=~/F/) {
                   8091: 	return 'F';
                   8092:     }
1.29      www      8093: 
1.52      www      8094:     unless ($thisallowed) {
                   8095:         return '';
                   8096:     }
1.29      www      8097: 
1.52      www      8098: # Restrictions exist, deal with them
                   8099: #
                   8100: #   C:according to course preferences
                   8101: #   R:according to resource settings
                   8102: #   L:unless locked
                   8103: #   X:according to user session state
                   8104: #
                   8105: 
                   8106: # Possibly locked functionality, check all courses
1.54      www      8107: # Locks might take effect only after 10 minutes cache expiration for other
                   8108: # courses, and 2 minutes for current course
1.52      www      8109: 
                   8110:     my $envkey;
                   8111:     if ($thisallowed=~/L/) {
1.1000    raeburn  8112:         foreach $envkey (keys(%env)) {
1.54      www      8113:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   8114:                my $courseid=$2;
                   8115:                my $roleid=$1.'.'.$2;
1.92      www      8116:                $courseid=~s/^\///;
1.54      www      8117:                my $expiretime=600;
1.620     albertel 8118:                if ($env{'request.role'} eq $roleid) {
1.54      www      8119: 		  $expiretime=120;
                   8120:                }
                   8121: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   8122:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 8123:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 8124: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      8125:                }
1.620     albertel 8126:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8127:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   8128: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   8129:                        &log($env{'user.domain'},$env{'user.name'},
                   8130:                             $env{'user.home'},
1.57      www      8131:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      8132:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8133:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8134: 		       return '';
                   8135:                    }
                   8136:                }
1.620     albertel 8137:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8138:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   8139: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   8140:                        &log($env{'user.domain'},$env{'user.name'},
                   8141:                             $env{'user.home'},
1.57      www      8142:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      8143:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8144:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8145: 		       return '';
                   8146:                    }
                   8147:                }
                   8148: 	   }
1.29      www      8149:        }
1.52      www      8150:     }
                   8151:    
                   8152: #
                   8153: # Rest of the restrictions depend on selected course
                   8154: #
                   8155: 
1.620     albertel 8156:     unless ($env{'request.course.id'}) {
1.766     albertel 8157: 	if ($thisallowed eq 'A') {
                   8158: 	    return 'A';
1.814     raeburn  8159:         } elsif ($thisallowed eq 'B') {
                   8160:             return 'B';
1.766     albertel 8161: 	} else {
                   8162: 	    return '1';
                   8163: 	}
1.52      www      8164:     }
1.29      www      8165: 
1.52      www      8166: #
                   8167: # Now user is definitely in a course
                   8168: #
1.53      www      8169: 
                   8170: 
                   8171: # Course preferences
                   8172: 
                   8173:    if ($thisallowed=~/C/) {
1.620     albertel 8174:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   8175:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   8176:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 8177: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  8178: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8179: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8180: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   8181: 			$env{'request.course.id'});
                   8182: 	   }
1.237     www      8183:            return '';
                   8184:        }
                   8185: 
1.620     albertel 8186:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 8187: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  8188: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8189: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   8190: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   8191: 			$env{'request.course.id'});
                   8192: 	   }
1.54      www      8193:            return '';
                   8194:        }
1.53      www      8195:    }
                   8196: 
                   8197: # Resource preferences
                   8198: 
                   8199:    if ($thisallowed=~/R/) {
1.620     albertel 8200:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 8201:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  8202: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8203: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8204: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   8205: 	   }
                   8206: 	   return '';
1.54      www      8207:        }
1.53      www      8208:    }
1.30      www      8209: 
1.246     www      8210: # Restricted by state or randomout?
1.30      www      8211: 
1.52      www      8212:    if ($thisallowed=~/X/) {
1.620     albertel 8213:       if ($env{'acc.randomout'}) {
1.579     albertel 8214: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 8215:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      8216:             return ''; 
                   8217:          }
1.247     www      8218:       }
                   8219:       if (&condval($statecond)) {
1.52      www      8220: 	 return '2';
                   8221:       } else {
                   8222:          return '';
                   8223:       }
                   8224:    }
1.30      www      8225: 
1.766     albertel 8226:     if ($thisallowed eq 'A') {
                   8227: 	return 'A';
1.814     raeburn  8228:     } elsif ($thisallowed eq 'B') {
                   8229:         return 'B';
1.766     albertel 8230:     }
1.52      www      8231:    return 'F';
1.232     www      8232: }
1.1162    raeburn  8233: 
1.1172.2.13  raeburn  8234: # ------------------------------------------- Check construction space access
                   8235: 
                   8236: sub constructaccess {
                   8237:     my ($url,$setpriv)=@_;
                   8238: 
                   8239: # We do not allow editing of previous versions of files
                   8240:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   8241: 
                   8242: # Get username and domain from URL
                   8243:     my ($ownername,$ownerdomain,$ownerhome);
                   8244: 
                   8245:     ($ownerdomain,$ownername) =
1.1172.2.83  raeburn  8246:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13  raeburn  8247: 
                   8248: # The URL does not really point to any authorspace, forget it
                   8249:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   8250: 
                   8251: # Now we need to see if the user has access to the authorspace of
                   8252: # $ownername at $ownerdomain
                   8253: 
                   8254:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   8255: # Real author for this?
                   8256:        $ownerhome = $env{'user.home'};
                   8257:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   8258:           return ($ownername,$ownerdomain,$ownerhome);
                   8259:        }
                   8260:     } else {
                   8261: # Co-author for this?
                   8262:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   8263:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   8264:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   8265:             return ($ownername,$ownerdomain,$ownerhome);
                   8266:         }
                   8267:     }
                   8268: 
                   8269: # We don't have any access right now. If we are not possibly going to do anything about this,
                   8270: # we might as well leave
                   8271:    unless ($setpriv) { return ''; }
                   8272: 
                   8273: # Backdoor access?
                   8274:     my $allowed=&allowed('eco',$ownerdomain);
                   8275: # Nope
                   8276:     unless ($allowed) { return ''; }
                   8277: # Looks like we may have access, but could be locked by the owner of the construction space
                   8278:     if ($allowed eq 'U') {
                   8279:         my %blocked=&get('environment',['domcoord.author'],
                   8280:                          $ownerdomain,$ownername);
                   8281: # Is blocked by owner
                   8282:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8283:     }
                   8284:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8285: # Grant temporary access
                   8286:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  8287:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  8288:         if (!$update) { $update = $then; }
                   8289:         my $refresh=$env{'user.refresh.time'};
                   8290:         if (!$refresh) { $refresh = $update; }
                   8291:         my $now = time;
                   8292:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8293:                            $now,'ca','constructaccess');
                   8294:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8295:         return($ownername,$ownerdomain,$ownerhome);
                   8296:     }
                   8297: # No business here
                   8298:     return '';
                   8299: }
                   8300: 
1.1172.2.66  raeburn  8301: # ----------------------------------------------------------- Content Blocking
                   8302: 
                   8303: {
                   8304: # Caches for faster Course Contents display where content blocking
                   8305: # is in operation (i.e., interval param set) for timed quiz.
                   8306: #
                   8307: # User for whom data are being temporarily cached.
                   8308: my $cacheduser='';
                   8309: # Cached blockers for this user (a hash of blocking items).
                   8310: my %cachedblockers=();
                   8311: # When the data were last cached.
                   8312: my $cachedlast='';
                   8313: 
                   8314: sub load_all_blockers {
                   8315:     my ($uname,$udom,$blocks)=@_;
                   8316:     if (($uname ne '') && ($udom ne '')) {
                   8317:         if (($cacheduser eq $uname.':'.$udom) &&
                   8318:             (abs($cachedlast-time)<5)) {
                   8319:             return;
                   8320:         }
                   8321:     }
                   8322:     $cachedlast=time;
                   8323:     $cacheduser=$uname.':'.$udom;
                   8324:     %cachedblockers = &get_commblock_resources($blocks);
                   8325: }
                   8326: 
1.1162    raeburn  8327: sub get_comm_blocks {
                   8328:     my ($cdom,$cnum) = @_;
                   8329:     if ($cdom eq '' || $cnum eq '') {
                   8330:         return unless ($env{'request.course.id'});
                   8331:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8332:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8333:     }
                   8334:     my %commblocks;
                   8335:     my $hashid=$cdom.'_'.$cnum;
                   8336:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8337:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8338:         %commblocks = %{$blocksref};
                   8339:     } else {
                   8340:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8341:         my $cachetime = 600;
                   8342:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8343:     }
                   8344:     return %commblocks;
                   8345: }
                   8346: 
1.1172.2.66  raeburn  8347: sub get_commblock_resources {
                   8348:     my ($blocks) = @_;
                   8349:     my %blockers = ();
                   8350:     return %blockers unless ($env{'request.course.id'});
                   8351:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  8352:     my %commblocks;
                   8353:     if (ref($blocks) eq 'HASH') {
                   8354:         %commblocks = %{$blocks};
                   8355:     } else {
                   8356:         %commblocks = &get_comm_blocks();
                   8357:     }
1.1172.2.66  raeburn  8358:     return %blockers unless (keys(%commblocks) > 0);
1.1163    raeburn  8359:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66  raeburn  8360:     return %blockers unless (ref($navmap));
                   8361:     my $now = time;
1.1162    raeburn  8362:     foreach my $block (keys(%commblocks)) {
                   8363:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8364:             my ($start,$end) = ($1,$2);
                   8365:             if ($start <= $now && $end >= $now) {
                   8366:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8367:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8368:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66  raeburn  8369:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8370:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162    raeburn  8371:                             }
                   8372:                         }
                   8373:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66  raeburn  8374:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8375:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8376:                             }
                   8377:                         }
                   8378:                     }
                   8379:                 }
                   8380:             }
                   8381:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8382:             my $item = $1;
1.1163    raeburn  8383:             my @to_test;
1.1162    raeburn  8384:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8385:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.66  raeburn  8386:                     my @interval;
                   8387:                     my $type = 'map';
                   8388:                     if ($item eq 'course') {
                   8389:                         $type = 'course';
                   8390:                         @interval=&EXT("resource.0.interval");
                   8391:                     } else {
                   8392:                         if ($item =~ /___\d+___/) {
                   8393:                             $type = 'resource';
                   8394:                             @interval=&EXT("resource.0.interval",$item);
                   8395:                             if (ref($navmap)) {
                   8396:                                 my $res = $navmap->getBySymb($item);
                   8397:                                 push(@to_test,$res);
                   8398:                             }
1.1162    raeburn  8399:                         } else {
1.1172.2.66  raeburn  8400:                             my $mapsymb = &symbread($item,1);
                   8401:                             if ($mapsymb) {
                   8402:                                 if (ref($navmap)) {
                   8403:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   8404:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   8405:                                     foreach my $res (@to_test) {
                   8406:                                         my $symb = $res->symb();
                   8407:                                         next if ($symb eq $mapsymb);
                   8408:                                         if ($symb ne '') {
                   8409:                                             @interval=&EXT("resource.0.interval",$symb);
                   8410:                                             if ($interval[1] eq 'map') {
                   8411:                                                 last;
1.1162    raeburn  8412:                                             }
                   8413:                                         }
                   8414:                                     }
                   8415:                                 }
                   8416:                             }
                   8417:                         }
1.1172.2.66  raeburn  8418:                     }
                   8419:                     if ($interval[0] =~ /^\d+$/) {
                   8420:                         my $first_access;
                   8421:                         if ($type eq 'resource') {
                   8422:                             $first_access=&get_first_access($interval[1],$item);
                   8423:                         } elsif ($type eq 'map') {
                   8424:                             $first_access=&get_first_access($interval[1],undef,$item);
                   8425:                         } else {
                   8426:                             $first_access=&get_first_access($interval[1]);
                   8427:                         }
                   8428:                         if ($first_access) {
                   8429:                             my $timesup = $first_access+$interval[0];
                   8430:                             if ($timesup > $now) {
                   8431:                                 my $activeblock;
                   8432:                                 foreach my $res (@to_test) {
                   8433:                                     if ($res->answerable()) {
                   8434:                                         $activeblock = 1;
                   8435:                                         last;
                   8436:                                     }
                   8437:                                 }
                   8438:                                 if ($activeblock) {
                   8439:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   8440:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8441:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   8442:                                          }
                   8443:                                     }
                   8444:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   8445:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8446:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  8447:                                         }
1.1162    raeburn  8448:                                     }
                   8449:                                 }
                   8450:                             }
                   8451:                         }
                   8452:                     }
                   8453:                 }
                   8454:             }
                   8455:         }
                   8456:     }
1.1172.2.66  raeburn  8457:     return %blockers;
1.1162    raeburn  8458: }
                   8459: 
1.1172.2.66  raeburn  8460: sub has_comm_blocking {
                   8461:     my ($priv,$symb,$uri,$blocks) = @_;
                   8462:     my @blockers;
                   8463:     return unless ($env{'request.course.id'});
                   8464:     return unless ($priv eq 'bre');
                   8465:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   8466:     return if ($env{'request.state'} eq 'construct');
                   8467:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   8468:     return unless (keys(%cachedblockers) > 0);
                   8469:     my (%possibles,@symbs);
                   8470:     if (!$symb) {
                   8471:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  8472:     }
1.1172.2.66  raeburn  8473:     if ($symb) {
                   8474:         @symbs = ($symb);
                   8475:     } elsif (keys(%possibles)) {
                   8476:         @symbs = keys(%possibles);
                   8477:     }
                   8478:     my $noblock;
                   8479:     foreach my $symb (@symbs) {
                   8480:         last if ($noblock);
                   8481:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   8482:         foreach my $block (keys(%cachedblockers)) {
                   8483:             if ($block =~ /^firstaccess____(.+)$/) {
                   8484:                 my $item = $1;
                   8485:                 if (($item eq $map) || ($item eq $symb)) {
                   8486:                     $noblock = 1;
                   8487:                     last;
                   8488:                 }
1.1162    raeburn  8489:             }
1.1172.2.66  raeburn  8490:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   8491:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   8492:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   8493:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8494:                             push(@blockers,$block);
                   8495:                         }
                   8496:                     }
                   8497:                 }
                   8498:             }
                   8499:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   8500:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   8501:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   8502:                         push(@blockers,$block);
                   8503:                     }
                   8504:                 }
1.1162    raeburn  8505:             }
                   8506:         }
                   8507:     }
1.1172.2.66  raeburn  8508:     return if ($noblock);
                   8509:     return @blockers;
                   8510: }
1.1162    raeburn  8511: }
                   8512: 
1.1172.2.66  raeburn  8513: # -------------------------------- Deversion and split uri into path an filename
                   8514: 
1.1133    foxr     8515: #
1.1172.2.66  raeburn  8516: #   Removes the version from a URI and
1.1133    foxr     8517: #   splits it in to its filename and path to the filename.
                   8518: #   Seems like File::Basename could have done this more clearly.
                   8519: #   Parameters:
                   8520: #      $uri   - input URI
                   8521: #   Returns:
                   8522: #     Two element list consisting of 
                   8523: #     $pathname  - the URI up to and excluding the trailing /
                   8524: #     $filename  - The part of the URI following the last /
                   8525: #  NOTE:
                   8526: #    Another realization of this is simply:
                   8527: #    use File::Basename;
                   8528: #    ...
                   8529: #    $uri = shift;
                   8530: #    $filename = basename($uri);
                   8531: #    $path     = dirname($uri);
                   8532: #    return ($filename, $path);
                   8533: #
                   8534: #     The implementation below is probably faster however.
                   8535: #
1.710     albertel 8536: sub split_uri_for_cond {
                   8537:     my $uri=&deversion(&declutter(shift));
                   8538:     my @uriparts=split(/\//,$uri);
                   8539:     my $filename=pop(@uriparts);
                   8540:     my $pathname=join('/',@uriparts);
                   8541:     return ($pathname,$filename);
                   8542: }
1.232     www      8543: # --------------------------------------------------- Is a resource on the map?
                   8544: 
                   8545: sub is_on_map {
1.710     albertel 8546:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 8547:     #Trying to find the conditional for the file
1.620     albertel 8548:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 8549: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      8550:     if ($match) {
1.289     bowersj2 8551: 	return (1,$1);
                   8552:     } else {
1.434     www      8553: 	return (0,0);
1.289     bowersj2 8554:     }
1.12      www      8555: }
                   8556: 
1.427     www      8557: # --------------------------------------------------------- Get symb from alias
                   8558: 
                   8559: sub get_symb_from_alias {
                   8560:     my $symb=shift;
                   8561:     my ($map,$resid,$url)=&decode_symb($symb);
                   8562: # Already is a symb
                   8563:     if ($url) { return $symb; }
                   8564: # Must be an alias
                   8565:     my $aliassymb='';
                   8566:     my %bighash;
1.620     albertel 8567:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      8568:                             &GDBM_READER(),0640)) {
                   8569:         my $rid=$bighash{'mapalias_'.$symb};
                   8570: 	if ($rid) {
                   8571: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 8572: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   8573: 				    $resid,$bighash{'src_'.$rid});
1.427     www      8574: 	}
                   8575:         untie %bighash;
                   8576:     }
                   8577:     return $aliassymb;
                   8578: }
                   8579: 
1.12      www      8580: # ----------------------------------------------------------------- Define Role
                   8581: 
                   8582: sub definerole {
                   8583:   if (allowed('mcr','/')) {
1.1172.2.84  raeburn  8584:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 8585:     foreach my $role (split(':',$sysrole)) {
                   8586: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8587:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   8588:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   8589: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8590:                return "refused:s:$crole&$cqual"; 
                   8591:             }
                   8592:         }
1.191     harris41 8593:     }
1.800     albertel 8594:     foreach my $role (split(':',$domrole)) {
                   8595: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8596:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   8597:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   8598: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      8599:                return "refused:d:$crole&$cqual"; 
                   8600:             }
                   8601:         }
1.191     harris41 8602:     }
1.800     albertel 8603:     foreach my $role (split(':',$courole)) {
                   8604: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8605:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   8606:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   8607: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8608:                return "refused:c:$crole&$cqual"; 
                   8609:             }
                   8610:         }
1.191     harris41 8611:     }
1.1172.2.84  raeburn  8612:     my $uhome;
                   8613:     if (($uname ne '') && ($udom ne '')) {
                   8614:         $uhome = &homeserver($uname,$udom);
                   8615:         return $uhome if ($uhome eq 'no_host');
                   8616:     } else {
                   8617:         $uname = $env{'user.name'};
                   8618:         $udom = $env{'user.domain'};
                   8619:         $uhome = $env{'user.home'};
                   8620:     }
1.620     albertel 8621:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84  raeburn  8622:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      8623:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84  raeburn  8624:     return reply($command,$uhome);
1.12      www      8625:   } else {
                   8626:     return 'refused';
                   8627:   }
1.105     harris41 8628: }
                   8629: 
                   8630: # ---------------- Make a metadata query against the network of library servers
                   8631: 
                   8632: sub metadata_query {
1.1172.2.33  raeburn  8633:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 8634:     my %rhash;
1.845     albertel 8635:     my %libserv = &all_library();
1.244     matthew  8636:     my @server_list = (defined($server_array) ? @$server_array
                   8637:                                               : keys(%libserv) );
                   8638:     for my $server (@server_list) {
1.1172.2.33  raeburn  8639:         my $domains = '';
                   8640:         if (ref($domains_hash) eq 'HASH') {
                   8641:             $domains = $domains_hash->{$server};    
                   8642:         }
1.118     harris41 8643: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  8644: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 8645: 	    $rhash{$server}=$reply;
                   8646: 	}
                   8647: 	else {
                   8648: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  8649: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 8650: 			     $server);
                   8651: 	    $rhash{$server}=$reply;
                   8652: 	}
1.112     harris41 8653:     }
1.118     harris41 8654:     return \%rhash;
1.240     www      8655: }
                   8656: 
                   8657: # ----------------------------------------- Send log queries and wait for reply
                   8658: 
                   8659: sub log_query {
                   8660:     my ($uname,$udom,$query,%filters)=@_;
                   8661:     my $uhome=&homeserver($uname,$udom);
                   8662:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 8663:     my $uhost=&hostname($uhome);
1.800     albertel 8664:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      8665:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   8666:                        $uhome);
1.479     albertel 8667:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      8668:     return get_query_reply($queryid);
                   8669: }
                   8670: 
1.818     raeburn  8671: # -------------------------- Update MySQL table for portfolio file
                   8672: 
                   8673: sub update_portfolio_table {
1.821     raeburn  8674:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  8675:     if ($group ne '') {
                   8676:         $file_name =~s /^\Q$group\E//;
                   8677:     }
1.818     raeburn  8678:     my $homeserver = &homeserver($uname,$udom);
                   8679:     my $queryid=
1.821     raeburn  8680:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   8681:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  8682:     my $reply = &get_query_reply($queryid);
                   8683:     return $reply;
                   8684: }
                   8685: 
1.899     raeburn  8686: # -------------------------- Update MySQL allusers table
                   8687: 
                   8688: sub update_allusers_table {
                   8689:     my ($uname,$udom,$names) = @_;
                   8690:     my $homeserver = &homeserver($uname,$udom);
                   8691:     my $queryid=
                   8692:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   8693:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   8694:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   8695:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   8696:                'generation='.&escape($names->{'generation'}).'%%'.
                   8697:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   8698:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  8699:     return;
1.899     raeburn  8700: }
                   8701: 
1.508     raeburn  8702: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  8703: 
                   8704: sub fetch_enrollment_query {
1.511     raeburn  8705:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79  raeburn  8706:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  8707:     my $maxtries = 1;
1.508     raeburn  8708:     if ($context eq 'automated') {
                   8709:         $homeserver = $perlvar{'lonHostID'};
1.1172.2.79  raeburn  8710:         $sleep = 2;
                   8711:         $loopmax = 100;
1.547     raeburn  8712:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  8713:     } else {
                   8714:         $homeserver = &homeserver($cnum,$dom);
                   8715:     }
1.838     albertel 8716:     my $host=&hostname($homeserver);
1.506     raeburn  8717:     my $cmd = '';
1.1000    raeburn  8718:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 8719:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  8720:     }
                   8721:     $cmd =~ s/%%$//;
                   8722:     $cmd = &escape($cmd);
                   8723:     my $query = 'fetchenrollment';
1.620     albertel 8724:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  8725:     unless ($queryid=~/^\Q$host\E\_/) { 
                   8726:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   8727:         return 'error: '.$queryid;
                   8728:     }
1.1172.2.93  raeburn  8729:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8730:     my $tries = 1;
                   8731:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79  raeburn  8732:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8733:         $tries ++;
                   8734:     }
1.526     raeburn  8735:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 8736:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  8737:     } else {
1.901     albertel 8738:         my @responses = split(/:/,$reply);
1.1172.2.82  raeburn  8739:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 8740:             foreach my $line (@responses) {
                   8741:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  8742:                 $$replyref{$key} = $value;
                   8743:             }
                   8744:         } else {
1.1117    foxr     8745:             my $pathname = LONCAPA::tempdir();
1.800     albertel 8746:             foreach my $line (@responses) {
                   8747:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  8748:                 $$replyref{$key} = $value;
                   8749:                 if ($value > 0) {
1.800     albertel 8750:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   8751:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  8752:                         my $destname = $pathname.'/'.$filename;
                   8753:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  8754:                         if ($xml_classlist =~ /^error/) {
                   8755:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   8756:                         } else {
1.1172.2.96  raeburn  8757:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  8758:                                 print FILE &unescape($xml_classlist);
                   8759:                                 close(FILE);
1.526     raeburn  8760:                             } else {
                   8761:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  8762:                             }
                   8763:                         }
                   8764:                     }
                   8765:                 }
                   8766:             }
                   8767:         }
                   8768:         return 'ok';
                   8769:     }
                   8770:     return 'error';
                   8771: }
                   8772: 
1.242     www      8773: sub get_query_reply {
1.1172.2.79  raeburn  8774:     my ($queryid,$sleep,$loopmax) = @_;
                   8775:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   8776:         $sleep = 0.2;
                   8777:     }
                   8778:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   8779:         $loopmax = 100;
                   8780:     }
1.1117    foxr     8781:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      8782:     my $reply='';
1.1172.2.79  raeburn  8783:     for (1..$loopmax) {
                   8784: 	sleep($sleep);
1.240     www      8785:         if (-e $replyfile.'.end') {
1.1172.2.96  raeburn  8786: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 8787: 		$reply = join('',<$fh>);
                   8788: 		close($fh);
1.240     www      8789: 	   } else { return 'error: reply_file_error'; }
1.242     www      8790:            return &unescape($reply);
                   8791: 	}
1.240     www      8792:     }
1.242     www      8793:     return 'timeout:'.$queryid;
1.240     www      8794: }
                   8795: 
                   8796: sub courselog_query {
1.241     www      8797: #
                   8798: # possible filters:
                   8799: # url: url or symb
                   8800: # username
                   8801: # domain
                   8802: # action: view, submit, grade
                   8803: # start: timestamp
                   8804: # end: timestamp
                   8805: #
1.240     www      8806:     my (%filters)=@_;
1.620     albertel 8807:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      8808:     if ($filters{'url'}) {
                   8809: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   8810:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   8811:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   8812:     }
1.620     albertel 8813:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8814:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      8815:     return &log_query($cname,$cdom,'courselog',%filters);
                   8816: }
                   8817: 
                   8818: sub userlog_query {
1.858     raeburn  8819: #
                   8820: # possible filters:
                   8821: # action: log check role
                   8822: # start: timestamp
                   8823: # end: timestamp
                   8824: #
1.240     www      8825:     my ($uname,$udom,%filters)=@_;
                   8826:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      8827: }
                   8828: 
1.506     raeburn  8829: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   8830: 
                   8831: sub auto_run {
1.508     raeburn  8832:     my ($cnum,$cdom) = @_;
1.876     raeburn  8833:     my $response = 0;
                   8834:     my $settings;
                   8835:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   8836:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   8837:         $settings = $domconfig{'autoenroll'};
                   8838:         if ($settings->{'run'} eq '1') {
                   8839:             $response = 1;
                   8840:         }
                   8841:     } else {
1.934     raeburn  8842:         my $homeserver;
                   8843:         if (&is_course($cdom,$cnum)) {
                   8844:             $homeserver = &homeserver($cnum,$cdom);
                   8845:         } else {
                   8846:             $homeserver = &domain($cdom,'primary');
                   8847:         }
                   8848:         if ($homeserver ne 'no_host') {
                   8849:             $response = &reply('autorun:'.$cdom,$homeserver);
                   8850:         }
1.876     raeburn  8851:     }
1.506     raeburn  8852:     return $response;
                   8853: }
1.776     albertel 8854: 
1.506     raeburn  8855: sub auto_get_sections {
1.508     raeburn  8856:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  8857:     my $homeserver;
                   8858:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   8859:         $homeserver = &homeserver($cnum,$cdom);
                   8860:     }
                   8861:     if (!defined($homeserver)) { 
                   8862:         if ($cdom =~ /^$match_domain$/) {
                   8863:             $homeserver = &domain($cdom,'primary');
                   8864:         }
                   8865:     }
                   8866:     my @secs;
                   8867:     if (defined($homeserver)) {
                   8868:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   8869:         unless ($response eq 'refused') {
                   8870:             @secs = split(/:/,$response);
                   8871:         }
1.506     raeburn  8872:     }
                   8873:     return @secs;
                   8874: }
1.776     albertel 8875: 
1.506     raeburn  8876: sub auto_new_course {
1.1099    raeburn  8877:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  8878:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  8879:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  8880:     return $response;
                   8881: }
1.776     albertel 8882: 
1.506     raeburn  8883: sub auto_validate_courseID {
1.508     raeburn  8884:     my ($cnum,$cdom,$inst_course_id) = @_;
                   8885:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  8886:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  8887:     return $response;
                   8888: }
1.776     albertel 8889: 
1.1007    raeburn  8890: sub auto_validate_instcode {
1.1020    raeburn  8891:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  8892:     my ($homeserver,$response);
                   8893:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8894:         $homeserver = &homeserver($cnum,$cdom);
                   8895:     }
                   8896:     if (!defined($homeserver)) {
                   8897:         if ($cdom =~ /^$match_domain$/) {
                   8898:             $homeserver = &domain($cdom,'primary');
                   8899:         }
                   8900:     }
1.1065    raeburn  8901:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   8902:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  8903:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   8904:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  8905: }
                   8906: 
1.506     raeburn  8907: sub auto_create_password {
1.873     raeburn  8908:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   8909:     my ($homeserver,$response);
1.506     raeburn  8910:     my $create_passwd = 0;
                   8911:     my $authchk = '';
1.873     raeburn  8912:     if ($udom =~ /^$match_domain$/) {
                   8913:         $homeserver = &domain($udom,'primary');
                   8914:     }
                   8915:     if ($homeserver eq '') {
                   8916:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8917:             $homeserver = &homeserver($cnum,$cdom);
                   8918:         }
                   8919:     }
                   8920:     if ($homeserver eq '') {
                   8921:         $authchk = 'nodomain';
1.506     raeburn  8922:     } else {
1.873     raeburn  8923:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   8924:         if ($response eq 'refused') {
                   8925:             $authchk = 'refused';
                   8926:         } else {
1.901     albertel 8927:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  8928:         }
1.506     raeburn  8929:     }
                   8930:     return ($authparam,$create_passwd,$authchk);
                   8931: }
                   8932: 
1.706     raeburn  8933: sub auto_photo_permission {
                   8934:     my ($cnum,$cdom,$students) = @_;
                   8935:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 8936:     my ($outcome,$perm_reqd,$conditions) = 
                   8937: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 8938:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8939: 	return (undef,undef);
                   8940:     }
1.706     raeburn  8941:     return ($outcome,$perm_reqd,$conditions);
                   8942: }
                   8943: 
                   8944: sub auto_checkphotos {
                   8945:     my ($uname,$udom,$pid) = @_;
                   8946:     my $homeserver = &homeserver($uname,$udom);
                   8947:     my ($result,$resulttype);
                   8948:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 8949: 				   &escape($uname).':'.&escape($pid),
                   8950: 				   $homeserver));
1.709     albertel 8951:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8952: 	return (undef,undef);
                   8953:     }
1.706     raeburn  8954:     if ($outcome) {
                   8955:         ($result,$resulttype) = split(/:/,$outcome);
                   8956:     } 
                   8957:     return ($result,$resulttype);
                   8958: }
                   8959: 
                   8960: sub auto_photochoice {
                   8961:     my ($cnum,$cdom) = @_;
                   8962:     my $homeserver = &homeserver($cnum,$cdom);
                   8963:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 8964: 						       &escape($cdom),
                   8965: 						       $homeserver)));
1.709     albertel 8966:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8967: 	return (undef,undef);
                   8968:     }
1.706     raeburn  8969:     return ($update,$comment);
                   8970: }
                   8971: 
                   8972: sub auto_photoupdate {
                   8973:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   8974:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 8975:     my $host=&hostname($homeserver);
1.706     raeburn  8976:     my $cmd = '';
                   8977:     my $maxtries = 1;
1.800     albertel 8978:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   8979:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  8980:     }
                   8981:     $cmd =~ s/%%$//;
                   8982:     $cmd = &escape($cmd);
                   8983:     my $query = 'institutionalphotos';
                   8984:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   8985:     unless ($queryid=~/^\Q$host\E\_/) {
                   8986:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   8987:         return 'error: '.$queryid;
                   8988:     }
                   8989:     my $reply = &get_query_reply($queryid);
                   8990:     my $tries = 1;
                   8991:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   8992:         $reply = &get_query_reply($queryid);
                   8993:         $tries ++;
                   8994:     }
                   8995:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   8996:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   8997:     } else {
                   8998:         my @responses = split(/:/,$reply);
                   8999:         my $outcome = shift(@responses); 
                   9000:         foreach my $item (@responses) {
                   9001:             my ($key,$value) = split(/=/,$item);
                   9002:             $$photo{$key} = $value;
                   9003:         }
                   9004:         return $outcome;
                   9005:     }
                   9006:     return 'error';
                   9007: }
                   9008: 
1.521     raeburn  9009: sub auto_instcode_format {
1.793     albertel 9010:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   9011: 	$cat_order) = @_;
1.521     raeburn  9012:     my $courses = '';
1.772     raeburn  9013:     my @homeservers;
1.521     raeburn  9014:     if ($caller eq 'global') {
1.841     albertel 9015: 	my %servers = &get_servers($codedom,'library');
                   9016: 	foreach my $tryserver (keys(%servers)) {
                   9017: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9018: 		push(@homeservers,$tryserver);
                   9019: 	    }
1.584     raeburn  9020:         }
1.1022    raeburn  9021:     } elsif ($caller eq 'requests') {
                   9022:         if ($codedom =~ /^$match_domain$/) {
                   9023:             my $chome = &domain($codedom,'primary');
                   9024:             unless ($chome eq 'no_host') {
                   9025:                 push(@homeservers,$chome);
                   9026:             }
                   9027:         }
1.521     raeburn  9028:     } else {
1.772     raeburn  9029:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  9030:     }
1.793     albertel 9031:     foreach my $code (keys(%{$instcodes})) {
                   9032:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  9033:     }
                   9034:     chop($courses);
1.772     raeburn  9035:     my $ok_response = 0;
                   9036:     my $response;
                   9037:     while (@homeservers > 0 && $ok_response == 0) {
                   9038:         my $server = shift(@homeservers); 
                   9039:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   9040:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   9041:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 9042: 		split(/:/,$response);
1.772     raeburn  9043:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   9044:             push(@{$codetitles},&str2array($codetitles_str));
                   9045:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   9046:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   9047:             $ok_response = 1;
                   9048:         }
                   9049:     }
                   9050:     if ($ok_response) {
1.521     raeburn  9051:         return 'ok';
1.772     raeburn  9052:     } else {
                   9053:         return $response;
1.521     raeburn  9054:     }
                   9055: }
                   9056: 
1.792     raeburn  9057: sub auto_instcode_defaults {
                   9058:     my ($domain,$returnhash,$code_order) = @_;
                   9059:     my @homeservers;
1.841     albertel 9060: 
                   9061:     my %servers = &get_servers($domain,'library');
                   9062:     foreach my $tryserver (keys(%servers)) {
                   9063: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9064: 	    push(@homeservers,$tryserver);
                   9065: 	}
1.792     raeburn  9066:     }
1.841     albertel 9067: 
1.792     raeburn  9068:     my $response;
1.841     albertel 9069:     foreach my $server (@homeservers) {
1.792     raeburn  9070:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 9071:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   9072: 	
                   9073: 	foreach my $pair (split(/\&/,$response)) {
                   9074: 	    my ($name,$value)=split(/\=/,$pair);
                   9075: 	    if ($name eq 'code_order') {
                   9076: 		@{$code_order} = split(/\&/,&unescape($value));
                   9077: 	    } else {
                   9078: 		$returnhash->{&unescape($name)}=&unescape($value);
                   9079: 	    }
                   9080: 	}
                   9081: 	return 'ok';
1.792     raeburn  9082:     }
1.841     albertel 9083: 
                   9084:     return $response;
1.1003    raeburn  9085: }
                   9086: 
                   9087: sub auto_possible_instcodes {
1.1007    raeburn  9088:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   9089:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   9090:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9091:         return;
                   9092:     }
1.1003    raeburn  9093:     my (@homeservers,$uhome);
                   9094:     if (defined(&domain($domain,'primary'))) {
                   9095:         $uhome=&domain($domain,'primary');
                   9096:         push(@homeservers,&domain($domain,'primary'));
                   9097:     } else {
                   9098:         my %servers = &get_servers($domain,'library');
                   9099:         foreach my $tryserver (keys(%servers)) {
                   9100:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9101:                 push(@homeservers,$tryserver);
                   9102:             }
                   9103:         }
                   9104:     }
                   9105:     my $response;
                   9106:     foreach my $server (@homeservers) {
                   9107:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   9108:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  9109:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   9110:             split(':',$response);
                   9111:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   9112:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  9113:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  9114:             my ($name,$value)=split('=',$item);
                   9115:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9116:         }
                   9117:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  9118:             my ($name,$value)=split('=',$item);
                   9119:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9120:         }
                   9121:         return 'ok';
                   9122:     }
                   9123:     return $response;
                   9124: }
1.792     raeburn  9125: 
1.1010    raeburn  9126: sub auto_courserequest_checks {
                   9127:     my ($dom) = @_;
1.1020    raeburn  9128:     my ($homeserver,%validations);
                   9129:     if ($dom =~ /^$match_domain$/) {
                   9130:         $homeserver = &domain($dom,'primary');
                   9131:     }
                   9132:     unless ($homeserver eq 'no_host') {
                   9133:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   9134:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9135:             my @items = split(/&/,$response);
                   9136:             foreach my $item (@items) {
                   9137:                 my ($key,$value) = split('=',$item);
                   9138:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   9139:             }
                   9140:         }
                   9141:     }
1.1010    raeburn  9142:     return %validations; 
                   9143: }
                   9144: 
1.1020    raeburn  9145: sub auto_courserequest_validation {
1.1172.2.43  raeburn  9146:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  9147:     my ($homeserver,$response);
                   9148:     if ($dom =~ /^$match_domain$/) {
                   9149:         $homeserver = &domain($dom,'primary');
                   9150:     }
1.1172.2.43  raeburn  9151:     unless ($homeserver eq 'no_host') {
                   9152:         my $customdata;
                   9153:         if (ref($custominfo) eq 'HASH') {
                   9154:             $customdata = &freeze_escape($custominfo);
                   9155:         }
1.1020    raeburn  9156:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  9157:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43  raeburn  9158:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   9159:                                     $customdata,$homeserver));
1.1020    raeburn  9160:     }
                   9161:     return $response;
                   9162: }
                   9163: 
1.777     albertel 9164: sub auto_validate_class_sec {
1.918     raeburn  9165:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  9166:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  9167:     my $ownerlist;
                   9168:     if (ref($owners) eq 'ARRAY') {
                   9169:         $ownerlist = join(',',@{$owners});
                   9170:     } else {
                   9171:         $ownerlist = $owners;
                   9172:     }
1.773     raeburn  9173:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  9174:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  9175:     return $response;
                   9176: }
                   9177: 
1.1172.2.94  raeburn  9178: sub auto_validate_instclasses {
                   9179:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   9180:     my ($homeserver,%validations);
                   9181:     $homeserver = &homeserver($cnum,$cdom);
                   9182:     unless ($homeserver eq 'no_host') {
                   9183:         my $ownerlist;
                   9184:         if (ref($owners) eq 'ARRAY') {
                   9185:             $ownerlist = join(',',@{$owners});
                   9186:         } else {
                   9187:             $ownerlist = $owners;
                   9188:         }
                   9189:         if (ref($classesref) eq 'HASH') {
                   9190:             my $classes = &freeze_escape($classesref);
                   9191:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   9192:                                 ':'.$cdom.':'.$classes,$homeserver);
                   9193:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9194:                 my @items = split(/&/,$response);
                   9195:                 foreach my $item (@items) {
                   9196:                     my ($key,$value) = split('=',$item);
                   9197:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   9198:                 }
                   9199:             }
                   9200:         }
                   9201:     }
                   9202:     return %validations;
                   9203: }
                   9204: 
1.1172.2.38  raeburn  9205: sub auto_crsreq_update {
                   9206:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45  raeburn  9207:         $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38  raeburn  9208:     my ($homeserver,%crsreqresponse);
                   9209:     if ($cdom =~ /^$match_domain$/) {
                   9210:         $homeserver = &domain($cdom,'primary');
                   9211:     }
                   9212:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9213:         my $info;
                   9214:         if (ref($inbound) eq 'HASH') {
                   9215:             $info = &freeze_escape($inbound);
                   9216:         }
                   9217:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   9218:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   9219:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45  raeburn  9220:                             &escape($title).':'.&escape($code).':'.
                   9221:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38  raeburn  9222:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9223:             my @items = split(/&/,$response);
                   9224:             foreach my $item (@items) {
                   9225:                 my ($key,$value) = split('=',$item);
                   9226:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   9227:             }
                   9228:         }
                   9229:     }
                   9230:     return \%crsreqresponse;
                   9231: }
                   9232: 
1.1172.2.78  raeburn  9233: sub auto_export_grades {
                   9234:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   9235:     my ($homeserver,%exportresponse);
                   9236:     if ($cdom =~ /^$match_domain$/) {
                   9237:         $homeserver = &domain($cdom,'primary');
                   9238:     }
                   9239:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9240:         my $info;
                   9241:         if (ref($inforef) eq 'HASH') {
                   9242:             $info = &freeze_escape($inforef);
                   9243:         }
                   9244:         if (ref($gradesref) eq 'HASH') {
                   9245:             my $grades = &freeze_escape($gradesref);
                   9246:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   9247:                                 $info.':'.$grades,$homeserver);
                   9248:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   9249:                 my @items = split(/&/,$response);
                   9250:                 foreach my $item (@items) {
                   9251:                     my ($key,$value) = split('=',$item);
                   9252:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   9253:                 }
                   9254:             }
                   9255:         }
                   9256:     }
                   9257:     return \%exportresponse;
                   9258: }
                   9259: 
1.1172.2.68  raeburn  9260: sub check_instcode_cloning {
                   9261:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   9262:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9263:         return;
                   9264:     }
                   9265:     my $canclone;
                   9266:     if (@{$code_order} > 0) {
                   9267:         my $instcoderegexp ='^';
                   9268:         my @clonecodes = split(/\&/,$cloner);
                   9269:         foreach my $item (@{$code_order}) {
                   9270:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   9271:                 foreach my $pair (@clonecodes) {
                   9272:                     my ($key,$val) = split(/\=/,$pair,2);
                   9273:                     $val = &unescape($val);
                   9274:                     if ($key eq $item) {
                   9275:                         $instcoderegexp .= '('.$val.')';
                   9276:                         last;
                   9277:                     }
                   9278:                 }
                   9279:             } else {
                   9280:                 $instcoderegexp .= $codedefaults->{$item};
                   9281:             }
                   9282:         }
                   9283:         $instcoderegexp .= '$';
                   9284:         my (@from,@to);
                   9285:         eval {
                   9286:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9287:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9288:         };
                   9289:         if ((@from > 0) && (@to > 0)) {
                   9290:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9291:             if (!@diffs) {
                   9292:                 $canclone = 1;
                   9293:             }
                   9294:         }
                   9295:     }
                   9296:     return $canclone;
                   9297: }
                   9298: 
                   9299: sub default_instcode_cloning {
                   9300:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   9301:     my (%codedefaults,@code_order,$canclone);
                   9302:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   9303:         %codedefaults = %{$codedefaultsref};
                   9304:         @code_order = @{$codeorderref};
                   9305:     } elsif ($clonedom) {
                   9306:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   9307:     }
                   9308:     if (($domdefclone) && (@code_order)) {
                   9309:         my @clonecodes = split(/\+/,$domdefclone);
                   9310:         my $instcoderegexp ='^';
                   9311:         foreach my $item (@code_order) {
                   9312:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   9313:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   9314:             } else {
                   9315:                 $instcoderegexp .= $codedefaults{$item};
                   9316:             }
                   9317:         }
                   9318:         $instcoderegexp .= '$';
                   9319:         my (@from,@to);
                   9320:         eval {
                   9321:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9322:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9323:         };
                   9324:         if ((@from > 0) && (@to > 0)) {
                   9325:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9326:             if (!@diffs) {
                   9327:                 $canclone = 1;
                   9328:             }
                   9329:         }
                   9330:     }
                   9331:     return $canclone;
                   9332: }
                   9333: 
1.679     raeburn  9334: # ------------------------------------------------------- Course Group routines
                   9335: 
                   9336: sub get_coursegroups {
1.809     raeburn  9337:     my ($cdom,$cnum,$group,$namespace) = @_;
                   9338:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  9339: }
                   9340: 
1.679     raeburn  9341: sub modify_coursegroup {
                   9342:     my ($cdom,$cnum,$groupsettings) = @_;
                   9343:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   9344: }
                   9345: 
1.809     raeburn  9346: sub toggle_coursegroup_status {
                   9347:     my ($cdom,$cnum,$group,$action) = @_;
                   9348:     my ($from_namespace,$to_namespace);
                   9349:     if ($action eq 'delete') {
                   9350:         $from_namespace = 'coursegroups';
                   9351:         $to_namespace = 'deleted_groups';
                   9352:     } else {
                   9353:         $from_namespace = 'deleted_groups';
                   9354:         $to_namespace = 'coursegroups';
                   9355:     }
                   9356:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  9357:     if (my $tmp = &error(%curr_group)) {
                   9358:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   9359:         return ('read error',$tmp);
                   9360:     } else {
                   9361:         my %savedsettings = %curr_group; 
1.809     raeburn  9362:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  9363:         my $deloutcome;
                   9364:         if ($result eq 'ok') {
1.809     raeburn  9365:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  9366:         } else {
                   9367:             return ('write error',$result);
                   9368:         }
                   9369:         if ($deloutcome eq 'ok') {
                   9370:             return 'ok';
                   9371:         } else {
                   9372:             return ('delete error',$deloutcome);
                   9373:         }
                   9374:     }
                   9375: }
                   9376: 
1.679     raeburn  9377: sub modify_group_roles {
1.957     raeburn  9378:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  9379:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   9380:     my $role = 'gr/'.&escape($userprivs);
                   9381:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  9382:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  9383:     if ($result eq 'ok') {
                   9384:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   9385:     }
1.679     raeburn  9386:     return $result;
                   9387: }
                   9388: 
                   9389: sub modify_coursegroup_membership {
                   9390:     my ($cdom,$cnum,$membership) = @_;
                   9391:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   9392:     return $result;
                   9393: }
                   9394: 
1.682     raeburn  9395: sub get_active_groups {
                   9396:     my ($udom,$uname,$cdom,$cnum) = @_;
                   9397:     my $now = time;
                   9398:     my %groups = ();
                   9399:     foreach my $key (keys(%env)) {
1.811     albertel 9400:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  9401:             my ($start,$end) = split(/\./,$env{$key});
                   9402:             if (($end!=0) && ($end<$now)) { next; }
                   9403:             if (($start!=0) && ($start>$now)) { next; }
                   9404:             if ($1 eq $cdom && $2 eq $cnum) {
                   9405:                 $groups{$3} = $env{$key} ;
                   9406:             }
                   9407:         }
                   9408:     }
                   9409:     return %groups;
                   9410: }
                   9411: 
1.683     raeburn  9412: sub get_group_membership {
                   9413:     my ($cdom,$cnum,$group) = @_;
                   9414:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   9415: }
                   9416: 
                   9417: sub get_users_groups {
                   9418:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  9419:     my @usersgroups;
1.683     raeburn  9420:     my $cachetime=1800;
                   9421: 
                   9422:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  9423:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   9424:     if (defined($cached)) {
1.734     albertel 9425:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  9426:     } else {  
                   9427:         $grouplist = '';
1.816     raeburn  9428:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  9429:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  9430:         my $access_end = $env{'course.'.$courseid.
                   9431:                               '.default_enrollment_end_date'};
                   9432:         my $now = time;
                   9433:         foreach my $key (keys(%roleshash)) {
                   9434:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   9435:                 my $group = $1;
                   9436:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   9437:                     my $start = $2;
                   9438:                     my $end = $1;
                   9439:                     if ($start == -1) { next; } # deleted from group
                   9440:                     if (($start!=0) && ($start>$now)) { next; }
                   9441:                     if (($end!=0) && ($end<$now)) {
                   9442:                         if ($access_end && $access_end < $now) {
                   9443:                             if ($access_end - $end < 86400) {
                   9444:                                 push(@usersgroups,$group);
1.733     raeburn  9445:                             }
                   9446:                         }
1.817     raeburn  9447:                         next;
1.733     raeburn  9448:                     }
1.817     raeburn  9449:                     push(@usersgroups,$group);
1.683     raeburn  9450:                 }
                   9451:             }
                   9452:         }
1.817     raeburn  9453:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   9454:         $grouplist = join(':',@usersgroups);
                   9455:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  9456:     }
1.733     raeburn  9457:     return @usersgroups;
1.683     raeburn  9458: }
                   9459: 
                   9460: sub devalidate_getgroups_cache {
                   9461:     my ($udom,$uname,$cdom,$cnum)=@_;
                   9462:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 9463: 
1.683     raeburn  9464:     my $hashid="$udom:$uname:$courseid";
                   9465:     &devalidate_cache_new('getgroups',$hashid);
                   9466: }
                   9467: 
1.12      www      9468: # ------------------------------------------------------------------ Plain Text
                   9469: 
                   9470: sub plaintext {
1.988     raeburn  9471:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  9472:     if ($short =~ m{^cr/}) {
1.758     albertel 9473: 	return (split('/',$short))[-1];
                   9474:     }
1.742     raeburn  9475:     if (!defined($cid)) {
                   9476:         $cid = $env{'request.course.id'};
                   9477:     }
                   9478:     my %rolenames = (
1.1008    raeburn  9479:                       Course    => 'std',
                   9480:                       Community => 'alt1',
1.742     raeburn  9481:                     );
1.1037    raeburn  9482:     if ($cid ne '') {
                   9483:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   9484:             unless ($forcedefault) {
                   9485:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   9486:                 &Apache::lonlocal::mt_escape(\$roletext);
                   9487:                 return &Apache::lonlocal::mt($roletext);
                   9488:             }
                   9489:         }
                   9490:     }
                   9491:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   9492:         (defined($rolenames{$type})) && 
                   9493:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  9494:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  9495:     } elsif ($cid ne '') {
                   9496:         my $crstype = $env{'course.'.$cid.'.type'};
                   9497:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   9498:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   9499:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   9500:         }
1.742     raeburn  9501:     }
1.1037    raeburn  9502:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      9503: }
                   9504: 
                   9505: # ----------------------------------------------------------------- Assign Role
                   9506: 
                   9507: sub assignrole {
1.957     raeburn  9508:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   9509:         $context)=@_;
1.21      www      9510:     my $mrole;
                   9511:     if ($role =~ /^cr\//) {
1.393     www      9512:         my $cwosec=$url;
1.811     albertel 9513:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      9514: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  9515:            my $refused = 1;
                   9516:            if ($context eq 'requestcourses') {
                   9517:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   9518:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   9519:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   9520:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9521:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9522:                            if ($crsenv{'internal.courseowner'} eq
                   9523:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   9524:                                $refused = '';
                   9525:                            }
                   9526:                        }
                   9527:                    }
                   9528:                }
                   9529:            }
                   9530:            if ($refused) {
                   9531:                &logthis('Refused custom assignrole: '.
                   9532:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   9533:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   9534:                return 'refused';
                   9535:            }
1.104     www      9536:         }
1.21      www      9537:         $mrole='cr';
1.678     raeburn  9538:     } elsif ($role =~ /^gr\//) {
                   9539:         my $cwogrp=$url;
1.811     albertel 9540:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  9541:         unless (&allowed('mdg',$cwogrp)) {
                   9542:             &logthis('Refused group assignrole: '.
                   9543:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   9544:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   9545:             return 'refused';
                   9546:         }
                   9547:         $mrole='gr';
1.21      www      9548:     } else {
1.82      www      9549:         my $cwosec=$url;
1.811     albertel 9550:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  9551:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   9552:             my $refused;
                   9553:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   9554:                 if (!(&allowed('c'.$role,$url))) {
                   9555:                     $refused = 1;
                   9556:                 }
                   9557:             } else {
                   9558:                 $refused = 1;
                   9559:             }
1.947     raeburn  9560:             if ($refused) {
1.1045    raeburn  9561:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9562:                 if (!$selfenroll && $context eq 'course') {
                   9563:                     my %crsenv;
                   9564:                     if ($role eq 'cc' || $role eq 'co') {
                   9565:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9566:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   9567:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   9568:                                 if ($crsenv{'internal.courseowner'} eq 
                   9569:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9570:                                     $refused = '';
                   9571:                                 }
                   9572:                             }
                   9573:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   9574:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   9575:                                 if ($crsenv{'internal.courseowner'} eq 
                   9576:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9577:                                     $refused = '';
                   9578:                                 }
                   9579:                             }
                   9580:                         }
                   9581:                     }
                   9582:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  9583:                     $refused = '';
1.1017    raeburn  9584:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  9585:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  9586:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  9587:                         my $wrongcc;
                   9588:                         if ($cnum =~ /^$match_community$/) {
                   9589:                             $wrongcc = 1 if ($role eq 'cc');
                   9590:                         } else {
                   9591:                             $wrongcc = 1 if ($role eq 'co');
                   9592:                         }
                   9593:                         unless ($wrongcc) {
                   9594:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9595:                             if ($crsenv{'internal.courseowner'} eq 
                   9596:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   9597:                                 $refused = '';
                   9598:                             }
1.1017    raeburn  9599:                         }
                   9600:                     }
1.1172.2.9  raeburn  9601:                 } elsif ($context eq 'requestauthor') {
                   9602:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   9603:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   9604:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   9605:                             $refused = '';
                   9606:                         } else {
                   9607:                             my %domdefaults = &get_domain_defaults($udom);
                   9608:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   9609:                                 my $checkbystatus;
                   9610:                                 if ($env{'user.adv'}) {
                   9611:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   9612:                                     if ($disposition eq 'automatic') {
                   9613:                                         $refused = '';
                   9614:                                     } elsif ($disposition eq '') {
                   9615:                                         $checkbystatus = 1;
                   9616:                                     }
                   9617:                                 } else {
                   9618:                                     $checkbystatus = 1;
                   9619:                                 }
                   9620:                                 if ($checkbystatus) {
                   9621:                                     if ($env{'environment.inststatus'}) {
                   9622:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   9623:                                         foreach my $type (@inststatuses) {
                   9624:                                             if (($type ne '') &&
                   9625:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   9626:                                                 $refused = '';
                   9627:                                             }
                   9628:                                         }
                   9629:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   9630:                                         $refused = '';
                   9631:                                     }
                   9632:                                 }
                   9633:                             }
                   9634:                         }
                   9635:                     }
1.1017    raeburn  9636:                 }
                   9637:                 if ($refused) {
1.947     raeburn  9638:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   9639:                              ' '.$role.' '.$end.' '.$start.' by '.
                   9640: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   9641:                     return 'refused';
                   9642:                 }
1.932     raeburn  9643:             }
1.1131    raeburn  9644:         } elsif ($role eq 'au') {
                   9645:             if ($url ne '/'.$udom.'/') {
                   9646:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   9647:                          ' to assign author role for '.$uname.':'.$udom.
                   9648:                          ' in domain: '.$url.' refused (wrong domain).');
                   9649:                 return 'refused';
                   9650:             }
1.104     www      9651:         }
1.21      www      9652:         $mrole=$role;
                   9653:     }
1.620     albertel 9654:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      9655:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      9656:     if ($end) { $command.='_'.$end; }
1.21      www      9657:     if ($start) {
                   9658: 	if ($end) { 
1.81      www      9659:            $command.='_'.$start; 
1.21      www      9660:         } else {
1.81      www      9661:            $command.='_0_'.$start;
1.21      www      9662:         }
                   9663:     }
1.739     raeburn  9664:     my $origstart = $start;
                   9665:     my $origend = $end;
1.957     raeburn  9666:     my $delflag;
1.357     www      9667: # actually delete
                   9668:     if ($deleteflag) {
1.373     www      9669: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      9670: # modify command to delete the role
1.620     albertel 9671:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      9672:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 9673: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      9674: # set start and finish to negative values for userrolelog
                   9675:            $start=-1;
                   9676:            $end=-1;
1.957     raeburn  9677:            $delflag = 1;
1.357     www      9678:         }
                   9679:     }
                   9680: # send command
1.349     www      9681:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      9682: # log new user role if status is ok
1.349     www      9683:     if ($answer eq 'ok') {
1.663     raeburn  9684: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  9685:         if (($role eq 'cc') || ($role eq 'in') ||
                   9686:             ($role eq 'ep') || ($role eq 'ad') ||
                   9687:             ($role eq 'ta') || ($role eq 'st') ||
                   9688:             ($role=~/^cr/) || ($role eq 'gr') ||
                   9689:             ($role eq 'co')) {
1.1172.2.13  raeburn  9690: # for course roles, perform group memberships changes triggered by role change.
                   9691:             unless ($role =~ /^gr/) {
                   9692:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   9693:                                                  $origstart,$selfenroll,$context);
                   9694:             }
1.1172.2.9  raeburn  9695:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9696:                            $selfenroll,$context);
                   9697:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90  raeburn  9698:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   9699:                  ($role eq 'da')) {
1.1172.2.9  raeburn  9700:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9701:                            $context);
                   9702:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   9703:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9704:                              $context);
                   9705:         }
1.1053    raeburn  9706:         if ($role eq 'cc') {
                   9707:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   9708:         }
1.349     www      9709:     }
                   9710:     return $answer;
1.169     harris41 9711: }
                   9712: 
1.1053    raeburn  9713: sub autoupdate_coowners {
                   9714:     my ($url,$end,$start,$uname,$udom) = @_;
                   9715:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   9716:     if (($cdom ne '') && ($cnum ne '')) {
                   9717:         my $now = time;
                   9718:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   9719:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   9720:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   9721:             my $instcode = $coursehash{'internal.coursecode'};
                   9722:             if ($instcode ne '') {
1.1056    raeburn  9723:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   9724:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  9725:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  9726:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   9727:                         if ($result eq 'valid') {
                   9728:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  9729:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9730:                                     push(@newcoowners,$coowner);
                   9731:                                 }
                   9732:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   9733:                                     push(@newcoowners,$uname.':'.$udom);
                   9734:                                 }
                   9735:                                 @newcoowners = sort(@newcoowners);
                   9736:                             } else {
                   9737:                                 push(@newcoowners,$uname.':'.$udom);
                   9738:                             }
                   9739:                         } else {
                   9740:                             if ($coursehash{'internal.co-owners'}) {
                   9741:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9742:                                     unless ($coowner eq $uname.':'.$udom) {
                   9743:                                         push(@newcoowners,$coowner);
                   9744:                                     }
                   9745:                                 }
                   9746:                                 unless (@newcoowners > 0) {
                   9747:                                     $delcoowners = 1;
                   9748:                                     $coowners = '';
                   9749:                                 }
                   9750:                             }
                   9751:                         }
                   9752:                         if (@newcoowners || $delcoowners) {
                   9753:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   9754:                                             $delcoowners,@newcoowners);
                   9755:                         }
                   9756:                     }
                   9757:                 }
                   9758:             }
                   9759:         }
                   9760:     }
                   9761: }
                   9762: 
                   9763: sub store_coowners {
                   9764:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   9765:     my $cid = $cdom.'_'.$cnum;
                   9766:     my ($coowners,$delresult,$putresult);
                   9767:     if (@newcoowners) {
                   9768:         $coowners = join(',',@newcoowners);
                   9769:         my %coownershash = (
                   9770:                             'internal.co-owners' => $coowners,
                   9771:                            );
                   9772:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   9773:         if ($putresult eq 'ok') {
                   9774:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   9775:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   9776:             }
                   9777:         }
                   9778:     }
                   9779:     if ($delcoowners) {
                   9780:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   9781:         if ($delresult eq 'ok') {
                   9782:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   9783:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   9784:             }
                   9785:         }
                   9786:     }
                   9787:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   9788:         my %crsinfo =
                   9789:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   9790:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   9791:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   9792:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   9793:         }
                   9794:     }
                   9795: }
                   9796: 
1.169     harris41 9797: # -------------------------------------------------- Modify user authentication
1.197     www      9798: # Overrides without validation
                   9799: 
1.169     harris41 9800: sub modifyuserauth {
                   9801:     my ($udom,$uname,$umode,$upass)=@_;
                   9802:     my $uhome=&homeserver($uname,$udom);
1.1172.2.115! raeburn  9803:     my $allowed;
        !          9804:     if (&allowed('mau',$udom)) {
        !          9805:         $allowed = 1;
        !          9806:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
        !          9807:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
        !          9808:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
        !          9809:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
        !          9810:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
        !          9811:         if (($cdom ne '') && ($cnum ne '')) {
        !          9812:             my $is_owner = &is_course_owner($cdom,$cnum);
        !          9813:             if ($is_owner) {
        !          9814:                 $allowed = 1;
        !          9815:             }
        !          9816:         }
        !          9817:     }
        !          9818:     unless ($allowed) { return 'refused'; }
1.197     www      9819:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 9820:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9821:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 9822:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   9823: 		     &escape($upass),$uhome);
1.620     albertel 9824:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      9825:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   9826:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   9827:     &log($udom,,$uname,$uhome,
1.620     albertel 9828:         'Authentication changed by '.$env{'user.domain'}.', '.
                   9829:                                      $env{'user.name'}.', '.$umode.
1.197     www      9830:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 9831:     unless ($reply eq 'ok') {
1.197     www      9832:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 9833: 	return 'error: '.$reply;
                   9834:     }   
1.170     harris41 9835:     return 'ok';
1.80      www      9836: }
                   9837: 
1.81      www      9838: # --------------------------------------------------------------- Modify a user
1.80      www      9839: 
1.81      www      9840: sub modifyuser {
1.206     matthew  9841:     my ($udom,    $uname, $uid,
                   9842:         $umode,   $upass, $first,
                   9843:         $middle,  $last,  $gene,
1.1058    raeburn  9844:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 9845:     $udom= &LONCAPA::clean_domain($udom);
                   9846:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  9847:     my $showcandelete = 'none';
                   9848:     if (ref($candelete) eq 'ARRAY') {
                   9849:         if (@{$candelete} > 0) {
                   9850:             $showcandelete = join(', ',@{$candelete});
                   9851:         }
                   9852:     }
1.81      www      9853:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      9854:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  9855: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  9856:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   9857:                                      ' desiredhome not specified'). 
1.620     albertel 9858:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9859:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 9860:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  9861:     my $newuser;
                   9862:     if ($uhome eq 'no_host') {
                   9863:         $newuser = 1;
                   9864:     }
1.80      www      9865: # ----------------------------------------------------------------- Create User
1.406     albertel 9866:     if (($uhome eq 'no_host') && 
                   9867: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      9868:         my $unhome='';
1.844     albertel 9869:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  9870:             $unhome = $desiredhome;
1.620     albertel 9871: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   9872: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  9873:         } else { # load balancing routine for determining $unhome
1.81      www      9874:             my $loadm=10000000;
1.841     albertel 9875: 	    my %servers = &get_servers($udom,'library');
                   9876: 	    foreach my $tryserver (keys(%servers)) {
                   9877: 		my $answer=reply('load',$tryserver);
                   9878: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   9879: 		    $loadm=$answer;
                   9880: 		    $unhome=$tryserver;
                   9881: 		}
1.80      www      9882: 	    }
                   9883:         }
                   9884:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  9885: 	    return 'error: unable to find a home server for '.$uname.
                   9886:                    ' in domain '.$udom;
1.80      www      9887:         }
                   9888:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   9889:                          &escape($upass),$unhome);
                   9890: 	unless ($reply eq 'ok') {
                   9891:             return 'error: '.$reply;
                   9892:         }   
1.230     stredwic 9893:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      9894:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  9895: 	    return 'error: unable verify users home machine.';
1.80      www      9896:         }
1.209     matthew  9897:     }   # End of creation of new user
1.80      www      9898: # ---------------------------------------------------------------------- Add ID
                   9899:     if ($uid) {
                   9900:        $uid=~tr/A-Z/a-z/;
                   9901:        my %uidhash=&idrget($udom,$uname);
1.196     www      9902:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   9903:          && (!$forceid)) {
1.80      www      9904: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  9905: 	      return 'error: user id "'.$uid.'" does not match '.
                   9906:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      9907:           }
                   9908:        } else {
                   9909: 	  &idput($udom,($uname => $uid));
                   9910:        }
                   9911:     }
                   9912: # -------------------------------------------------------------- Add names, etc
1.313     matthew  9913:     my @tmp=&get('environment',
1.899     raeburn  9914: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  9915:                     'permanentemail','inststatus'],
1.134     albertel 9916: 		   $udom,$uname);
1.1075    raeburn  9917:     my (%names,%oldnames);
1.313     matthew  9918:     if ($tmp[0] =~ m/^error:.*/) { 
                   9919:         %names=(); 
                   9920:     } else {
                   9921:         %names = @tmp;
1.1075    raeburn  9922:         %oldnames = %names;
1.313     matthew  9923:     }
1.388     www      9924: #
1.1058    raeburn  9925: # If name, email and/or uid are blank (e.g., because an uploaded file
                   9926: # of users did not contain them), do not overwrite existing values
                   9927: # unless field is in $candelete array ref.  
                   9928: #
                   9929: 
                   9930:     my @fields = ('firstname','middlename','lastname','generation',
                   9931:                   'permanentemail','id');
                   9932:     my %newvalues;
                   9933:     if (ref($candelete) eq 'ARRAY') {
                   9934:         foreach my $field (@fields) {
                   9935:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   9936:                 if ($field eq 'firstname') {
                   9937:                     $names{$field} = $first;
                   9938:                 } elsif ($field eq 'middlename') {
                   9939:                     $names{$field} = $middle;
                   9940:                 } elsif ($field eq 'lastname') {
                   9941:                     $names{$field} = $last;
                   9942:                 } elsif ($field eq 'generation') { 
                   9943:                     $names{$field} = $gene;
                   9944:                 } elsif ($field eq 'permanentemail') {
                   9945:                     $names{$field} = $email;
                   9946:                 } elsif ($field eq 'id') {
                   9947:                     $names{$field}  = $uid;
                   9948:                 }
                   9949:             }
                   9950:         }
                   9951:     }
1.388     www      9952:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  9953:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      9954:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  9955:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      9956:     if ($email) {
                   9957:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  9958:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      9959:     }
1.899     raeburn  9960:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  9961:     if (defined($inststatus)) {
                   9962:         $names{'inststatus'} = '';
                   9963:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   9964:         if (ref($usertypes) eq 'HASH') {
                   9965:             my @okstatuses; 
                   9966:             foreach my $item (split(/:/,$inststatus)) {
                   9967:                 if (defined($usertypes->{$item})) {
                   9968:                     push(@okstatuses,$item);  
                   9969:                 }
                   9970:             }
                   9971:             if (@okstatuses) {
                   9972:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   9973:             }
                   9974:         }
                   9975:     }
1.1075    raeburn  9976:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  9977:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  9978:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  9979:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   9980:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   9981:     } else {
                   9982:         $logmsg .= ' during self creation';
                   9983:     }
1.1075    raeburn  9984:     my $changed;
                   9985:     if ($newuser) {
                   9986:         $changed = 1;
                   9987:     } else {
                   9988:         foreach my $field (@fields) {
                   9989:             if ($names{$field} ne $oldnames{$field}) {
                   9990:                 $changed = 1;
                   9991:                 last;
                   9992:             }
                   9993:         }
                   9994:     }
                   9995:     unless ($changed) {
                   9996:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   9997:         &logthis($logmsg);
                   9998:         return 'ok';
                   9999:     }
                   10000:     my $reply = &put('environment', \%names, $udom,$uname);
                   10001:     if ($reply ne 'ok') { 
                   10002:         return 'error: '.$reply;
                   10003:     }
1.1087    raeburn  10004:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   10005:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   10006:     }
1.1075    raeburn  10007:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   10008:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   10009:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  10010:     &logthis($logmsg);
1.134     albertel 10011:     return 'ok';
1.80      www      10012: }
                   10013: 
1.81      www      10014: # -------------------------------------------------------------- Modify student
1.80      www      10015: 
1.81      www      10016: sub modifystudent {
                   10017:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  10018:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76  raeburn  10019:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 10020:     if (!$cid) {
1.620     albertel 10021: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10022: 	    return 'not_in_class';
                   10023: 	}
1.80      www      10024:     }
                   10025: # --------------------------------------------------------------- Make the user
1.81      www      10026:     my $reply=&modifyuser
1.209     matthew  10027: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  10028:          $desiredhome,$email,$inststatus);
1.80      www      10029:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  10030:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  10031:     # student's environment
1.297     matthew  10032:     $uid = undef if (!$forceid);
1.455     albertel 10033:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  10034: 					$gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76  raeburn  10035:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  10036:     return $reply;
                   10037: }
                   10038: 
                   10039: sub modify_student_enrollment {
1.1172.2.23  raeburn  10040:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76  raeburn  10041:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 10042:     my ($cdom,$cnum,$chome);
                   10043:     if (!$cid) {
1.620     albertel 10044: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10045: 	    return 'not_in_class';
                   10046: 	}
1.620     albertel 10047: 	$cdom=$env{'course.'.$cid.'.domain'};
                   10048: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 10049:     } else {
                   10050: 	($cdom,$cnum)=split(/_/,$cid);
                   10051:     }
1.620     albertel 10052:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 10053:     if (!$chome) {
1.457     raeburn  10054: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  10055:     }
1.455     albertel 10056:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  10057:     # Make sure the user exists
1.81      www      10058:     my $uhome=&homeserver($uname,$udom);
                   10059:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10060: 	return 'error: no such user';
                   10061:     }
1.297     matthew  10062:     # Get student data if we were not given enough information
                   10063:     if (!defined($first)  || $first  eq '' || 
                   10064:         !defined($last)   || $last   eq '' || 
                   10065:         !defined($uid)    || $uid    eq '' || 
                   10066:         !defined($middle) || $middle eq '' || 
                   10067:         !defined($gene)   || $gene   eq '') {
1.294     matthew  10068:         # They did not supply us with enough data to enroll the student, so
                   10069:         # we need to pick up more information.
1.297     matthew  10070:         my %tmp = &get('environment',
1.294     matthew  10071:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  10072:                        ,$udom,$uname);
                   10073: 
1.800     albertel 10074:         #foreach my $key (keys(%tmp)) {
                   10075:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 10076:         #}
1.294     matthew  10077:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   10078:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   10079:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  10080:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  10081:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   10082:     }
1.556     albertel 10083:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  10084:     my $user = "$uname:$udom";
                   10085:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 10086:     my $reply=cput('classlist',
1.1148    raeburn  10087: 		   {$user => 
1.1172.2.76  raeburn  10088: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 10089: 		   $cdom,$cnum);
1.1148    raeburn  10090:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   10091:         &devalidate_getsection_cache($udom,$uname,$cid);
                   10092:     } else { 
1.81      www      10093: 	return 'error: '.$reply;
                   10094:     }
1.297     matthew  10095:     # Add student role to user
1.83      www      10096:     my $uurl='/'.$cid;
1.81      www      10097:     $uurl=~s/\_/\//g;
                   10098:     if ($usec) {
                   10099: 	$uurl.='/'.$usec;
                   10100:     }
1.1148    raeburn  10101:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   10102:                              $selfenroll,$context);
                   10103:     if ($result ne 'ok') {
                   10104:         if ($old_entry{$user} ne '') {
                   10105:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   10106:         } else {
                   10107:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   10108:         }
                   10109:     }
                   10110:     return $result; 
1.21      www      10111: }
                   10112: 
1.556     albertel 10113: sub format_name {
                   10114:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   10115:     my $name;
                   10116:     if ($first ne 'lastname') {
                   10117: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   10118:     } else {
                   10119: 	if ($lastname=~/\S/) {
                   10120: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   10121: 	    $name=~s/\s+,/,/;
                   10122: 	} else {
                   10123: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   10124: 	}
                   10125:     }
                   10126:     $name=~s/^\s+//;
                   10127:     $name=~s/\s+$//;
                   10128:     $name=~s/\s+/ /g;
                   10129:     return $name;
                   10130: }
                   10131: 
1.84      www      10132: # ------------------------------------------------- Write to course preferences
                   10133: 
                   10134: sub writecoursepref {
                   10135:     my ($courseid,%prefs)=@_;
                   10136:     $courseid=~s/^\///;
                   10137:     $courseid=~s/\_/\//g;
                   10138:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   10139:     my $chome=homeserver($cnum,$cdomain);
                   10140:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   10141: 	return 'error: no such course';
                   10142:     }
                   10143:     my $cstring='';
1.800     albertel 10144:     foreach my $pref (keys(%prefs)) {
                   10145: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 10146:     }
1.84      www      10147:     $cstring=~s/\&$//;
                   10148:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   10149: }
                   10150: 
                   10151: # ---------------------------------------------------------- Make/modify course
                   10152: 
                   10153: sub createcourse {
1.741     raeburn  10154:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  10155:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      10156:     $url=&declutter($url);
                   10157:     my $cid='';
1.1028    raeburn  10158:     if ($context eq 'requestcourses') {
                   10159:         my $can_create = 0;
                   10160:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   10161:         if ($udom eq $ownerdom) {
                   10162:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   10163:                                   $context)) {
                   10164:                 $can_create = 1;
                   10165:             }
                   10166:         } else {
                   10167:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   10168:                                            $category);
                   10169:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   10170:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   10171:                 if (@curr > 0) {
                   10172:                     my @options = qw(approval validate autolimit);
                   10173:                     my $optregex = join('|',@options);
                   10174:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   10175:                         $can_create = 1;
                   10176:                     }
                   10177:                 }
                   10178:             }
                   10179:         }
                   10180:         if ($can_create) {
                   10181:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   10182:                 unless (&allowed('ccc',$udom)) {
                   10183:                     return 'refused'; 
                   10184:                 }
1.1017    raeburn  10185:             }
                   10186:         } else {
                   10187:             return 'refused';
                   10188:         }
1.1028    raeburn  10189:     } elsif (!&allowed('ccc',$udom)) {
                   10190:         return 'refused';
1.84      www      10191:     }
1.1011    raeburn  10192: # --------------------------------------------------------------- Get Unique ID
                   10193:     my $uname;
                   10194:     if ($cnum =~ /^$match_courseid$/) {
                   10195:         my $chome=&homeserver($cnum,$udom,'true');
                   10196:         if (($chome eq '') || ($chome eq 'no_host')) {
                   10197:             $uname = $cnum;
                   10198:         } else {
1.1038    raeburn  10199:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10200:         }
                   10201:     } else {
1.1038    raeburn  10202:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10203:     }
                   10204:     return $uname if ($uname =~ /^error/);
                   10205: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  10206:     if (!defined($course_server)) {
                   10207:         if (defined(&domain($udom,'primary'))) {
                   10208:             $course_server = &domain($udom,'primary');
                   10209:         } else {
                   10210:             $course_server = $env{'user.home'}; 
                   10211:         }
                   10212:     }
                   10213:     my %host_servers =
                   10214:         &Apache::lonnet::get_servers($udom,'library');
                   10215:     unless ($host_servers{$course_server}) {
                   10216:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  10217:     }
1.84      www      10218: # ------------------------------------------------------------- Make the course
                   10219:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  10220:                       $course_server);
1.84      www      10221:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  10222:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      10223:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10224: 	return 'error: no such course';
                   10225:     }
1.271     www      10226: # ----------------------------------------------------------------- Course made
1.516     raeburn  10227: # log existence
1.1029    raeburn  10228:     my $now = time;
1.918     raeburn  10229:     my $newcourse = {
                   10230:                     $udom.'_'.$uname => {
1.921     raeburn  10231:                                      description => $description,
                   10232:                                      inst_code   => $inst_code,
                   10233:                                      owner       => $course_owner,
                   10234:                                      type        => $crstype,
1.1029    raeburn  10235:                                      creator     => $env{'user.name'}.':'.
                   10236:                                                     $env{'user.domain'},
                   10237:                                      created     => $now,
                   10238:                                      context     => $context,
1.918     raeburn  10239:                                                 },
                   10240:                     };
1.921     raeburn  10241:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      10242: # set toplevel url
1.271     www      10243:     my $topurl=$url;
                   10244:     unless ($nonstandard) {
                   10245: # ------------------------------------------ For standard courses, make top url
                   10246:         my $mapurl=&clutter($url);
1.278     www      10247:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 10248:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      10249: <map>
                   10250: <resource id="1" type="start"></resource>
                   10251: <resource id="2" src="$mapurl"></resource>
                   10252: <resource id="3" type="finish"></resource>
                   10253: <link index="1" from="1" to="2"></link>
                   10254: <link index="2" from="2" to="3"></link>
                   10255: </map>
                   10256: ENDINITMAP
                   10257:         $topurl=&declutter(
1.638     albertel 10258:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      10259:                           );
                   10260:     }
                   10261: # ----------------------------------------------------------- Write preferences
1.84      www      10262:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  10263:                      ('description'              => $description,
                   10264:                       'url'                      => $topurl,
                   10265:                       'internal.creator'         => $env{'user.name'}.':'.
                   10266:                                                     $env{'user.domain'},
                   10267:                       'internal.created'         => $now,
                   10268:                       'internal.creationcontext' => $context)
                   10269:                     );
1.84      www      10270:     return '/'.$udom.'/'.$uname;
                   10271: }
                   10272: 
1.1011    raeburn  10273: # ------------------------------------------------------------------- Create ID
                   10274: sub generate_coursenum {
1.1038    raeburn  10275:     my ($udom,$crstype) = @_;
1.1011    raeburn  10276:     my $domdesc = &domain($udom);
                   10277:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  10278:     my $first;
                   10279:     if ($crstype eq 'Community') {
                   10280:         $first = '0';
                   10281:     } else {
                   10282:         $first = int(1+rand(9)); 
                   10283:     } 
                   10284:     my $uname=$first.
1.1011    raeburn  10285:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10286:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10287:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10288: # ----------------------------------------------- Make sure that does not exist
                   10289:     my $uhome=&homeserver($uname,$udom,'true');
                   10290:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  10291:         if ($crstype eq 'Community') {
                   10292:             $first = '0';
                   10293:         } else {
                   10294:             $first = int(1+rand(9));
                   10295:         }
                   10296:         $uname=$first.
1.1011    raeburn  10297:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10298:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10299:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10300:         $uhome=&homeserver($uname,$udom,'true');
                   10301:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   10302:             return 'error: unable to generate unique course-ID';
                   10303:         }
                   10304:     }
                   10305:     return $uname;
                   10306: }
                   10307: 
1.813     albertel 10308: sub is_course {
1.1167    droeschl 10309:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   10310:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
1.1172.2.95  raeburn  10311:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   10312:     my $uhome=&homeserver($cnum,$cdom);
                   10313:     my $iscourse;
                   10314:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   10315:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
                   10316:     } else {
                   10317:         my $hashid = $cdom.':'.$cnum;
                   10318:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   10319:         unless (defined($cached)) {
                   10320:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   10321:                                         $cnum,undef,undef,'.');
                   10322:             $iscourse = 0;
                   10323:             if (exists($courses{$cdom.'_'.$cnum})) {
                   10324:                 $iscourse = 1;
                   10325:             }
                   10326:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   10327:         }
                   10328:     }
                   10329:     return unless($iscourse);
1.1167    droeschl 10330:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 10331: }
                   10332: 
1.1015    raeburn  10333: sub store_userdata {
                   10334:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  10335:     my $result;
1.1016    raeburn  10336:     if ($datakey ne '') {
1.1013    raeburn  10337:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  10338:             if ($udom eq '' || $uname eq '') {
                   10339:                 $udom = $env{'user.domain'};
                   10340:                 $uname = $env{'user.name'};
                   10341:             }
                   10342:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  10343:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   10344:                 $result = 'error: no_host';
                   10345:             } else {
                   10346:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   10347:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   10348: 
                   10349:                 my $namevalue='';
                   10350:                 foreach my $key (keys(%{$storehash})) {
                   10351:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   10352:                 }
                   10353:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  10354:                 unless ($namespace eq 'courserequests') {
                   10355:                     $datakey = &escape($datakey);
                   10356:                 }
1.1105    raeburn  10357:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   10358:                                   $namevalue,$uhome);
1.1013    raeburn  10359:             }
                   10360:         } else {
                   10361:             $result = 'error: data to store was not a hash reference'; 
                   10362:         }
                   10363:     } else {
                   10364:         $result= 'error: invalid requestkey'; 
                   10365:     }
                   10366:     return $result;
                   10367: }
                   10368: 
1.21      www      10369: # ---------------------------------------------------------- Assign Custom Role
                   10370: 
                   10371: sub assigncustomrole {
1.957     raeburn  10372:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10373:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  10374:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      10375: }
                   10376: 
                   10377: # ----------------------------------------------------------------- Revoke Role
                   10378: 
                   10379: sub revokerole {
1.957     raeburn  10380:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10381:     my $now=time;
1.965     raeburn  10382:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      10383: }
                   10384: 
                   10385: # ---------------------------------------------------------- Revoke Custom Role
                   10386: 
                   10387: sub revokecustomrole {
1.957     raeburn  10388:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10389:     my $now=time;
1.357     www      10390:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  10391:            $deleteflag,$selfenroll,$context);
1.17      www      10392: }
                   10393: 
1.533     banghart 10394: # ------------------------------------------------------------ Disk usage
1.535     albertel 10395: sub diskusage {
1.955     raeburn  10396:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   10397:     $directorypath =~ s/\/$//;
                   10398:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   10399:                        .&escape($getpropath).':'.&escape($uname).':'
                   10400:                        .&escape($udom),homeserver($uname,$udom));
                   10401:     if ($listing eq 'unknown_cmd') {
                   10402:         if ($getpropath) {
                   10403:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   10404:         }
                   10405:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   10406:     }
1.514     albertel 10407:     return $listing;
1.512     banghart 10408: }
                   10409: 
1.566     banghart 10410: sub is_locked {
1.1096    raeburn  10411:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 10412:     my @check;
                   10413:     my $is_locked;
1.1093    raeburn  10414:     push (@check,$file_name);
1.613     albertel 10415:     my %locked = &get('file_permissions',\@check,
1.620     albertel 10416: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 10417:     my ($tmp)=keys(%locked);
                   10418:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  10419:     
1.566     banghart 10420:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  10421:         $is_locked = 'false';
                   10422:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  10423:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  10424:                $is_locked = 'true';
1.1096    raeburn  10425:                if (ref($which) eq 'ARRAY') {
                   10426:                    push(@{$which},$entry);
                   10427:                } else {
                   10428:                    last;
                   10429:                }
1.745     raeburn  10430:            }
                   10431:        }
1.566     banghart 10432:     } else {
                   10433:         $is_locked = 'false';
                   10434:     }
1.1093    raeburn  10435:     return $is_locked;
1.566     banghart 10436: }
                   10437: 
1.759     albertel 10438: sub declutter_portfile {
                   10439:     my ($file) = @_;
1.833     albertel 10440:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 10441:     return $file;
                   10442: }
                   10443: 
1.559     banghart 10444: # ------------------------------------------------------------- Mark as Read Only
                   10445: 
                   10446: sub mark_as_readonly {
                   10447:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 10448:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10449:     my ($tmp)=keys(%current_permissions);
                   10450:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 10451:     foreach my $file (@{$files}) {
1.759     albertel 10452: 	$file = &declutter_portfile($file);
1.561     banghart 10453:         push(@{$current_permissions{$file}},$what);
1.559     banghart 10454:     }
1.613     albertel 10455:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10456:     return;
                   10457: }
                   10458: 
1.572     banghart 10459: # ------------------------------------------------------------Save Selected Files
                   10460: 
                   10461: sub save_selected_files {
                   10462:     my ($user, $path, @files) = @_;
                   10463:     my $filename = $user."savedfiles";
1.573     banghart 10464:     my @other_files = &files_not_in_path($user, $path);
1.1172.2.96  raeburn  10465:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 10466:     foreach my $file (@files) {
1.620     albertel 10467:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 10468:     }
                   10469:     foreach my $file (@other_files) {
1.574     banghart 10470:         print (OUT $file."\n");
1.572     banghart 10471:     }
1.574     banghart 10472:     close (OUT);
1.572     banghart 10473:     return 'ok';
                   10474: }
                   10475: 
1.574     banghart 10476: sub clear_selected_files {
                   10477:     my ($user) = @_;
                   10478:     my $filename = $user."savedfiles";
1.1172.2.96  raeburn  10479:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 10480:     print (OUT undef);
                   10481:     close (OUT);
                   10482:     return ("ok");    
                   10483: }
                   10484: 
1.572     banghart 10485: sub files_in_path {
                   10486:     my ($user, $path) = @_;
                   10487:     my $filename = $user."savedfiles";
                   10488:     my %return_files;
1.1172.2.96  raeburn  10489:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 10490:     while (my $line_in = <IN>) {
1.574     banghart 10491:         chomp ($line_in);
                   10492:         my @paths_and_file = split (m!/!, $line_in);
                   10493:         my $file_part = pop (@paths_and_file);
                   10494:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 10495:         $path_part.='/';
                   10496:         my $path_and_file = $path_part.$file_part;
                   10497:         if ($path_part eq $path) {
                   10498:             $return_files{$file_part}= 'selected';
                   10499:         }
                   10500:     }
1.574     banghart 10501:     close (IN);
                   10502:     return (\%return_files);
1.572     banghart 10503: }
                   10504: 
                   10505: # called in portfolio select mode, to show files selected NOT in current directory
                   10506: sub files_not_in_path {
                   10507:     my ($user, $path) = @_;
                   10508:     my $filename = $user."savedfiles";
                   10509:     my @return_files;
                   10510:     my $path_part;
1.1172.2.96  raeburn  10511:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 10512:     while (my $line = <IN>) {
1.572     banghart 10513:         #ok, I know it's clunky, but I want it to work
1.800     albertel 10514:         my @paths_and_file = split(m|/|, $line);
                   10515:         my $file_part = pop(@paths_and_file);
                   10516:         chomp($file_part);
                   10517:         my $path_part = join('/', @paths_and_file);
1.572     banghart 10518:         $path_part .= '/';
                   10519:         my $path_and_file = $path_part.$file_part;
                   10520:         if ($path_part ne $path) {
1.800     albertel 10521:             push(@return_files, ($path_and_file));
1.572     banghart 10522:         }
                   10523:     }
1.800     albertel 10524:     close(OUT);
1.574     banghart 10525:     return (@return_files);
1.572     banghart 10526: }
                   10527: 
1.745     raeburn  10528: #----------------------------------------------Get portfolio file permissions
1.629     banghart 10529: 
1.745     raeburn  10530: sub get_portfile_permissions {
                   10531:     my ($domain,$user) = @_;
1.613     albertel 10532:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10533:     my ($tmp)=keys(%current_permissions);
                   10534:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10535:     return \%current_permissions;
                   10536: }
                   10537: 
                   10538: #---------------------------------------------Get portfolio file access controls
                   10539: 
1.749     raeburn  10540: sub get_access_controls {
1.745     raeburn  10541:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 10542:     my %access;
                   10543:     my $real_file = $file;
                   10544:     $file =~ s/\.meta$//;
1.745     raeburn  10545:     if (defined($file)) {
1.749     raeburn  10546:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   10547:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 10548:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  10549:             }
                   10550:         }
1.745     raeburn  10551:     } else {
1.749     raeburn  10552:         foreach my $key (keys(%{$current_permissions})) {
                   10553:             if ($key =~ /\0accesscontrol$/) {
                   10554:                 if (defined($group)) {
                   10555:                     if ($key !~ m-^\Q$group\E/-) {
                   10556:                         next;
                   10557:                     }
                   10558:                 }
                   10559:                 my ($fullpath) = split(/\0/,$key);
                   10560:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   10561:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   10562:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   10563:                     }
                   10564:                 }
                   10565:             }
                   10566:         }
                   10567:     }
                   10568:     return %access;
                   10569: }
                   10570: 
                   10571: sub modify_access_controls {
                   10572:     my ($file_name,$changes,$domain,$user)=@_;
                   10573:     my ($outcome,$deloutcome);
                   10574:     my %store_permissions;
                   10575:     my %new_values;
                   10576:     my %new_control;
                   10577:     my %translation;
                   10578:     my @deletions = ();
                   10579:     my $now = time;
                   10580:     if (exists($$changes{'activate'})) {
                   10581:         if (ref($$changes{'activate'}) eq 'HASH') {
                   10582:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   10583:             my $numnew = scalar(@newitems);
                   10584:             for (my $i=0; $i<$numnew; $i++) {
                   10585:                 my $newkey = $newitems[$i];
                   10586:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  10587:                 if ($newkey =~ /^\d+:/) { 
                   10588:                     $newkey =~ s/^(\d+)/$newid/;
                   10589:                     $translation{$1} = $newid;
                   10590:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   10591:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   10592:                     $translation{$1} = $newid;
                   10593:                 }
1.749     raeburn  10594:                 $new_values{$file_name."\0".$newkey} = 
                   10595:                                           $$changes{'activate'}{$newitems[$i]};
                   10596:                 $new_control{$newkey} = $now;
                   10597:             }
                   10598:         }
                   10599:     }
                   10600:     my %todelete;
                   10601:     my %changed_items;
                   10602:     foreach my $action ('delete','update') {
                   10603:         if (exists($$changes{$action})) {
                   10604:             if (ref($$changes{$action}) eq 'HASH') {
                   10605:                 foreach my $key (keys(%{$$changes{$action}})) {
                   10606:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   10607:                     if ($action eq 'delete') { 
                   10608:                         $todelete{$itemnum} = 1;
                   10609:                     } else {
                   10610:                         $changed_items{$itemnum} = $key;
                   10611:                     }
                   10612:                 }
1.745     raeburn  10613:             }
                   10614:         }
1.749     raeburn  10615:     }
                   10616:     # get lock on access controls for file.
                   10617:     my $lockhash = {
                   10618:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   10619:                                                        ':'.$env{'user.domain'},
                   10620:                    }; 
                   10621:     my $tries = 0;
                   10622:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10623:    
1.1172.2.79  raeburn  10624:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  10625:         $tries ++;
1.1172.2.79  raeburn  10626:         sleep(0.1);
1.749     raeburn  10627:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10628:     }
                   10629:     if ($gotlock eq 'ok') {
                   10630:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   10631:         my ($tmp)=keys(%curr_permissions);
                   10632:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   10633:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   10634:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   10635:             if (ref($curr_controls) eq 'HASH') {
                   10636:                 foreach my $control_item (keys(%{$curr_controls})) {
                   10637:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   10638:                     if (defined($todelete{$itemnum})) {
                   10639:                         push(@deletions,$file_name."\0".$control_item);
                   10640:                     } else {
                   10641:                         if (defined($changed_items{$itemnum})) {
                   10642:                             $new_control{$changed_items{$itemnum}} = $now;
                   10643:                             push(@deletions,$file_name."\0".$control_item);
                   10644:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   10645:                         } else {
                   10646:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   10647:                         }
                   10648:                     }
1.745     raeburn  10649:                 }
                   10650:             }
                   10651:         }
1.970     raeburn  10652:         my ($group);
                   10653:         if (&is_course($domain,$user)) {
                   10654:             ($group,my $file) = split(/\//,$file_name,2);
                   10655:         }
1.749     raeburn  10656:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   10657:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   10658:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   10659:         #  remove lock
                   10660:         my @del_lock = ($file_name."\0".'locked_access_records');
                   10661:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  10662:         my $sqlresult =
1.970     raeburn  10663:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  10664:                                     $group);
1.749     raeburn  10665:     } else {
                   10666:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  10667:     }
1.749     raeburn  10668:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  10669: }
                   10670: 
1.827     raeburn  10671: sub make_public_indefinitely {
                   10672:     my ($requrl) = @_;
                   10673:     my $now = time;
                   10674:     my $action = 'activate';
                   10675:     my $aclnum = 0;
                   10676:     if (&is_portfolio_url($requrl)) {
                   10677:         my (undef,$udom,$unum,$file_name,$group) =
                   10678:             &parse_portfolio_url($requrl);
                   10679:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   10680:         my %access_controls = &get_access_controls($current_perms,
                   10681:                                                    $group,$file_name);
                   10682:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   10683:             my ($num,$scope,$end,$start) = 
                   10684:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   10685:             if ($scope eq 'public') {
                   10686:                 if ($start <= $now && $end == 0) {
                   10687:                     $action = 'none';
                   10688:                 } else {
                   10689:                     $action = 'update';
                   10690:                     $aclnum = $num;
                   10691:                 }
                   10692:                 last;
                   10693:             }
                   10694:         }
                   10695:         if ($action eq 'none') {
                   10696:              return 'ok';
                   10697:         } else {
                   10698:             my %changes;
                   10699:             my $newend = 0;
                   10700:             my $newstart = $now;
                   10701:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   10702:             $changes{$action}{$newkey} = {
                   10703:                 type => 'public',
                   10704:                 time => {
                   10705:                     start => $newstart,
                   10706:                     end   => $newend,
                   10707:                 },
                   10708:             };
                   10709:             my ($outcome,$deloutcome,$new_values,$translation) =
                   10710:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   10711:             return $outcome;
                   10712:         }
                   10713:     } else {
                   10714:         return 'invalid';
                   10715:     }
                   10716: }
                   10717: 
1.745     raeburn  10718: #------------------------------------------------------Get Marked as Read Only
                   10719: 
                   10720: sub get_marked_as_readonly {
                   10721:     my ($domain,$user,$what,$group) = @_;
                   10722:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 10723:     my @readonly_files;
1.629     banghart 10724:     my $cmp1=$what;
                   10725:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  10726:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10727:         if (defined($group)) {
                   10728:             if ($file_name !~ m-^\Q$group\E/-) {
                   10729:                 next;
                   10730:             }
                   10731:         }
1.561     banghart 10732:         if (ref($value) eq "ARRAY"){
                   10733:             foreach my $stored_what (@{$value}) {
1.629     banghart 10734:                 my $cmp2=$stored_what;
1.759     albertel 10735:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  10736:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  10737:                 }
1.629     banghart 10738:                 if ($cmp1 eq $cmp2) {
1.561     banghart 10739:                     push(@readonly_files, $file_name);
1.745     raeburn  10740:                     last;
1.563     banghart 10741:                 } elsif (!defined($what)) {
                   10742:                     push(@readonly_files, $file_name);
1.745     raeburn  10743:                     last;
1.561     banghart 10744:                 }
                   10745:             }
1.745     raeburn  10746:         }
1.561     banghart 10747:     }
                   10748:     return @readonly_files;
                   10749: }
1.577     banghart 10750: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 10751: 
1.577     banghart 10752: sub get_marked_as_readonly_hash {
1.745     raeburn  10753:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 10754:     my %readonly_files;
1.745     raeburn  10755:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10756:         if (defined($group)) {
                   10757:             if ($file_name !~ m-^\Q$group\E/-) {
                   10758:                 next;
                   10759:             }
                   10760:         }
1.577     banghart 10761:         if (ref($value) eq "ARRAY"){
                   10762:             foreach my $stored_what (@{$value}) {
1.745     raeburn  10763:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 10764:                     foreach my $lock_descriptor(@{$stored_what}) {
                   10765:                         if ($lock_descriptor eq 'graded') {
                   10766:                             $readonly_files{$file_name} = 'graded';
                   10767:                         } elsif ($lock_descriptor eq 'handback') {
                   10768:                             $readonly_files{$file_name} = 'handback';
                   10769:                         } else {
                   10770:                             if (!exists($readonly_files{$file_name})) {
                   10771:                                 $readonly_files{$file_name} = 'locked';
                   10772:                             }
                   10773:                         }
1.745     raeburn  10774:                     }
1.750     banghart 10775:                 } 
1.577     banghart 10776:             }
                   10777:         } 
                   10778:     }
                   10779:     return %readonly_files;
                   10780: }
1.559     banghart 10781: # ------------------------------------------------------------ Unmark as Read Only
                   10782: 
                   10783: sub unmark_as_readonly {
1.629     banghart 10784:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   10785:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  10786:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 10787:     $file_name = &declutter_portfile($file_name);
1.634     albertel 10788:     my $symb_crs = $what;
                   10789:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  10790:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 10791:     my ($tmp)=keys(%current_permissions);
                   10792:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10793:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 10794:     foreach my $file (@readonly_files) {
1.759     albertel 10795: 	my $clean_file = &declutter_portfile($file);
                   10796: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 10797: 	my $current_locks = $current_permissions{$file};
1.563     banghart 10798:         my @new_locks;
                   10799:         my @del_keys;
                   10800:         if (ref($current_locks) eq "ARRAY"){
                   10801:             foreach my $locker (@{$current_locks}) {
1.632     albertel 10802:                 my $compare=$locker;
1.749     raeburn  10803:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  10804:                     $compare=join('',@{$locker});
1.746     raeburn  10805:                     if ($compare ne $symb_crs) {
                   10806:                         push(@new_locks, $locker);
                   10807:                     }
1.563     banghart 10808:                 }
                   10809:             }
1.650     albertel 10810:             if (scalar(@new_locks) > 0) {
1.563     banghart 10811:                 $current_permissions{$file} = \@new_locks;
                   10812:             } else {
                   10813:                 push(@del_keys, $file);
1.613     albertel 10814:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 10815:                 delete($current_permissions{$file});
1.563     banghart 10816:             }
                   10817:         }
1.561     banghart 10818:     }
1.613     albertel 10819:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10820:     return;
                   10821: }
1.512     banghart 10822: 
1.17      www      10823: # ------------------------------------------------------------ Directory lister
                   10824: 
                   10825: sub dirlist {
1.955     raeburn  10826:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      10827:     $uri=~s/^\///;
                   10828:     $uri=~s/\/$//;
1.253     stredwic 10829:     my ($udom, $uname);
1.955     raeburn  10830:     if ($getuserdir) {
1.253     stredwic 10831:         $udom = $userdomain;
                   10832:         $uname = $username;
1.955     raeburn  10833:     } else {
                   10834:         (undef,$udom,$uname)=split(/\//,$uri);
                   10835:         if(defined($userdomain)) {
                   10836:             $udom = $userdomain;
                   10837:         }
                   10838:         if(defined($username)) {
                   10839:             $uname = $username;
                   10840:         }
1.253     stredwic 10841:     }
1.955     raeburn  10842:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 10843: 
1.955     raeburn  10844:     $dirRoot = $perlvar{'lonDocRoot'};
                   10845:     if (defined($getpropath)) {
                   10846:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 10847:         $dirRoot =~ s/\/$//;
1.955     raeburn  10848:     } elsif (defined($getuserdir)) {
                   10849:         my $subdir=$uname.'__';
                   10850:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   10851:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   10852:                    ."/$udom/$subdir/$uname";
                   10853:     } elsif (defined($alternateRoot)) {
                   10854:         $dirRoot = $alternateRoot;
1.751     banghart 10855:     }
1.253     stredwic 10856: 
                   10857:     if($udom) {
                   10858:         if($uname) {
1.1135    raeburn  10859:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  10860:             if ($uhome eq 'no_host') {
                   10861:                 return ([],'no_host');
                   10862:             }
1.955     raeburn  10863:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  10864:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  10865:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  10866:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10867:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  10868:             } else {
                   10869:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10870:             }
1.605     matthew  10871:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10872:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  10873:                 @listing_results = split(/:/,$listing);
                   10874:             } else {
                   10875:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10876:             }
1.1135    raeburn  10877:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  10878:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10879:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10880:                 return ([],$listing);
                   10881:             } else {
                   10882:                 return (\@listing_results);
1.1135    raeburn  10883:             }
1.955     raeburn  10884:         } elsif(!$alternateRoot) {
1.1136    raeburn  10885:             my (%allusers,%listerror);
1.841     albertel 10886: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  10887:  	    foreach my $tryserver (keys(%servers)) {
                   10888:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   10889:                                   &escape($udom),$tryserver);
                   10890:                 if ($listing eq 'unknown_cmd') {
                   10891: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10892: 				      $udom, $tryserver);
                   10893:                 } else {
                   10894:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10895:                 }
1.841     albertel 10896: 		if ($listing eq 'unknown_cmd') {
                   10897: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10898: 				      $udom, $tryserver);
                   10899: 		    @listing_results = split(/:/,$listing);
                   10900: 		} else {
                   10901: 		    @listing_results =
                   10902: 			map { &unescape($_); } split(/:/,$listing);
                   10903: 		}
1.1136    raeburn  10904:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   10905:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10906:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10907:                     $listerror{$tryserver} = $listing;
                   10908:                 } else {
1.841     albertel 10909: 		    foreach my $line (@listing_results) {
                   10910: 			my ($entry) = split(/&/,$line,2);
                   10911: 			$allusers{$entry} = 1;
                   10912: 		    }
                   10913: 		}
1.253     stredwic 10914:             }
1.1136    raeburn  10915:             my @alluserslist=();
1.800     albertel 10916:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  10917:                 push(@alluserslist,$user.'&user');
1.253     stredwic 10918:             }
1.1172.2.80  raeburn  10919:             if (!%listerror) {
                   10920:                 # no errors
                   10921:                 return (\@alluserslist);
                   10922:             } elsif (scalar(keys(%servers)) == 1) {
                   10923:                 # one library server, one error
                   10924:                 my ($key) = keys(%listerror);
                   10925:                 return (\@alluserslist, $listerror{$key});
                   10926:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   10927:                 # con_lost indicates that we might miss data from at least one
                   10928:                 # library server
                   10929:                 return (\@alluserslist, 'con_lost');
                   10930:             } else {
                   10931:                 # multiple library servers and no con_lost -> data should be
                   10932:                 # complete.
                   10933:                 return (\@alluserslist);
                   10934:             }
                   10935: 
1.253     stredwic 10936:         } else {
1.1136    raeburn  10937:             return ([],'missing username');
1.253     stredwic 10938:         }
1.955     raeburn  10939:     } elsif(!defined($getpropath)) {
1.1136    raeburn  10940:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   10941:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   10942:         return (\@all_domains);
1.955     raeburn  10943:     } else {
1.1136    raeburn  10944:         return ([],'missing domain');
1.275     stredwic 10945:     }
                   10946: }
                   10947: 
                   10948: # --------------------------------------------- GetFileTimestamp
                   10949: # This function utilizes dirlist and returns the date stamp for
                   10950: # when it was last modified.  It will also return an error of -1
                   10951: # if an error occurs
                   10952: 
                   10953: sub GetFileTimestamp {
1.955     raeburn  10954:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 10955:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   10956:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  10957:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   10958:                                     undef,$getuserdir);
                   10959:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10960:         return -1;
                   10961:     }
                   10962:     if (ref($fileref) eq 'ARRAY') {
                   10963:         my @stats = split('&',$fileref->[0]);
1.375     matthew  10964:         # @stats contains first the filename, then the stat output
                   10965:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 10966:     } else {
                   10967:         return -1;
1.253     stredwic 10968:     }
1.26      www      10969: }
                   10970: 
1.712     albertel 10971: sub stat_file {
                   10972:     my ($uri) = @_;
1.787     albertel 10973:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 10974: 
1.955     raeburn  10975:     my ($udom,$uname,$file);
1.712     albertel 10976:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   10977: 	($udom,$uname,$file) =
1.811     albertel 10978: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 10979: 	$file = 'userfiles/'.$file;
                   10980:     }
                   10981:     if ($uri =~ m-^/res/-) {
                   10982: 	($udom,$uname) = 
1.807     albertel 10983: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 10984: 	$file = $uri;
                   10985:     }
                   10986: 
                   10987:     if (!$udom || !$uname || !$file) {
                   10988: 	# unable to handle the uri
                   10989: 	return ();
                   10990:     }
1.956     raeburn  10991:     my $getpropath;
                   10992:     if ($file =~ /^userfiles\//) {
                   10993:         $getpropath = 1;
                   10994:     }
1.1136    raeburn  10995:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   10996:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10997:         return ();
                   10998:     } else {
                   10999:         if (ref($listref) eq 'ARRAY') {
                   11000:             my @stats = split('&',$listref->[0]);
                   11001: 	    shift(@stats); #filename is first
                   11002: 	    return @stats;
                   11003:         }
1.712     albertel 11004:     }
                   11005:     return ();
                   11006: }
                   11007: 
1.26      www      11008: # -------------------------------------------------------- Value of a Condition
                   11009: 
1.713     albertel 11010: # gets the value of a specific preevaluated condition
                   11011: #    stored in the string  $env{user.state.<cid>}
                   11012: # or looks up a condition reference in the bighash and if if hasn't
                   11013: # already been evaluated recurses into docondval to get the value of
                   11014: # the condition, then memoizing it to 
                   11015: #   $env{user.state.<cid>.<condition>}
1.40      www      11016: sub directcondval {
                   11017:     my $number=shift;
1.620     albertel 11018:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 11019: 	&Apache::lonuserstate::evalstate();
                   11020:     }
1.713     albertel 11021:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   11022: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   11023:     } elsif ($number =~ /^_/) {
                   11024: 	my $sub_condition;
                   11025: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11026: 		&GDBM_READER(),0640)) {
                   11027: 	    $sub_condition=$bighash{'conditions'.$number};
                   11028: 	    untie(%bighash);
                   11029: 	}
                   11030: 	my $value = &docondval($sub_condition);
1.949     raeburn  11031: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 11032: 	return $value;
                   11033:     }
1.620     albertel 11034:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   11035:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      11036:     } else {
                   11037:        return 2;
                   11038:     }
                   11039: }
                   11040: 
1.713     albertel 11041: # get the collection of conditions for this resource
1.26      www      11042: sub condval {
                   11043:     my $condidx=shift;
1.54      www      11044:     my $allpathcond='';
1.713     albertel 11045:     foreach my $cond (split(/\|/,$condidx)) {
                   11046: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   11047: 	    $allpathcond.=
                   11048: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   11049: 	}
1.191     harris41 11050:     }
1.54      www      11051:     $allpathcond=~s/\|$//;
1.713     albertel 11052:     return &docondval($allpathcond);
                   11053: }
                   11054: 
                   11055: #evaluates an expression of conditions
                   11056: sub docondval {
                   11057:     my ($allpathcond) = @_;
                   11058:     my $result=0;
                   11059:     if ($env{'request.course.id'}
                   11060: 	&& defined($allpathcond)) {
                   11061: 	my $operand='|';
                   11062: 	my @stack;
                   11063: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   11064: 	    if ($chunk eq '(') {
                   11065: 		push @stack,($operand,$result);
                   11066: 	    } elsif ($chunk eq ')') {
                   11067: 		my $before=pop @stack;
                   11068: 		if (pop @stack eq '&') {
                   11069: 		    $result=$result>$before?$before:$result;
                   11070: 		} else {
                   11071: 		    $result=$result>$before?$result:$before;
                   11072: 		}
                   11073: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   11074: 		$operand=$chunk;
                   11075: 	    } else {
                   11076: 		my $new=directcondval($chunk);
                   11077: 		if ($operand eq '&') {
                   11078: 		    $result=$result>$new?$new:$result;
                   11079: 		} else {
                   11080: 		    $result=$result>$new?$result:$new;
                   11081: 		}
                   11082: 	    }
                   11083: 	}
1.26      www      11084:     }
                   11085:     return $result;
1.421     albertel 11086: }
                   11087: 
                   11088: # ---------------------------------------------------- Devalidate courseresdata
                   11089: 
                   11090: sub devalidatecourseresdata {
                   11091:     my ($coursenum,$coursedomain)=@_;
                   11092:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11093:     &devalidate_cache_new('courseres',$hashid);
1.28      www      11094: }
                   11095: 
1.763     www      11096: 
1.200     www      11097: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     11098: #
                   11099: #  Parameters:
                   11100: #      $coursenum    - Number of the course.
                   11101: #      $coursedomain - Domain at which the course was created.
                   11102: #  Returns:
                   11103: #     A hash of the course parameters along (I think) with timestamps
                   11104: #     and version info.
1.877     foxr     11105: 
1.624     albertel 11106: sub get_courseresdata {
                   11107:     my ($coursenum,$coursedomain)=@_;
1.200     www      11108:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   11109:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11110:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 11111:     my %dumpreply;
1.417     albertel 11112:     unless (defined($cached)) {
1.624     albertel 11113: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 11114: 	$result=\%dumpreply;
1.251     albertel 11115: 	my ($tmp) = keys(%dumpreply);
                   11116: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 11117: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 11118: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   11119: 	    return $tmp;
1.416     albertel 11120: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 11121: 	    $result=undef;
1.599     albertel 11122: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 11123: 	}
                   11124:     }
1.624     albertel 11125:     return $result;
                   11126: }
                   11127: 
1.633     albertel 11128: sub devalidateuserresdata {
                   11129:     my ($uname,$udom)=@_;
                   11130:     my $hashid="$udom:$uname";
                   11131:     &devalidate_cache_new('userres',$hashid);
                   11132: }
                   11133: 
1.624     albertel 11134: sub get_userresdata {
                   11135:     my ($uname,$udom)=@_;
                   11136:     #most student don\'t have any data set, check if there is some data
                   11137:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   11138: 
                   11139:     my $hashid="$udom:$uname";
                   11140:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   11141:     if (!defined($cached)) {
                   11142: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   11143: 	$result=\%resourcedata;
                   11144: 	&do_cache_new('userres',$hashid,$result,600);
                   11145:     }
                   11146:     my ($tmp)=keys(%$result);
                   11147:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   11148: 	return $result;
                   11149:     }
                   11150:     #error 2 occurs when the .db doesn't exist
                   11151:     if ($tmp!~/error: 2 /) {
1.1172.2.71  raeburn  11152:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   11153: 	    &logthis("<font color=\"blue\">WARNING:".
                   11154: 		     " Trying to get resource data for ".
                   11155: 		     $uname." at ".$udom.": ".
                   11156: 		     $tmp."</font>");
                   11157:         }
1.624     albertel 11158:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 11159: 	#&EXT_cache_set($udom,$uname);
                   11160: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 11161: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 11162:     }
                   11163:     return $tmp;
                   11164: }
1.879     foxr     11165: #----------------------------------------------- resdata - return resource data
                   11166: #  Purpose:
                   11167: #    Return resource data for either users or for a course.
                   11168: #  Parameters:
                   11169: #     $name      - Course/user name.
                   11170: #     $domain    - Name of the domain the user/course is registered on.
                   11171: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   11172: #     @which     - Array of names of resources desired.
                   11173: #  Returns:
                   11174: #     The value of the first reasource in @which that is found in the
                   11175: #     resource hash.
                   11176: #  Exceptional Conditions:
                   11177: #     If the $type passed in is not valid (not the string 'course' or 
                   11178: #     'user', an undefined  reference is returned.
                   11179: #     If none of the resources are found, an undef is returned
1.624     albertel 11180: sub resdata {
                   11181:     my ($name,$domain,$type,@which)=@_;
                   11182:     my $result;
                   11183:     if ($type eq 'course') {
                   11184: 	$result=&get_courseresdata($name,$domain);
                   11185:     } elsif ($type eq 'user') {
                   11186: 	$result=&get_userresdata($name,$domain);
                   11187:     }
                   11188:     if (!ref($result)) { return $result; }    
1.251     albertel 11189:     foreach my $item (@which) {
1.927     albertel 11190: 	if (defined($result->{$item->[0]})) {
                   11191: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 11192: 	}
1.250     albertel 11193:     }
1.291     albertel 11194:     return undef;
1.200     www      11195: }
                   11196: 
1.1172.2.31  raeburn  11197: sub get_numsuppfiles {
                   11198:     my ($cnum,$cdom,$ignorecache)=@_;
                   11199:     my $hashid=$cnum.':'.$cdom;
                   11200:     my ($suppcount,$cached);
                   11201:     unless ($ignorecache) {
                   11202:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   11203:     }
                   11204:     unless (defined($cached)) {
                   11205:         my $chome=&homeserver($cnum,$cdom);
                   11206:         unless ($chome eq 'no_host') {
                   11207:             ($suppcount,my $errors) = (0,0);
                   11208:             my $suppmap = 'supplemental.sequence';
                   11209:             ($suppcount,$errors) =
                   11210:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   11211:         }
                   11212:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   11213:     }
                   11214:     return $suppcount;
                   11215: }
                   11216: 
1.379     matthew  11217: #
                   11218: # EXT resource caching routines
                   11219: #
                   11220: 
                   11221: sub clear_EXT_cache_status {
1.383     albertel 11222:     &delenv('cache.EXT.');
1.379     matthew  11223: }
                   11224: 
                   11225: sub EXT_cache_status {
                   11226:     my ($target_domain,$target_user) = @_;
1.383     albertel 11227:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 11228:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  11229:         # We know already the user has no data
                   11230:         return 1;
                   11231:     } else {
                   11232:         return 0;
                   11233:     }
                   11234: }
                   11235: 
                   11236: sub EXT_cache_set {
                   11237:     my ($target_domain,$target_user) = @_;
1.383     albertel 11238:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  11239:     #&appenv({$cachename => time});
1.379     matthew  11240: }
                   11241: 
1.28      www      11242: # --------------------------------------------------------- Value of a Variable
1.58      www      11243: sub EXT {
1.715     albertel 11244: 
1.1172.2.28  raeburn  11245:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      11246:     unless ($varname) { return ''; }
1.218     albertel 11247:     #get real user name/domain, courseid and symb
                   11248:     my $courseid;
1.359     albertel 11249:     my $publicuser;
1.427     www      11250:     if ($symbparm) {
                   11251: 	$symbparm=&get_symb_from_alias($symbparm);
                   11252:     }
1.218     albertel 11253:     if (!($uname && $udom)) {
1.790     albertel 11254:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 11255:       if (!$symbparm) {	$symbparm=$cursymb; }
                   11256:     } else {
1.620     albertel 11257: 	$courseid=$env{'request.course.id'};
1.218     albertel 11258:     }
1.48      www      11259:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   11260:     my $rest;
1.320     albertel 11261:     if (defined($therest[0])) {
1.48      www      11262:        $rest=join('.',@therest);
                   11263:     } else {
                   11264:        $rest='';
                   11265:     }
1.320     albertel 11266: 
1.57      www      11267:     my $qualifierrest=$qualifier;
                   11268:     if ($rest) { $qualifierrest.='.'.$rest; }
                   11269:     my $spacequalifierrest=$space;
                   11270:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      11271:     if ($realm eq 'user') {
1.48      www      11272: # --------------------------------------------------------------- user.resource
                   11273: 	if ($space eq 'resource') {
1.651     albertel 11274: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   11275: 		  || defined($Apache::lonhomework::parsing_a_task))
                   11276: 		 &&
1.744     albertel 11277: 		 ($symbparm eq &symbread()) ) {	
                   11278: 		# if we are in the middle of processing the resource the
                   11279: 		# get the value we are planning on committing
                   11280:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   11281:                     return $Apache::lonhomework::results{$qualifierrest};
                   11282:                 } else {
                   11283:                     return $Apache::lonhomework::history{$qualifierrest};
                   11284:                 }
1.335     albertel 11285: 	    } else {
1.359     albertel 11286: 		my %restored;
1.620     albertel 11287: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 11288: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   11289: 		} else {
                   11290: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   11291: 		}
1.335     albertel 11292: 		return $restored{$qualifierrest};
                   11293: 	    }
1.48      www      11294: # ----------------------------------------------------------------- user.access
                   11295:         } elsif ($space eq 'access') {
1.218     albertel 11296: 	    # FIXME - not supporting calls for a specific user
1.48      www      11297:             return &allowed($qualifier,$rest);
                   11298: # ------------------------------------------ user.preferences, user.environment
                   11299:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 11300: 	    if (($uname eq $env{'user.name'}) &&
                   11301: 		($udom eq $env{'user.domain'})) {
                   11302: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 11303: 	    } else {
1.359     albertel 11304: 		my %returnhash;
                   11305: 		if (!$publicuser) {
                   11306: 		    %returnhash=&userenvironment($udom,$uname,
                   11307: 						 $qualifierrest);
                   11308: 		}
1.218     albertel 11309: 		return $returnhash{$qualifierrest};
                   11310: 	    }
1.48      www      11311: # ----------------------------------------------------------------- user.course
                   11312:         } elsif ($space eq 'course') {
1.218     albertel 11313: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11314:             return $env{join('.',('request.course',$qualifier))};
1.48      www      11315: # ------------------------------------------------------------------- user.role
                   11316:         } elsif ($space eq 'role') {
1.218     albertel 11317: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11318:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      11319:             if ($qualifier eq 'value') {
                   11320: 		return $role;
                   11321:             } elsif ($qualifier eq 'extent') {
                   11322:                 return $where;
                   11323:             }
                   11324: # ----------------------------------------------------------------- user.domain
                   11325:         } elsif ($space eq 'domain') {
1.218     albertel 11326:             return $udom;
1.48      www      11327: # ------------------------------------------------------------------- user.name
                   11328:         } elsif ($space eq 'name') {
1.218     albertel 11329:             return $uname;
1.48      www      11330: # ---------------------------------------------------- Any other user namespace
1.29      www      11331:         } else {
1.359     albertel 11332: 	    my %reply;
                   11333: 	    if (!$publicuser) {
                   11334: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   11335: 	    }
                   11336: 	    return $reply{$qualifierrest};
1.48      www      11337:         }
1.236     www      11338:     } elsif ($realm eq 'query') {
                   11339: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 11340:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   11341: 						[$spacequalifierrest]);
1.620     albertel 11342: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      11343:    } elsif ($realm eq 'request') {
1.48      www      11344: # ------------------------------------------------------------- request.browser
                   11345:         if ($space eq 'browser') {
1.1145    bisitz   11346:             return $env{'browser.'.$qualifier};
1.57      www      11347: # ------------------------------------------------------------ request.filename
                   11348:         } else {
1.620     albertel 11349:             return $env{'request.'.$spacequalifierrest};
1.29      www      11350:         }
1.28      www      11351:     } elsif ($realm eq 'course') {
1.48      www      11352: # ---------------------------------------------------------- course.description
1.620     albertel 11353:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      11354:     } elsif ($realm eq 'resource') {
1.165     www      11355: 
1.620     albertel 11356: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 11357: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   11358: 	}
1.693     albertel 11359: 
1.1172.2.30  raeburn  11360:         if ($qualifier eq '') {
                   11361: 	    if ($space eq 'title') {
                   11362: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   11363: 	        return &gettitle($symbparm);
                   11364: 	    }
1.693     albertel 11365: 	
1.1172.2.30  raeburn  11366: 	    if ($space eq 'map') {
                   11367: 	        my ($map) = &decode_symb($symbparm);
                   11368: 	        return &symbread($map);
                   11369: 	    }
                   11370:             if ($space eq 'maptitle') {
                   11371:                 my ($map) = &decode_symb($symbparm);
                   11372:                 return &gettitle($map);
                   11373:             }
                   11374: 	    if ($space eq 'filename') {
                   11375: 	        if ($symbparm) {
                   11376: 		    return &clutter((&decode_symb($symbparm))[2]);
                   11377: 	        }
                   11378: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 11379: 	    }
1.1172.2.30  raeburn  11380: 
                   11381:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   11382:                 if ($space eq 'visibleparts') {
                   11383:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   11384:                     my $item;
                   11385:                     if (ref($navmap)) {
                   11386:                         my $res = $navmap->getBySymb($symbparm);
                   11387:                         my $parts = $res->parts();
                   11388:                         if (ref($parts) eq 'ARRAY') {
                   11389:                             $item = join(',',@{$parts});
                   11390:                         }
                   11391:                         undef($navmap);
                   11392:                     }
                   11393:                     return $item;
                   11394:                 }
                   11395:             }
                   11396:         }
1.693     albertel 11397: 
                   11398: 	my ($section, $group, @groups);
1.593     albertel 11399: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  11400:         if (($courseid eq '') && ($cid)) {
                   11401:             $courseid = $cid;
                   11402:         }
                   11403: 	if (($symbparm && $courseid) && 
                   11404: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      11405: 
1.218     albertel 11406: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      11407: 
1.60      www      11408: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 11409: 	    my $symbp=$symbparm;
1.735     albertel 11410: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 11411: 
                   11412: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   11413: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   11414: 
1.620     albertel 11415: 	    if (($env{'user.name'} eq $uname) &&
                   11416: 		($env{'user.domain'} eq $udom)) {
                   11417: 		$section=$env{'request.course.sec'};
1.733     raeburn  11418:                 @groups = split(/:/,$env{'request.course.groups'});  
                   11419:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 11420: 	    } else {
1.539     albertel 11421: 		if (! defined($usection)) {
1.551     albertel 11422: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 11423: 		} else {
                   11424: 		    $section = $usection;
                   11425: 		}
1.733     raeburn  11426:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 11427: 	    }
                   11428: 
                   11429: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   11430: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   11431: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   11432: 
1.593     albertel 11433: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 11434: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 11435: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      11436: 
1.60      www      11437: # ----------------------------------------------------------- first, check user
1.624     albertel 11438: 
                   11439: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 11440: 				       ([$courselevelr,'resource'],
                   11441: 					[$courselevelm,'map'     ],
                   11442: 					[$courselevel, 'course'  ]));
1.931     albertel 11443: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      11444: 
1.594     albertel 11445: # ------------------------------------------------ second, check some of course
1.684     raeburn  11446:             my $coursereply;
1.691     raeburn  11447:             if (@groups > 0) {
                   11448:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   11449:                                        $mapparm,$spacequalifierrest);
1.927     albertel 11450:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  11451:             }
1.96      www      11452: 
1.684     raeburn  11453: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 11454: 				  $env{'course.'.$courseid.'.domain'},
                   11455: 				  'course',
                   11456: 				  ([$seclevelr,   'resource'],
                   11457: 				   [$seclevelm,   'map'     ],
                   11458: 				   [$seclevel,    'course'  ],
                   11459: 				   [$courselevelr,'resource']));
                   11460: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      11461: 
1.60      www      11462: # ------------------------------------------------------ third, check map parms
1.218     albertel 11463: 	    my %parmhash=();
                   11464: 	    my $thisparm='';
                   11465: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 11466: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 11467: 		    &GDBM_READER(),0640)) {
1.218     albertel 11468: 		$thisparm=$parmhash{$symbparm};
                   11469: 		untie(%parmhash);
                   11470: 	    }
1.927     albertel 11471: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 11472: 	}
1.594     albertel 11473: # ------------------------------------------ fourth, look in resource metadata
1.71      www      11474: 
1.218     albertel 11475: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 11476: 	my $filename;
                   11477: 	if (!$symbparm) { $symbparm=&symbread(); }
                   11478: 	if ($symbparm) {
1.409     www      11479: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 11480: 	} else {
1.620     albertel 11481: 	    $filename=$env{'request.filename'};
1.282     albertel 11482: 	}
                   11483: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 11484: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 11485: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 11486: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      11487: 
1.927     albertel 11488: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 11489: 	if ($symbparm && defined($courseid) && 
1.620     albertel 11490: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 11491: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   11492: 				     $env{'course.'.$courseid.'.domain'},
                   11493: 				     'course',
1.927     albertel 11494: 				     ([$courselevelm,'map'   ],
                   11495: 				      [$courselevel, 'course']));
                   11496: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 11497: 	}
1.145     www      11498: # ------------------------------------------------------------------ Cascade up
1.218     albertel 11499: 	unless ($space eq '0') {
1.336     albertel 11500: 	    my @parts=split(/_/,$space);
                   11501: 	    my $id=pop(@parts);
                   11502: 	    my $part=join('_',@parts);
                   11503: 	    if ($part eq '') { $part='0'; }
1.927     albertel 11504: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 11505: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  11506: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 11507: 	}
1.395     albertel 11508: 	if ($recurse) { return undef; }
                   11509: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 11510: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      11511: # ---------------------------------------------------- Any other user namespace
                   11512:     } elsif ($realm eq 'environment') {
                   11513: # ----------------------------------------------------------------- environment
1.620     albertel 11514: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   11515: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 11516: 	} else {
1.770     albertel 11517: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   11518: 		return '';
                   11519: 	    }
1.219     albertel 11520: 	    my %returnhash=&userenvironment($udom,$uname,
                   11521: 					    $spacequalifierrest);
                   11522: 	    return $returnhash{$spacequalifierrest};
                   11523: 	}
1.28      www      11524:     } elsif ($realm eq 'system') {
1.48      www      11525: # ----------------------------------------------------------------- system.time
                   11526: 	if ($space eq 'time') {
                   11527: 	    return time;
                   11528:         }
1.696     albertel 11529:     } elsif ($realm eq 'server') {
                   11530: # ----------------------------------------------------------------- system.time
                   11531: 	if ($space eq 'name') {
                   11532: 	    return $ENV{'SERVER_NAME'};
                   11533:         }
1.28      www      11534:     }
1.48      www      11535:     return '';
1.61      www      11536: }
                   11537: 
1.927     albertel 11538: sub get_reply {
                   11539:     my ($reply_value) = @_;
1.940     raeburn  11540:     if (ref($reply_value) eq 'ARRAY') {
                   11541:         if (wantarray) {
                   11542: 	    return @$reply_value;
                   11543:         }
                   11544:         return $reply_value->[0];
                   11545:     } else {
                   11546:         return $reply_value;
1.927     albertel 11547:     }
                   11548: }
                   11549: 
1.691     raeburn  11550: sub check_group_parms {
                   11551:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   11552:     my @groupitems = ();
                   11553:     my $resultitem;
1.927     albertel 11554:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  11555:     foreach my $group (@{$groups}) {
                   11556:         foreach my $level (@levels) {
1.927     albertel 11557:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   11558:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  11559:         }
                   11560:     }
                   11561:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   11562:                             $env{'course.'.$courseid.'.domain'},
                   11563:                                      'course',@groupitems);
                   11564:     return $coursereply;
                   11565: }
                   11566: 
                   11567: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  11568:     my ($courseid,@groups) = @_;
                   11569:     @groups = sort(@groups);
1.691     raeburn  11570:     return @groups;
                   11571: }
                   11572: 
1.395     albertel 11573: sub packages_tab_default {
                   11574:     my ($uri,$varname)=@_;
                   11575:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 11576: 
                   11577:     my (@extension,@specifics,$do_default);
                   11578:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 11579: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 11580: 	if ($pack_type eq 'default') {
                   11581: 	    $do_default=1;
                   11582: 	} elsif ($pack_type eq 'extension') {
                   11583: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 11584: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 11585: 	    # only look at packages defaults for packages that this id is
1.738     albertel 11586: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   11587: 	}
                   11588:     }
                   11589:     # first look for a package that matches the requested part id
                   11590:     foreach my $package (@specifics) {
                   11591: 	my (undef,$pack_type,$pack_part)=@{$package};
                   11592: 	next if ($pack_part ne $part);
                   11593: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11594: 	    return $packagetab{"$pack_type&$name&default"};
                   11595: 	}
                   11596:     }
                   11597:     # look for any possible matching non extension_ package
                   11598:     foreach my $package (@specifics) {
                   11599: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 11600: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11601: 	    return $packagetab{"$pack_type&$name&default"};
                   11602: 	}
1.585     albertel 11603: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 11604: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   11605: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 11606: 	}
                   11607:     }
1.738     albertel 11608:     # look for any posible extension_ match
                   11609:     foreach my $package (@extension) {
                   11610: 	my ($package,$pack_type)=@{$package};
                   11611: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11612: 	    return $packagetab{"$pack_type&$name&default"};
                   11613: 	}
                   11614: 	if (defined($packagetab{$package."&$name&default"})) {
                   11615: 	    return $packagetab{$package."&$name&default"};
                   11616: 	}
                   11617:     }
                   11618:     # look for a global default setting
                   11619:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11620: 	return $packagetab{"default&$name&default"};
                   11621:     }
1.395     albertel 11622:     return undef;
                   11623: }
                   11624: 
1.334     albertel 11625: sub add_prefix_and_part {
                   11626:     my ($prefix,$part)=@_;
                   11627:     my $keyroot;
                   11628:     if (defined($prefix) && $prefix !~ /^__/) {
                   11629: 	# prefix that has a part already
                   11630: 	$keyroot=$prefix;
                   11631:     } elsif (defined($prefix)) {
                   11632: 	# prefix that is missing a part
                   11633: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11634:     } else {
                   11635: 	# no prefix at all
                   11636: 	if (defined($part)) { $keyroot='_'.$part; }
                   11637:     }
                   11638:     return $keyroot;
                   11639: }
                   11640: 
1.71      www      11641: # ---------------------------------------------------------------- Get metadata
                   11642: 
1.599     albertel 11643: my %metaentry;
1.1070    www      11644: my %importedpartids;
1.1172.2.99  raeburn  11645: my %importedrespids;
1.71      www      11646: sub metadata {
1.176     www      11647:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      11648:     $uri=&declutter($uri);
1.288     albertel 11649:     # if it is a non metadata possible uri return quickly
1.529     albertel 11650:     if (($uri eq '') || 
                   11651: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.20  raeburn  11652: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108    raeburn  11653:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11654: 	return undef;
                   11655:     }
1.1172.2.49  raeburn  11656:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11657: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11658: 	return undef;
1.288     albertel 11659:     }
1.73      www      11660:     my $filename=$uri;
                   11661:     $uri=~s/\.meta$//;
1.172     www      11662: #
                   11663: # Is the metadata already cached?
1.177     www      11664: # Look at timestamp of caching
1.172     www      11665: # Everything is cached by the main uri, libraries are never directly cached
                   11666: #
1.428     albertel 11667:     if (!defined($liburi)) {
1.599     albertel 11668: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11669: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11670:     }
                   11671:     {
1.1069    www      11672: # Imported parts would go here
1.1172.2.99  raeburn  11673:         my @origfiletagids=();
1.1069    www      11674:         my $importedparts=0;
1.1172.2.99  raeburn  11675: 
                   11676: # Imported responseids would go here
                   11677:         my $importedresponses=0;
1.172     www      11678: #
                   11679: # Is this a recursive call for a library?
                   11680: #
1.599     albertel 11681: #	if (! exists($metacache{$uri})) {
                   11682: #	    $metacache{$uri}={};
                   11683: #	}
1.924     albertel 11684: 	my $cachetime = 60*60;
1.171     www      11685:         if ($liburi) {
                   11686: 	    $liburi=&declutter($liburi);
                   11687:             $filename=$liburi;
1.401     bowersj2 11688:         } else {
1.599     albertel 11689: 	    &devalidate_cache_new('meta',$uri);
                   11690: 	    undef(%metaentry);
1.401     bowersj2 11691: 	}
1.140     www      11692:         my %metathesekeys=();
1.73      www      11693:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 11694: 	my $metastring;
1.1140    www      11695: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 11696: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 11697: 	    $metastring = 
1.929     albertel 11698: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 11699: 					  ('grade_target' => 'meta'));
                   11700: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  11701: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   11702:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 11703: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 11704: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 11705: 	    $metastring=&getfile($file);
1.489     albertel 11706: 	}
1.208     albertel 11707:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      11708:         my $token;
1.140     www      11709:         undef %metathesekeys;
1.71      www      11710:         while ($token=$parser->get_token) {
1.339     albertel 11711: 	    if ($token->[0] eq 'S') {
                   11712: 		if (defined($token->[2]->{'package'})) {
1.172     www      11713: #
                   11714: # This is a package - get package info
                   11715: #
1.339     albertel 11716: 		    my $package=$token->[2]->{'package'};
                   11717: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11718: 		    if (defined($token->[2]->{'id'})) { 
                   11719: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   11720: 		    }
1.599     albertel 11721: 		    if ($metaentry{':packages'}) {
                   11722: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 11723: 		    } else {
1.599     albertel 11724: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 11725: 		    }
1.736     albertel 11726: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 11727: 			my $part=$keyroot;
                   11728: 			$part=~s/^\_//;
1.736     albertel 11729: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   11730: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   11731: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 11732: 			    # ignore package.tab specified default values
                   11733:                             # here &package_tab_default() will fetch those
                   11734: 			    if ($subp eq 'default') { next; }
1.736     albertel 11735: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 11736: 			    my $unikey;
                   11737: 			    if ($pack =~ /_0$/) {
                   11738: 				$unikey='parameter_0_'.$name;
                   11739: 				$part=0;
                   11740: 			    } else {
                   11741: 				$unikey='parameter'.$keyroot.'_'.$name;
                   11742: 			    }
1.339     albertel 11743: 			    if ($subp eq 'display') {
                   11744: 				$value.=' [Part: '.$part.']';
                   11745: 			    }
1.599     albertel 11746: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 11747: 			    $metathesekeys{$unikey}=1;
1.599     albertel 11748: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11749: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 11750: 			    }
1.599     albertel 11751: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   11752: 				$metaentry{':'.$unikey}=
                   11753: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 11754: 			    }
1.339     albertel 11755: 			}
                   11756: 		    }
                   11757: 		} else {
1.172     www      11758: #
                   11759: # This is not a package - some other kind of start tag
1.339     albertel 11760: #
                   11761: 		    my $entry=$token->[1];
1.1068    www      11762: 		    my $unikey='';
1.175     www      11763: 
1.339     albertel 11764: 		    if ($entry eq 'import') {
1.175     www      11765: #
                   11766: # Importing a library here
1.339     albertel 11767: #
1.1067    www      11768:                         my $location=$parser->get_text('/import');
                   11769:                         my $dir=$filename;
                   11770:                         $dir=~s|[^/]*$||;
                   11771:                         $location=&filelocation($dir,$location);
1.1172.2.99  raeburn  11772: 
                   11773:                         my $importid=$token->[2]->{'id'};
1.1068    www      11774:                         my $importmode=$token->[2]->{'importmode'};
1.1172.2.99  raeburn  11775: #
                   11776: # Check metadata for imported file to
                   11777: # see if it contained response items
                   11778: #
                   11779:                         my %currmetaentry = %metaentry;
                   11780:                         my $libresponseorder = &metadata($location,'responseorder');
                   11781:                         my $origfile;
                   11782:                         if ($libresponseorder ne '') {
                   11783:                             if ($#origfiletagids<0) {
                   11784:                                 undef(%importedrespids);
                   11785:                                 undef(%importedpartids);
                   11786:                             }
                   11787:                             @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
                   11788:                             if (@{$importedrespids{$importid}} > 0) {
                   11789:                                 $importedresponses = 1;
                   11790: # We need to get the original file and the imported file to get the response order correct
                   11791: # Load and inspect original file
                   11792:                                 if ($#origfiletagids<0) {
                   11793:                                     my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11794:                                     $origfile=&getfile($origfilelocation);
                   11795:                                     @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11796:                                 }
                   11797:                             }
                   11798:                         }
                   11799: # Do not overwrite contents of %metaentry hash for resource itself with 
                   11800: # hash populated for imported library file
                   11801:                         %metaentry = %currmetaentry;
                   11802:                         undef(%currmetaentry);
1.1068    www      11803:                         if ($importmode eq 'problem') {
1.1069    www      11804: # Import as problem/response
1.1068    www      11805:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11806:                         } elsif ($importmode eq 'part') {
                   11807: # Import as part(s)
1.1069    www      11808:                            $importedparts=1;
                   11809: # We need to get the original file and the imported file to get the part order correct
                   11810: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.99  raeburn  11811: # Load and inspect original file if we didn't do that already
                   11812:                            if ($#origfiletagids<0) {
                   11813:                                undef(%importedrespids);
                   11814:                                undef(%importedpartids);
                   11815:                                if ($origfile eq '') {
                   11816:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11817:                                    $origfile=&getfile($origfilelocation);
                   11818:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11819:                                }
1.1070    www      11820:                            }
                   11821: 
1.1069    www      11822: # Load and inspect imported file
                   11823:                            my $impfile=&getfile($location);
                   11824:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11825:                            if ($#impfilepartids>=0) {
                   11826: # This problem had parts
1.1070    www      11827:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      11828:                            } else {
                   11829: # Importing by turning a single problem into a problem part
                   11830: # It gets the import-tags ID as part-ID
                   11831:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      11832:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      11833:                            }
1.1068    www      11834:                         } else {
                   11835: # Normal import
                   11836:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11837:                            if (defined($token->[2]->{'id'})) {
                   11838:                               $unikey.='_'.$token->[2]->{'id'};
                   11839:                            }
1.1067    www      11840:                         }
                   11841: 
1.339     albertel 11842: 			if ($depthcount<20) {
1.736     albertel 11843: 			    my $metadata = 
                   11844: 				&metadata($uri,'keys', $location,$unikey,
                   11845: 					  $depthcount+1);
                   11846: 			    foreach my $meta (split(',',$metadata)) {
                   11847: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   11848: 				$metathesekeys{$meta}=1;
1.339     albertel 11849: 			    }
1.1068    www      11850: 			
                   11851:                         }
1.1067    www      11852: 		    } else {
                   11853: #
                   11854: # Not importing, some other kind of non-package, non-library start tag
                   11855: # 
                   11856:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11857:                         if (defined($token->[2]->{'id'})) {
                   11858:                             $unikey.='_'.$token->[2]->{'id'};
                   11859:                         }
1.339     albertel 11860: 			if (defined($token->[2]->{'name'})) { 
                   11861: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   11862: 			}
                   11863: 			$metathesekeys{$unikey}=1;
1.736     albertel 11864: 			foreach my $param (@{$token->[3]}) {
                   11865: 			    $metaentry{':'.$unikey.'.'.$param} =
                   11866: 				$token->[2]->{$param};
1.339     albertel 11867: 			}
                   11868: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 11869: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 11870: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   11871: 		 # only ws inside the tag, and not in default, so use default
                   11872: 		 # as value
1.599     albertel 11873: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 11874: 			} elsif ( $internaltext =~ /\S/ ) {
                   11875: 		  # something interesting inside the tag
                   11876: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 11877: 			} else {
1.908     albertel 11878: 		  # no interesting values, don't set a default
1.339     albertel 11879: 			}
1.172     www      11880: # end of not-a-package not-a-library import
1.339     albertel 11881: 		    }
1.172     www      11882: # end of not-a-package start tag
1.339     albertel 11883: 		}
1.172     www      11884: # the next is the end of "start tag"
1.339     albertel 11885: 	    }
                   11886: 	}
1.483     albertel 11887: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 11888: 	$extension = lc($extension);
                   11889: 	if ($extension eq 'htm') { $extension='html'; }
                   11890: 
1.737     albertel 11891: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 11892: 	    #no specific packages #how's our extension
                   11893: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 11894: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 11895: 					 \%metathesekeys);
                   11896: 	}
1.883     albertel 11897: 
                   11898: 	if (!exists($metaentry{':packages'})
                   11899: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 11900: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 11901: 		#no specific packages well let's get default then
                   11902: 		if ($key!~/^default&/) { next; }
1.488     albertel 11903: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 11904: 					     \%metathesekeys);
                   11905: 	    }
                   11906: 	}
1.338     www      11907: # are there custom rights to evaluate
1.599     albertel 11908: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 11909: 
1.338     www      11910:     #
                   11911:     # Importing a rights file here
1.339     albertel 11912:     #
                   11913: 	    unless ($depthcount) {
1.599     albertel 11914: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 11915: 		my $dir=$filename;
                   11916: 		$dir=~s|[^/]*$||;
                   11917: 		$location=&filelocation($dir,$location);
1.736     albertel 11918: 		my $rights_metadata =
                   11919: 		    &metadata($uri,'keys',$location,'_rights',
                   11920: 			      $depthcount+1);
                   11921: 		foreach my $rights (split(',',$rights_metadata)) {
                   11922: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   11923: 		    $metathesekeys{$rights}=1;
1.339     albertel 11924: 		}
                   11925: 	    }
                   11926: 	}
1.737     albertel 11927: 	# uniqifiy package listing
                   11928: 	my %seen;
                   11929: 	my @uniq_packages =
                   11930: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   11931: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   11932: 
1.1172.2.99  raeburn  11933:         if (($importedresponses) || ($importedparts)) {
                   11934:             if ($importedparts) {
1.1070    www      11935: # We had imported parts and need to rebuild partorder
1.1172.2.99  raeburn  11936:                 $metaentry{':partorder'}='';
                   11937:                 $metathesekeys{'partorder'}=1;
                   11938:             }
                   11939:             if ($importedresponses) {
                   11940: # We had imported responses and need to rebuild responseorder
                   11941:                 $metaentry{':responseorder'}='';
                   11942:                 $metathesekeys{'responseorder'}=1;
                   11943:             }
                   11944:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   11945:                 my $origid = $origfiletagids[$index+1];
                   11946:                 if ($origfiletagids[$index] eq 'part') {
                   11947: # Original part, part of the problem
                   11948:                     if ($importedparts) {
                   11949:                         $metaentry{':partorder'}.=','.$origid;
                   11950:                     }
                   11951:                 } elsif ($origfiletagids[$index] eq 'import') {
                   11952:                     if ($importedparts) {
                   11953: # We have imported parts at this position
                   11954:                         $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   11955:                     }
                   11956:                     if ($importedresponses) {
                   11957: # We have imported responses at this position
                   11958:                         if (ref($importedrespids{$origid}) eq 'ARRAY') {
                   11959:                             $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
                   11960:                         }
                   11961:                     }
                   11962:                 } else {
                   11963: # Original response item, part of the problem
                   11964:                     if ($importedresponses) {
                   11965:                         $metaentry{':responseorder'}.=','.$origid;
                   11966:                     }
                   11967:                 }
                   11968:             }
                   11969:             if ($importedparts) {
                   11970:                 $metaentry{':partorder'}=~s/^\,//;
                   11971:             }
                   11972:             if ($importedresponses) {
                   11973:                 $metaentry{':responseorder'}=~s/^\,//;
                   11974:             }
1.1070    www      11975:         }
                   11976: 
1.737     albertel 11977: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 11978: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58  raeburn  11979: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 11980: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      11981: # this is the end of "was not already recently cached
1.71      www      11982:     }
1.599     albertel 11983:     return $metaentry{':'.$what};
1.261     albertel 11984: }
                   11985: 
1.488     albertel 11986: sub metadata_create_package_def {
1.483     albertel 11987:     my ($uri,$key,$package,$metathesekeys)=@_;
                   11988:     my ($pack,$name,$subp)=split(/\&/,$key);
                   11989:     if ($subp eq 'default') { next; }
                   11990:     
1.599     albertel 11991:     if (defined($metaentry{':packages'})) {
                   11992: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 11993:     } else {
1.599     albertel 11994: 	$metaentry{':packages'}=$package;
1.483     albertel 11995:     }
                   11996:     my $value=$packagetab{$key};
                   11997:     my $unikey;
                   11998:     $unikey='parameter_0_'.$name;
1.599     albertel 11999:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 12000:     $$metathesekeys{$unikey}=1;
1.599     albertel 12001:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12002: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 12003:     }
1.599     albertel 12004:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   12005: 	$metaentry{':'.$unikey}=
                   12006: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 12007:     }
                   12008: }
                   12009: 
1.261     albertel 12010: sub metadata_generate_part0 {
                   12011:     my ($metadata,$metacache,$uri) = @_;
                   12012:     my %allnames;
1.737     albertel 12013:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 12014: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 12015: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   12016: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 12017: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 12018: 	    $allnames{$name}=$part;
                   12019: 	  }
                   12020: 	}
                   12021:     }
                   12022:     foreach my $name (keys(%allnames)) {
                   12023:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 12024:       my $key=":parameter_0_$name";
1.261     albertel 12025:       $$metacache{"$key.part"}='0';
                   12026:       $$metacache{"$key.name"}=$name;
1.428     albertel 12027:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 12028: 					   $allnames{$name}.'_'.$name.
                   12029: 					   '.type'};
1.428     albertel 12030:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 12031: 			     '.display'};
1.644     www      12032:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 12033:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 12034:       $$metacache{"$key.display"}=$olddis;
                   12035:     }
1.71      www      12036: }
                   12037: 
1.764     albertel 12038: # ------------------------------------------------------ Devalidate title cache
                   12039: 
                   12040: sub devalidate_title_cache {
                   12041:     my ($url)=@_;
                   12042:     if (!$env{'request.course.id'}) { return; }
                   12043:     my $symb=&symbread($url);
                   12044:     if (!$symb) { return; }
                   12045:     my $key=$env{'request.course.id'}."\0".$symb;
                   12046:     &devalidate_cache_new('title',$key);
                   12047: }
                   12048: 
1.1014    droeschl 12049: # ------------------------------------------------- Get the title of a course
                   12050: 
                   12051: sub current_course_title {
                   12052:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   12053: }
1.301     www      12054: # ------------------------------------------------- Get the title of a resource
                   12055: 
                   12056: sub gettitle {
                   12057:     my $urlsymb=shift;
                   12058:     my $symb=&symbread($urlsymb);
1.534     albertel 12059:     if ($symb) {
1.620     albertel 12060: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 12061: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 12062: 	if (defined($cached)) { 
                   12063: 	    return $result;
                   12064: 	}
1.534     albertel 12065: 	my ($map,$resid,$url)=&decode_symb($symb);
                   12066: 	my $title='';
1.907     albertel 12067: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   12068: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   12069: 	} else {
                   12070: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   12071: 		    &GDBM_READER(),0640)) {
                   12072: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   12073: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   12074: 		untie(%bighash);
                   12075: 	    }
1.534     albertel 12076: 	}
                   12077: 	$title=~s/\&colon\;/\:/gs;
                   12078: 	if ($title) {
1.1159    www      12079: # Remember both $symb and $title for dynamic metadata
                   12080:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      12081:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      12082: # Cache this title and then return it
1.599     albertel 12083: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 12084: 	}
                   12085: 	$urlsymb=$url;
                   12086:     }
                   12087:     my $title=&metadata($urlsymb,'title');
                   12088:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   12089:     return $title;
1.301     www      12090: }
1.613     albertel 12091: 
1.614     albertel 12092: sub get_slot {
                   12093:     my ($which,$cnum,$cdom)=@_;
                   12094:     if (!$cnum || !$cdom) {
1.790     albertel 12095: 	(undef,my $courseid)=&whichuser();
1.620     albertel 12096: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   12097: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 12098:     }
1.703     albertel 12099:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   12100:     my %slotinfo;
                   12101:     if (exists($remembered{$key})) {
                   12102: 	$slotinfo{$which} = $remembered{$key};
                   12103:     } else {
                   12104: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   12105: 	&Apache::lonhomework::showhash(%slotinfo);
                   12106: 	my ($tmp)=keys(%slotinfo);
                   12107: 	if ($tmp=~/^error:/) { return (); }
                   12108: 	$remembered{$key} = $slotinfo{$which};
                   12109:     }
1.616     albertel 12110:     if (ref($slotinfo{$which}) eq 'HASH') {
                   12111: 	return %{$slotinfo{$which}};
                   12112:     }
                   12113:     return $slotinfo{$which};
1.614     albertel 12114: }
1.1150    raeburn  12115: 
                   12116: sub get_reservable_slots {
                   12117:     my ($cnum,$cdom,$uname,$udom) = @_;
                   12118:     my $now = time;
                   12119:     my $reservable_info;
                   12120:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   12121:     if (exists($remembered{$key})) {
                   12122:         $reservable_info = $remembered{$key};
                   12123:     } else {
                   12124:         my %resv;
                   12125:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   12126:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   12127:         $reservable_info = \%resv;
                   12128:         $remembered{$key} = $reservable_info;
                   12129:     }
                   12130:     return $reservable_info;
                   12131: }
                   12132: 
                   12133: sub get_course_slots {
                   12134:     my ($cnum,$cdom) = @_;
                   12135:     my $hashid=$cnum.':'.$cdom;
                   12136:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   12137:     if (defined($cached)) {
                   12138:         if (ref($result) eq 'HASH') {
                   12139:             return %{$result};
                   12140:         }
                   12141:     } else {
                   12142:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   12143:         my ($tmp) = keys(%slots);
                   12144:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  12145:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  12146:             return %slots;
                   12147:         }
                   12148:     }
                   12149:     return;
                   12150: }
                   12151: 
                   12152: sub devalidate_slots_cache {
                   12153:     my ($cnum,$cdom)=@_;
                   12154:     my $hashid=$cnum.':'.$cdom;
                   12155:     &devalidate_cache_new('allslots',$hashid);
                   12156: }
                   12157: 
1.1172.2.8  raeburn  12158: sub get_coursechange {
                   12159:     my ($cdom,$cnum) = @_;
                   12160:     if ($cdom eq '' || $cnum eq '') {
                   12161:         return unless ($env{'request.course.id'});
                   12162:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   12163:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12164:     }
                   12165:     my $hashid=$cdom.'_'.$cnum;
                   12166:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   12167:     if ((defined($cached)) && ($change ne '')) {
                   12168:         return $change;
                   12169:     } else {
                   12170:         my %crshash;
                   12171:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   12172:         if ($crshash{'internal.contentchange'} eq '') {
                   12173:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   12174:             if ($change eq '') {
                   12175:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   12176:                 $change = $crshash{'internal.created'};
                   12177:             }
                   12178:         } else {
                   12179:             $change = $crshash{'internal.contentchange'};
                   12180:         }
                   12181:         my $cachetime = 600;
                   12182:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   12183:     }
                   12184:     return $change;
                   12185: }
                   12186: 
                   12187: sub devalidate_coursechange_cache {
                   12188:     my ($cnum,$cdom)=@_;
                   12189:     my $hashid=$cnum.':'.$cdom;
                   12190:     &devalidate_cache_new('crschange',$hashid);
                   12191: }
                   12192: 
1.31      www      12193: # ------------------------------------------------- Update symbolic store links
                   12194: 
                   12195: sub symblist {
                   12196:     my ($mapname,%newhash)=@_;
1.438     www      12197:     $mapname=&deversion(&declutter($mapname));
1.31      www      12198:     my %hash;
1.620     albertel 12199:     if (($env{'request.course.fn'}) && (%newhash)) {
                   12200:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12201:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  12202: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 12203: 		next if ($url eq 'last_known'
                   12204: 			 && $env{'form.no_update_last_known'});
                   12205: 		$hash{declutter($url)}=&encode_symb($mapname,
                   12206: 						    $newhash{$url}->[1],
                   12207: 						    $newhash{$url}->[0]);
1.191     harris41 12208:             }
1.31      www      12209:             if (untie(%hash)) {
                   12210: 		return 'ok';
                   12211:             }
                   12212:         }
                   12213:     }
                   12214:     return 'error';
1.212     www      12215: }
                   12216: 
                   12217: # --------------------------------------------------------------- Verify a symb
                   12218: 
                   12219: sub symbverify {
1.1172.2.11  raeburn  12220:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      12221:     my $thisfn=$thisurl;
1.439     www      12222:     $thisfn=&declutter($thisfn);
1.215     www      12223: # direct jump to resource in page or to a sequence - will construct own symbs
                   12224:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   12225: # check URL part
1.409     www      12226:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      12227: 
1.431     www      12228:     unless ($url eq $thisfn) { return 0; }
1.213     www      12229: 
1.216     www      12230:     $symb=&symbclean($symb);
1.510     www      12231:     $thisurl=&deversion($thisurl);
1.439     www      12232:     $thisfn=&deversion($thisfn);
1.213     www      12233: 
                   12234:     my %bighash;
                   12235:     my $okay=0;
1.431     www      12236: 
1.620     albertel 12237:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12238:                             &GDBM_READER(),0640)) {
1.1172.2.13  raeburn  12239:         my $noclutter;
1.1032    raeburn  12240:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   12241:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  12242:             if ($map =~ m{^uploaded/.+\.page$}) {
                   12243:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   12244:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   12245:                 $noclutter = 1;
                   12246:             }
                   12247:         }
                   12248:         my $ids;
                   12249:         if ($noclutter) {
                   12250:             $ids=$bighash{'ids_'.$thisurl};
                   12251:         } else {
                   12252:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  12253:         }
1.1102    raeburn  12254:         unless ($ids) {
1.1172.2.13  raeburn  12255:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  12256:             $ids=$bighash{$idkey};
1.216     www      12257:         }
                   12258:         if ($ids) {
                   12259: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  12260:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   12261:                 $symb =~ s/\?.+$//;
                   12262:             }
1.800     albertel 12263: 	    foreach my $id (split(/\,/,$ids)) {
                   12264: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      12265:                if (
                   12266:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  12267:    eq $symb) {
1.1172.2.11  raeburn  12268:                    if (ref($encstate)) {
                   12269:                        $$encstate = $bighash{'encrypted_'.$id};
                   12270:                    }
1.1172.2.13  raeburn  12271:                    if (($env{'request.role.adv'}) ||
                   12272:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  12273:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  12274:                        $okay=1;
                   12275:                        last;
                   12276:                    }
                   12277:                }
                   12278:            }
1.216     www      12279:         }
1.213     www      12280: 	untie(%bighash);
                   12281:     }
                   12282:     return $okay;
1.31      www      12283: }
                   12284: 
1.210     www      12285: # --------------------------------------------------------------- Clean-up symb
                   12286: 
                   12287: sub symbclean {
                   12288:     my $symb=shift;
1.568     albertel 12289:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      12290: # remove version from map
                   12291:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      12292: 
1.210     www      12293: # remove version from URL
                   12294:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      12295: 
1.507     www      12296: # remove wrapper
                   12297: 
1.510     www      12298:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 12299:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      12300:     return $symb;
1.409     www      12301: }
                   12302: 
                   12303: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 12304: 
                   12305: sub encode_symb {
                   12306:     my ($map,$resid,$url)=@_;
                   12307:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   12308: }
1.409     www      12309: 
                   12310: sub decode_symb {
1.568     albertel 12311:     my $symb=shift;
                   12312:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   12313:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      12314:     return (&fixversion($map),$resid,&fixversion($url));
                   12315: }
                   12316: 
                   12317: sub fixversion {
                   12318:     my $fn=shift;
1.609     banghart 12319:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      12320:     my %bighash;
                   12321:     my $uri=&clutter($fn);
1.620     albertel 12322:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      12323: # is this cached?
1.599     albertel 12324:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      12325:     if (defined($cached)) { return $result; }
                   12326: # unfortunately not cached, or expired
1.620     albertel 12327:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      12328: 	    &GDBM_READER(),0640)) {
                   12329:  	if ($bighash{'version_'.$uri}) {
                   12330:  	    my $version=$bighash{'version_'.$uri};
1.444     www      12331:  	    unless (($version eq 'mostrecent') || 
                   12332: 		    ($version==&getversion($uri))) {
1.440     www      12333:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   12334:  	    }
                   12335:  	}
                   12336:  	untie %bighash;
1.413     www      12337:     }
1.599     albertel 12338:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      12339: }
                   12340: 
                   12341: sub deversion {
                   12342:     my $url=shift;
                   12343:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   12344:     return $url;
1.210     www      12345: }
                   12346: 
1.31      www      12347: # ------------------------------------------------------ Return symb list entry
                   12348: 
                   12349: sub symbread {
1.1172.2.66  raeburn  12350:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1172.2.54  raeburn  12351:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.66  raeburn  12352:     if (defined($env{$cache_str})) {
                   12353:         if ($ignorecachednull) {
                   12354:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   12355:         } else {
                   12356:             return $env{$cache_str};
                   12357:         }
                   12358:     }
1.242     www      12359: # no filename provided? try from environment
1.1172.2.54  raeburn  12360:     unless ($thisfn) {
1.620     albertel 12361:         if ($env{'request.symb'}) {
1.1172.2.13  raeburn  12362:             return $env{$cache_str}=&symbclean($env{'request.symb'});
                   12363:         }
                   12364:         $thisfn=$env{'request.filename'};
1.44      www      12365:     }
1.569     albertel 12366:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      12367: # is that filename actually a symb? Verify, clean, and return
                   12368:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 12369: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 12370: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 12371: 	}
1.242     www      12372:     }
1.44      www      12373:     $thisfn=declutter($thisfn);
1.31      www      12374:     my %hash;
1.37      www      12375:     my %bighash;
                   12376:     my $syval='';
1.620     albertel 12377:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  12378:         my $targetfn = $thisfn;
1.609     banghart 12379:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  12380:             $targetfn = 'adm/wrapper/'.$thisfn;
                   12381:         }
1.687     albertel 12382: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   12383: 	    $targetfn=$1;
                   12384: 	}
1.620     albertel 12385:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12386:                       &GDBM_READER(),0640)) {
1.481     raeburn  12387: 	    $syval=$hash{$targetfn};
1.37      www      12388:             untie(%hash);
                   12389:         }
                   12390: # ---------------------------------------------------------- There was an entry
                   12391:         if ($syval) {
1.601     albertel 12392: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 12393: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  12394: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12395: 		    #return $env{$cache_str}='';
1.601     albertel 12396: 		#}    
                   12397: 		#$syval.=$1;
                   12398: 	    #}
1.37      www      12399:         } else {
                   12400: # ------------------------------------------------------- Was not in symb table
1.620     albertel 12401:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12402:                             &GDBM_READER(),0640)) {
1.37      www      12403: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      12404:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      12405:               unless ($ids) { 
                   12406:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      12407:               }
                   12408:               unless ($ids) {
                   12409: # alias?
                   12410: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      12411:               }
1.37      www      12412:               if ($ids) {
                   12413: # ------------------------------------------------------------------- Has ID(s)
                   12414:                  my @possibilities=split(/\,/,$ids);
1.39      www      12415:                  if ($#possibilities==0) {
                   12416: # ----------------------------------------------- There is only one possibility
1.37      www      12417: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 12418: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12419: 						    $resid,$thisfn);
1.1172.2.66  raeburn  12420:                      if (ref($possibles) eq 'HASH') {
                   12421:                          $possibles->{$syval} = 1;
                   12422:                      }
                   12423:                      if ($checkforblock) {
                   12424:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   12425:                          if (@blockers) {
                   12426:                              $syval = '';
                   12427:                              return;
                   12428:                          }
                   12429:                      }
                   12430:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39      www      12431: # ------------------------------------------ There is more than one possibility
                   12432:                      my $realpossible=0;
1.800     albertel 12433:                      foreach my $id (@possibilities) {
                   12434: 			 my $file=$bighash{'src_'.$id};
1.1172.2.66  raeburn  12435:                          my $canaccess;
                   12436:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   12437:                              $canaccess = 1;
                   12438:                          } else {
                   12439:                              $canaccess = &allowed('bre',$file);
                   12440:                          }
                   12441:                          if ($canaccess) {
                   12442:          		     my ($mapid,$resid)=split(/\./,$id);
                   12443:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   12444:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12445:                                                              $resid,$thisfn);
                   12446:                                  if (ref($possibles) eq 'HASH') {
                   12447:                                      $possibles->{$syval} = 1;
                   12448:                                  }
                   12449:                                  if ($checkforblock) {
                   12450:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   12451:                                      unless (@blockers > 0) {
                   12452:                                          $syval = $poss_syval;
                   12453:                                          $realpossible++;
                   12454:                                      }
                   12455:                                  } else {
                   12456:                                      $syval = $poss_syval;
                   12457:                                      $realpossible++;
                   12458:                                  }
                   12459:                              }
1.39      www      12460: 			 }
1.191     harris41 12461:                      }
1.39      www      12462: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      12463:                  } else {
                   12464:                      $syval='';
1.37      www      12465:                  }
                   12466: 	      }
1.1172.2.66  raeburn  12467:               untie(%bighash);
1.481     raeburn  12468:            }
1.31      www      12469:         }
1.62      www      12470:         if ($syval) {
1.620     albertel 12471: 	    return $env{$cache_str}=$syval;
1.62      www      12472:         }
1.31      www      12473:     }
1.949     raeburn  12474:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12475:     return $env{$cache_str}='';
1.31      www      12476: }
                   12477: 
                   12478: # ---------------------------------------------------------- Return random seed
                   12479: 
1.32      www      12480: sub numval {
                   12481:     my $txt=shift;
                   12482:     $txt=~tr/A-J/0-9/;
                   12483:     $txt=~tr/a-j/0-9/;
                   12484:     $txt=~tr/K-T/0-9/;
                   12485:     $txt=~tr/k-t/0-9/;
                   12486:     $txt=~tr/U-Z/0-5/;
                   12487:     $txt=~tr/u-z/0-5/;
                   12488:     $txt=~s/\D//g;
1.564     albertel 12489:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      12490:     return int($txt);
1.368     albertel 12491: }
                   12492: 
1.484     albertel 12493: sub numval2 {
                   12494:     my $txt=shift;
                   12495:     $txt=~tr/A-J/0-9/;
                   12496:     $txt=~tr/a-j/0-9/;
                   12497:     $txt=~tr/K-T/0-9/;
                   12498:     $txt=~tr/k-t/0-9/;
                   12499:     $txt=~tr/U-Z/0-5/;
                   12500:     $txt=~tr/u-z/0-5/;
                   12501:     $txt=~s/\D//g;
                   12502:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12503:     my $total;
                   12504:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 12505:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 12506:     return int($total);
                   12507: }
                   12508: 
1.575     albertel 12509: sub numval3 {
                   12510:     use integer;
                   12511:     my $txt=shift;
                   12512:     $txt=~tr/A-J/0-9/;
                   12513:     $txt=~tr/a-j/0-9/;
                   12514:     $txt=~tr/K-T/0-9/;
                   12515:     $txt=~tr/k-t/0-9/;
                   12516:     $txt=~tr/U-Z/0-5/;
                   12517:     $txt=~tr/u-z/0-5/;
                   12518:     $txt=~s/\D//g;
                   12519:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12520:     my $total;
                   12521:     foreach my $val (@txts) { $total+=$val; }
                   12522:     if ($_64bit) { $total=(($total<<32)>>32); }
                   12523:     return $total;
                   12524: }
                   12525: 
1.675     albertel 12526: sub digest {
                   12527:     my ($data)=@_;
                   12528:     my $digest=&Digest::MD5::md5($data);
                   12529:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   12530:     my ($e,$f);
                   12531:     {
                   12532:         use integer;
                   12533:         $e=($a+$b);
                   12534:         $f=($c+$d);
                   12535:         if ($_64bit) {
                   12536:             $e=(($e<<32)>>32);
                   12537:             $f=(($f<<32)>>32);
                   12538:         }
                   12539:     }
                   12540:     if (wantarray) {
                   12541: 	return ($e,$f);
                   12542:     } else {
                   12543: 	my $g;
                   12544: 	{
                   12545: 	    use integer;
                   12546: 	    $g=($e+$f);
                   12547: 	    if ($_64bit) {
                   12548: 		$g=(($g<<32)>>32);
                   12549: 	    }
                   12550: 	}
                   12551: 	return $g;
                   12552:     }
                   12553: }
                   12554: 
1.368     albertel 12555: sub latest_rnd_algorithm_id {
1.675     albertel 12556:     return '64bit5';
1.366     albertel 12557: }
1.32      www      12558: 
1.503     albertel 12559: sub get_rand_alg {
                   12560:     my ($courseid)=@_;
1.790     albertel 12561:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 12562:     if ($courseid) {
1.620     albertel 12563: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 12564:     }
                   12565:     return &latest_rnd_algorithm_id();
                   12566: }
                   12567: 
1.562     albertel 12568: sub validCODE {
                   12569:     my ($CODE)=@_;
                   12570:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   12571:     return 0;
                   12572: }
                   12573: 
1.491     albertel 12574: sub getCODE {
1.620     albertel 12575:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 12576:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   12577: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   12578: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 12579: 	return $Apache::lonhomework::history{'resource.CODE'};
                   12580:     }
                   12581:     return undef;
                   12582: }
1.1133    foxr     12583: #
                   12584: #  Determines the random seed for a specific context:
                   12585: #
                   12586: # parameters:
                   12587: #   symb      - in course context the symb for the seed.
                   12588: #   course_id - The course id of the form domain_coursenum.
                   12589: #   domain    - Domain for the user.
                   12590: #   course    - Course for the user.
                   12591: #   cenv      - environment of the course.
                   12592: #
                   12593: # NOTE:
                   12594: #   All parameters are picked out of the environment if missing
                   12595: #   or not defined.
                   12596: #   If a symb cannot be determined the current time is used instead.
                   12597: #
                   12598: #  For a given well defined symb, courside, domain, username,
                   12599: #  and course environment, the seed is reproducible.
                   12600: #
1.31      www      12601: sub rndseed {
1.1133    foxr     12602:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 12603:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 12604:     if (!defined($symb)) {
1.366     albertel 12605: 	unless ($symb=$wsymb) { return time; }
                   12606:     }
1.1146    foxr     12607:     if (!defined $courseid) { 
                   12608: 	$courseid=$wcourseid; 
                   12609:     }
                   12610:     if (!defined $domain) { $domain=$wdomain; }
                   12611:     if (!defined $username) { $username=$wusername }
1.1133    foxr     12612: 
                   12613:     my $which;
                   12614:     if (defined($cenv->{'rndseed'})) {
                   12615: 	$which = $cenv->{'rndseed'};
                   12616:     } else {
                   12617: 	$which =&get_rand_alg($courseid);
                   12618:     }
1.491     albertel 12619:     if (defined(&getCODE())) {
1.675     albertel 12620: 	if ($which eq '64bit5') {
                   12621: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   12622: 	} elsif ($which eq '64bit4') {
1.575     albertel 12623: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   12624: 	} else {
                   12625: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   12626: 	}
1.675     albertel 12627:     } elsif ($which eq '64bit5') {
                   12628: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 12629:     } elsif ($which eq '64bit4') {
                   12630: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 12631:     } elsif ($which eq '64bit3') {
                   12632: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 12633:     } elsif ($which eq '64bit2') {
                   12634: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 12635:     } elsif ($which eq '64bit') {
                   12636: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   12637:     }
                   12638:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   12639: }
                   12640: 
                   12641: sub rndseed_32bit {
                   12642:     my ($symb,$courseid,$domain,$username)=@_;
                   12643:     {
                   12644: 	use integer;
                   12645: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   12646: 	my $symbseed=numval($symb) << 22;
                   12647: 	my $namechck=unpack("%32C*",$username) << 17;
                   12648: 	my $nameseed=numval($username) << 12;
                   12649: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   12650: 	my $courseseed=unpack("%32C*",$courseid);
                   12651: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 12652: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12653: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12654: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 12655: 	return $num;
                   12656:     }
                   12657: }
                   12658: 
                   12659: sub rndseed_64bit {
                   12660:     my ($symb,$courseid,$domain,$username)=@_;
                   12661:     {
                   12662: 	use integer;
                   12663: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   12664: 	my $symbseed=numval($symb) << 10;
                   12665: 	my $namechck=unpack("%32S*",$username);
                   12666: 	
                   12667: 	my $nameseed=numval($username) << 21;
                   12668: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   12669: 	my $courseseed=unpack("%32S*",$courseid);
                   12670: 	
                   12671: 	my $num1=$symbchck+$symbseed+$namechck;
                   12672: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12673: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12674: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12675: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 12676: 	return "$num1,$num2";
1.155     albertel 12677:     }
1.366     albertel 12678: }
                   12679: 
1.443     albertel 12680: sub rndseed_64bit2 {
                   12681:     my ($symb,$courseid,$domain,$username)=@_;
                   12682:     {
                   12683: 	use integer;
                   12684: 	# strings need to be an even # of cahracters long, it it is odd the
                   12685:         # last characters gets thrown away
                   12686: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12687: 	my $symbseed=numval($symb) << 10;
                   12688: 	my $namechck=unpack("%32S*",$username.' ');
                   12689: 	
                   12690: 	my $nameseed=numval($username) << 21;
1.501     albertel 12691: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12692: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12693: 	
                   12694: 	my $num1=$symbchck+$symbseed+$namechck;
                   12695: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12696: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12697: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 12698: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 12699: 	return "$num1,$num2";
                   12700:     }
                   12701: }
                   12702: 
                   12703: sub rndseed_64bit3 {
                   12704:     my ($symb,$courseid,$domain,$username)=@_;
                   12705:     {
                   12706: 	use integer;
                   12707: 	# strings need to be an even # of cahracters long, it it is odd the
                   12708:         # last characters gets thrown away
                   12709: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12710: 	my $symbseed=numval2($symb) << 10;
                   12711: 	my $namechck=unpack("%32S*",$username.' ');
                   12712: 	
                   12713: 	my $nameseed=numval2($username) << 21;
1.443     albertel 12714: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12715: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12716: 	
                   12717: 	my $num1=$symbchck+$symbseed+$namechck;
                   12718: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12719: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12720: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 12721: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12722: 	
1.503     albertel 12723: 	return "$num1:$num2";
1.443     albertel 12724:     }
                   12725: }
                   12726: 
1.575     albertel 12727: sub rndseed_64bit4 {
                   12728:     my ($symb,$courseid,$domain,$username)=@_;
                   12729:     {
                   12730: 	use integer;
                   12731: 	# strings need to be an even # of cahracters long, it it is odd the
                   12732:         # last characters gets thrown away
                   12733: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12734: 	my $symbseed=numval3($symb) << 10;
                   12735: 	my $namechck=unpack("%32S*",$username.' ');
                   12736: 	
                   12737: 	my $nameseed=numval3($username) << 21;
                   12738: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12739: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12740: 	
                   12741: 	my $num1=$symbchck+$symbseed+$namechck;
                   12742: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12743: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12744: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 12745: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12746: 	
1.575     albertel 12747: 	return "$num1:$num2";
                   12748:     }
                   12749: }
                   12750: 
1.675     albertel 12751: sub rndseed_64bit5 {
                   12752:     my ($symb,$courseid,$domain,$username)=@_;
                   12753:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   12754:     return "$num1:$num2";
                   12755: }
                   12756: 
1.366     albertel 12757: sub rndseed_CODE_64bit {
                   12758:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 12759:     {
1.366     albertel 12760: 	use integer;
1.443     albertel 12761: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 12762: 	my $symbseed=numval2($symb);
1.491     albertel 12763: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12764: 	my $CODEseed=numval(&getCODE());
1.443     albertel 12765: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 12766: 	my $num1=$symbseed+$CODEchck;
                   12767: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12768: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12769: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 12770: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12771: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 12772: 	return "$num1:$num2";
1.366     albertel 12773:     }
                   12774: }
                   12775: 
1.575     albertel 12776: sub rndseed_CODE_64bit4 {
                   12777:     my ($symb,$courseid,$domain,$username)=@_;
                   12778:     {
                   12779: 	use integer;
                   12780: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   12781: 	my $symbseed=numval3($symb);
                   12782: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12783: 	my $CODEseed=numval3(&getCODE());
                   12784: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12785: 	my $num1=$symbseed+$CODEchck;
                   12786: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12787: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12788: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 12789: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12790: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   12791: 	return "$num1:$num2";
                   12792:     }
                   12793: }
                   12794: 
1.675     albertel 12795: sub rndseed_CODE_64bit5 {
                   12796:     my ($symb,$courseid,$domain,$username)=@_;
                   12797:     my $code = &getCODE();
                   12798:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   12799:     return "$num1:$num2";
                   12800: }
                   12801: 
1.366     albertel 12802: sub setup_random_from_rndseed {
                   12803:     my ($rndseed)=@_;
1.503     albertel 12804:     if ($rndseed =~/([,:])/) {
1.1172.2.51  raeburn  12805: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   12806:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   12807:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   12808:         } else {
                   12809:             &Math::Random::random_set_seed($num1,$num2);
                   12810:         }
1.366     albertel 12811:     } else {
                   12812: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 12813:     }
1.36      albertel 12814: }
                   12815: 
1.474     albertel 12816: sub latest_receipt_algorithm_id {
1.835     albertel 12817:     return 'receipt3';
1.474     albertel 12818: }
                   12819: 
1.480     www      12820: sub recunique {
                   12821:     my $fucourseid=shift;
                   12822:     my $unique;
1.835     albertel 12823:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   12824: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12825: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      12826:     } else {
                   12827: 	$unique=$perlvar{'lonReceipt'};
                   12828:     }
                   12829:     return unpack("%32C*",$unique);
                   12830: }
                   12831: 
                   12832: sub recprefix {
                   12833:     my $fucourseid=shift;
                   12834:     my $prefix;
1.835     albertel 12835:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   12836: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12837: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      12838:     } else {
                   12839: 	$prefix=$perlvar{'lonHostID'};
                   12840:     }
                   12841:     return unpack("%32C*",$prefix);
                   12842: }
                   12843: 
1.76      www      12844: sub ireceipt {
1.474     albertel 12845:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 12846: 
                   12847:     my $return =&recprefix($fucourseid).'-';
                   12848: 
                   12849:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   12850: 	$env{'request.state'} eq 'construct') {
                   12851: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   12852: 	return $return;
                   12853:     }
                   12854: 
1.76      www      12855:     my $cuname=unpack("%32C*",$funame);
                   12856:     my $cudom=unpack("%32C*",$fudom);
                   12857:     my $cucourseid=unpack("%32C*",$fucourseid);
                   12858:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      12859:     my $cunique=&recunique($fucourseid);
1.474     albertel 12860:     my $cpart=unpack("%32S*",$part);
1.835     albertel 12861:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   12862: 
1.790     albertel 12863: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 12864: 			       
                   12865: 	$return.= ($cunique%$cuname+
                   12866: 		   $cunique%$cudom+
                   12867: 		   $cusymb%$cuname+
                   12868: 		   $cusymb%$cudom+
                   12869: 		   $cucourseid%$cuname+
                   12870: 		   $cucourseid%$cudom+
                   12871: 		   $cpart%$cuname+
                   12872: 		   $cpart%$cudom);
                   12873:     } else {
                   12874: 	$return.= ($cunique%$cuname+
                   12875: 		   $cunique%$cudom+
                   12876: 		   $cusymb%$cuname+
                   12877: 		   $cusymb%$cudom+
                   12878: 		   $cucourseid%$cuname+
                   12879: 		   $cucourseid%$cudom);
                   12880:     }
                   12881:     return $return;
1.76      www      12882: }
                   12883: 
                   12884: sub receipt {
1.474     albertel 12885:     my ($part)=@_;
1.790     albertel 12886:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 12887:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      12888: }
1.260     ng       12889: 
1.790     albertel 12890: sub whichuser {
                   12891:     my ($passedsymb)=@_;
                   12892:     my ($symb,$courseid,$domain,$name,$publicuser);
                   12893:     if (defined($env{'form.grade_symb'})) {
                   12894: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   12895: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   12896: 	if (!$allowed &&
                   12897: 	    exists($env{'request.course.sec'}) &&
                   12898: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   12899: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   12900: 			      '/'.$env{'request.course.sec'});
                   12901: 	}
                   12902: 	if ($allowed) {
                   12903: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   12904: 	    $courseid=$tmp_courseid;
                   12905: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   12906: 	    ($name)=&get_env_multiple('form.grade_username');
                   12907: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   12908: 	}
                   12909:     }
                   12910:     if (!$passedsymb) {
                   12911: 	$symb=&symbread();
                   12912:     } else {
                   12913: 	$symb=$passedsymb;
                   12914:     }
                   12915:     $courseid=$env{'request.course.id'};
                   12916:     $domain=$env{'user.domain'};
                   12917:     $name=$env{'user.name'};
                   12918:     if ($name eq 'public' && $domain eq 'public') {
                   12919: 	if (!defined($env{'form.username'})) {
                   12920: 	    $env{'form.username'}.=time.rand(10000000);
                   12921: 	}
                   12922: 	$name.=$env{'form.username'};
                   12923:     }
                   12924:     return ($symb,$courseid,$domain,$name,$publicuser);
                   12925: 
                   12926: }
                   12927: 
1.36      albertel 12928: # ------------------------------------------------------------ Serves up a file
1.472     albertel 12929: # returns either the contents of the file or 
                   12930: # -1 if the file doesn't exist
1.481     raeburn  12931: #
                   12932: # if the target is a file that was uploaded via DOCS, 
                   12933: # a check will be made to see if a current copy exists on the local server,
                   12934: # if it does this will be served, otherwise a copy will be retrieved from
                   12935: # the home server for the course and stored in /home/httpd/html/userfiles on
                   12936: # the local server.   
1.472     albertel 12937: 
1.36      albertel 12938: sub getfile {
1.538     albertel 12939:     my ($file) = @_;
1.609     banghart 12940:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 12941:     &repcopy($file);
                   12942:     return &readfile($file);
                   12943: }
                   12944: 
                   12945: sub repcopy_userfile {
                   12946:     my ($file)=@_;
1.1142    raeburn  12947:     my $londocroot = $perlvar{'lonDocRoot'};
                   12948:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  12949:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 12950:     my ($cdom,$cnum,$filename) = 
1.811     albertel 12951: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 12952:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   12953:     if (-e "$file") {
1.828     www      12954: # we already have a local copy, check it out
1.538     albertel 12955: 	my @fileinfo = stat($file);
1.828     www      12956: 	my $rtncode;
                   12957: 	my $info;
1.538     albertel 12958: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 12959: 	if ($lwpresp ne 'ok') {
1.828     www      12960: # there is no such file anymore, even though we had a local copy
1.482     albertel 12961: 	    if ($rtncode eq '404') {
1.538     albertel 12962: 		unlink($file);
1.482     albertel 12963: 	    }
                   12964: 	    return -1;
                   12965: 	}
                   12966: 	if ($info < $fileinfo[9]) {
1.828     www      12967: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  12968: 	    return 'ok';
1.828     www      12969: 	} else {
                   12970: # the file is outdated, get rid of it
                   12971: 	    unlink($file);
1.482     albertel 12972: 	}
1.828     www      12973:     }
                   12974: # one way or the other, at this point, we don't have the file
                   12975: # construct the correct path for the file
                   12976:     my @parts = ($cdom,$cnum); 
                   12977:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   12978: 	push @parts, split(/\//,$1);
                   12979:     }
                   12980:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   12981:     foreach my $part (@parts) {
                   12982: 	$path .= '/'.$part;
                   12983: 	if (!-e $path) {
                   12984: 	    mkdir($path,0770);
1.482     albertel 12985: 	}
                   12986:     }
1.828     www      12987: # now the path exists for sure
                   12988: # get a user agent
                   12989:     my $ua=new LWP::UserAgent;
                   12990:     my $transferfile=$file.'.in.transfer';
                   12991: # FIXME: this should flock
                   12992:     if (-e $transferfile) { return 'ok'; }
                   12993:     my $request;
                   12994:     $uri=~s/^\///;
1.980     raeburn  12995:     my $homeserver = &homeserver($cnum,$cdom);
                   12996:     my $protocol = $protocol{$homeserver};
                   12997:     $protocol = 'http' if ($protocol ne 'https');
                   12998:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      12999:     my $response=$ua->request($request,$transferfile);
                   13000: # did it work?
                   13001:     if ($response->is_error()) {
                   13002: 	unlink($transferfile);
                   13003: 	&logthis("Userfile repcopy failed for $uri");
                   13004: 	return -1;
                   13005:     }
                   13006: # worked, rename the transfer file
                   13007:     rename($transferfile,$file);
1.607     raeburn  13008:     return 'ok';
1.481     raeburn  13009: }
                   13010: 
1.517     albertel 13011: sub tokenwrapper {
                   13012:     my $uri=shift;
1.980     raeburn  13013:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 13014:     $uri=~s|^/||;
1.620     albertel 13015:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 13016:     my $token=$1;
1.552     albertel 13017:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   13018:     if ($udom && $uname && $file) {
                   13019: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  13020:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  13021:         my $homeserver = &homeserver($uname,$udom);
                   13022:         my $protocol = $protocol{$homeserver};
                   13023:         $protocol = 'http' if ($protocol ne 'https');
                   13024:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 13025:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   13026:                                '&tokenissued='.$perlvar{'lonHostID'};
                   13027:     } else {
                   13028:         return '/adm/notfound.html';
                   13029:     }
                   13030: }
                   13031: 
1.828     www      13032: # call with reqtype HEAD: get last modification time
                   13033: # call with reqtype GET: get the file contents
                   13034: # Do not call this with reqtype GET for large files! It loads everything into memory
                   13035: #
1.481     raeburn  13036: sub getuploaded {
                   13037:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   13038:     $uri=~s/^\///;
1.980     raeburn  13039:     my $homeserver = &homeserver($cnum,$cdom);
                   13040:     my $protocol = $protocol{$homeserver};
                   13041:     $protocol = 'http' if ($protocol ne 'https');
                   13042:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  13043:     my $ua=new LWP::UserAgent;
                   13044:     my $request=new HTTP::Request($reqtype,$uri);
                   13045:     my $response=$ua->request($request);
                   13046:     $$rtncode = $response->code;
1.482     albertel 13047:     if (! $response->is_success()) {
                   13048: 	return 'failed';
                   13049:     }      
                   13050:     if ($reqtype eq 'HEAD') {
1.486     www      13051: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 13052:     } elsif ($reqtype eq 'GET') {
                   13053: 	$$info = $response->content;
1.472     albertel 13054:     }
1.482     albertel 13055:     return 'ok';
1.36      albertel 13056: }
                   13057: 
1.481     raeburn  13058: sub readfile {
                   13059:     my $file = shift;
                   13060:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   13061:     my $fh;
1.1172.2.96  raeburn  13062:     open($fh,"<",$file);
1.481     raeburn  13063:     my $a='';
1.800     albertel 13064:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  13065:     return $a;
                   13066: }
                   13067: 
1.36      albertel 13068: sub filelocation {
1.590     banghart 13069:     my ($dir,$file) = @_;
                   13070:     my $location;
                   13071:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 13072: 
                   13073:     if ($file =~ m-^/adm/-) {
                   13074: 	$file=~s-^/adm/wrapper/-/-;
                   13075: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   13076:     }
1.882     albertel 13077: 
1.1139    www      13078:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  13079:         $location = $file;
1.609     banghart 13080:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 13081:         my ($udom,$uname,$filename)=
1.811     albertel 13082:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 13083:         my $home=&homeserver($uname,$udom);
                   13084:         my $is_me=0;
                   13085:         my @ids=&current_machine_ids();
                   13086:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   13087:         if ($is_me) {
1.1117    foxr     13088:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 13089:         } else {
                   13090:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   13091:   	      $udom.'/'.$uname.'/'.$filename;
                   13092:         }
1.882     albertel 13093:     } elsif ($file =~ m-^/adm/-) {
                   13094: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 13095:     } else {
                   13096:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      13097:         $file=~s:^/(res|priv)/:/:;
                   13098:         my $space=$1;
1.590     banghart 13099:         if ( !( $file =~ m:^/:) ) {
                   13100:             $location = $dir. '/'.$file;
                   13101:         } else {
1.1142    raeburn  13102:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 13103:         }
1.59      albertel 13104:     }
1.590     banghart 13105:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 13106:     while ($location=~m{/\.\./}) {
                   13107: 	if ($location =~ m{/[^/]+/\.\./}) {
                   13108: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   13109: 	} else {
                   13110: 	    $location=~ s{/\.\./}{/}g;
                   13111: 	}
                   13112:     } #remove dir/..
1.590     banghart 13113:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   13114:     return $location;
1.46      www      13115: }
1.36      albertel 13116: 
1.46      www      13117: sub hreflocation {
                   13118:     my ($dir,$file)=@_;
1.980     raeburn  13119:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 13120: 	$file=filelocation($dir,$file);
1.700     albertel 13121:     } elsif ($file=~m-^/adm/-) {
                   13122: 	$file=~s-^/adm/wrapper/-/-;
                   13123: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 13124:     }
                   13125:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   13126: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   13127:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  13128: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   13129: 	        {/uploaded/$1/$2/}x;
1.46      www      13130:     }
1.913     albertel 13131:     if ($file=~ m{^/userfiles/}) {
                   13132: 	$file =~ s{^/userfiles/}{/uploaded/};
                   13133:     }
1.462     albertel 13134:     return $file;
1.465     albertel 13135: }
                   13136: 
1.1139    www      13137: 
                   13138: 
                   13139: 
                   13140: 
1.465     albertel 13141: sub current_machine_domains {
1.853     albertel 13142:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   13143: }
                   13144: 
                   13145: sub machine_domains {
                   13146:     my ($hostname) = @_;
1.465     albertel 13147:     my @domains;
1.838     albertel 13148:     my %hostname = &all_hostnames();
1.465     albertel 13149:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  13150: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 13151: 	if ($hostname eq $name) {
1.844     albertel 13152: 	    push(@domains,&host_domain($id));
1.465     albertel 13153: 	}
                   13154:     }
                   13155:     return @domains;
                   13156: }
                   13157: 
                   13158: sub current_machine_ids {
1.853     albertel 13159:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   13160: }
                   13161: 
                   13162: sub machine_ids {
                   13163:     my ($hostname) = @_;
                   13164:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 13165:     my @ids;
1.888     albertel 13166:     my %name_to_host = &all_names();
1.889     albertel 13167:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   13168: 	return @{ $name_to_host{$hostname} };
                   13169:     }
                   13170:     return;
1.31      www      13171: }
                   13172: 
1.824     raeburn  13173: sub additional_machine_domains {
                   13174:     my @domains;
1.1172.2.96  raeburn  13175:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824     raeburn  13176:     while( my $line = <$fh>) {
                   13177:         $line =~ s/\s//g;
                   13178:         push(@domains,$line);
                   13179:     }
                   13180:     return @domains;
                   13181: }
                   13182: 
                   13183: sub default_login_domain {
                   13184:     my $domain = $perlvar{'lonDefDomain'};
                   13185:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   13186:     foreach my $posdom (&current_machine_domains(),
                   13187:                         &additional_machine_domains()) {
                   13188:         if (lc($posdom) eq lc($testdomain)) {
                   13189:             $domain=$posdom;
                   13190:             last;
                   13191:         }
                   13192:     }
                   13193:     return $domain;
                   13194: }
                   13195: 
1.1172.2.106  raeburn  13196: sub shared_institution {
                   13197:     my ($dom) = @_;
                   13198:     my $same_intdom;
                   13199:     my $hostintdom = &internet_dom($perlvar{'lonHostID'});
                   13200:     if ($hostintdom ne '') {
                   13201:         my %iphost = &get_iphost();
                   13202:         my $primary_id = &domain($dom,'primary');
                   13203:         my $primary_ip = &get_host_ip($primary_id);
                   13204:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
                   13205:             foreach my $id (@{$iphost{$primary_ip}}) {
                   13206:                 my $intdom = &internet_dom($id);
                   13207:                 if ($intdom eq $hostintdom) {
                   13208:                     $same_intdom = 1;
                   13209:                     last;
                   13210:                 }
                   13211:             }
                   13212:         }
                   13213:     }
                   13214:     return $same_intdom;
                   13215: }
                   13216: 
1.31      www      13217: # ------------------------------------------------------------- Declutters URLs
                   13218: 
                   13219: sub declutter {
                   13220:     my $thisfn=shift;
1.569     albertel 13221:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49  raeburn  13222:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   13223:         $thisfn=~s{^/home/httpd/html}{};
                   13224:     }
1.31      www      13225:     $thisfn=~s/^\///;
1.697     albertel 13226:     $thisfn=~s|^adm/wrapper/||;
                   13227:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      13228:     $thisfn=~s/^res\///;
1.1172    bisitz   13229:     $thisfn=~s/^priv\///;
1.1032    raeburn  13230:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   13231:         $thisfn=~s/\?.+$//;
                   13232:     }
1.268     www      13233:     return $thisfn;
                   13234: }
                   13235: 
                   13236: # ------------------------------------------------------------- Clutter up URLs
                   13237: 
                   13238: sub clutter {
                   13239:     my $thisfn='/'.&declutter(shift);
1.887     albertel 13240:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 13241: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      13242:        $thisfn='/res'.$thisfn; 
                   13243:     }
1.1031    raeburn  13244:     if ($thisfn !~m|^/adm|) {
                   13245: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 13246: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 13247: 	} else {
                   13248: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   13249: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 13250: 	    if ($embstyle eq 'ssi'
                   13251: 		|| ($embstyle eq 'hdn')
                   13252: 		|| ($embstyle eq 'rat')
                   13253: 		|| ($embstyle eq 'prv')
                   13254: 		|| ($embstyle eq 'ign')) {
                   13255: 		#do nothing with these
                   13256: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 13257: 		|| ($embstyle eq 'emb')
                   13258: 		|| ($embstyle eq 'wrp')) {
                   13259: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 13260: 	    } elsif ($embstyle eq 'unk'
                   13261: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 13262: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 13263: 	    } else {
1.718     www      13264: #		&logthis("Got a blank emb style");
1.695     albertel 13265: 	    }
1.694     albertel 13266: 	}
                   13267:     }
1.31      www      13268:     return $thisfn;
1.12      www      13269: }
                   13270: 
1.787     albertel 13271: sub clutter_with_no_wrapper {
                   13272:     my $uri = &clutter(shift);
                   13273:     if ($uri =~ m-^/adm/-) {
                   13274: 	$uri =~ s-^/adm/wrapper/-/-;
                   13275: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   13276:     }
                   13277:     return $uri;
                   13278: }
                   13279: 
1.557     albertel 13280: sub freeze_escape {
                   13281:     my ($value)=@_;
                   13282:     if (ref($value)) {
                   13283: 	$value=&nfreeze($value);
                   13284: 	return '__FROZEN__'.&escape($value);
                   13285:     }
                   13286:     return &escape($value);
                   13287: }
                   13288: 
1.11      www      13289: 
1.557     albertel 13290: sub thaw_unescape {
                   13291:     my ($value)=@_;
                   13292:     if ($value =~ /^__FROZEN__/) {
                   13293: 	substr($value,0,10,undef);
                   13294: 	$value=&unescape($value);
                   13295: 	return &thaw($value);
                   13296:     }
                   13297:     return &unescape($value);
                   13298: }
                   13299: 
1.436     albertel 13300: sub correct_line_ends {
                   13301:     my ($result)=@_;
                   13302:     $$result =~s/\r\n/\n/mg;
                   13303:     $$result =~s/\r/\n/mg;
1.415     albertel 13304: }
1.1       albertel 13305: # ================================================================ Main Program
                   13306: 
1.184     www      13307: sub goodbye {
1.204     albertel 13308:    &logthis("Starting Shut down");
1.443     albertel 13309: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 13310:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 13311: #converted
1.599     albertel 13312: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 13313:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   13314: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   13315: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 13316: #1.1 only
1.870     albertel 13317: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   13318: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   13319: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   13320: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   13321:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 13322:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   13323:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      13324:    &flushcourselogs();
                   13325:    &logthis("Shutting down");
                   13326: }
                   13327: 
1.852     albertel 13328: sub get_dns {
1.1172.2.17  raeburn  13329:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 13330:     if (!$ignore_cache) {
                   13331: 	my ($content,$cached)=
                   13332: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   13333: 	if ($cached) {
1.1172.2.17  raeburn  13334: 	    &$func($content,$hashref);
1.869     albertel 13335: 	    return;
                   13336: 	}
                   13337:     }
                   13338: 
                   13339:     my %alldns;
1.1172.2.96  raeburn  13340:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   13341:         foreach my $dns (<$config>) {
                   13342: 	    next if ($dns !~ /^\^(\S*)/x);
                   13343:             my $line = $1;
                   13344:             my ($host,$protocol) = split(/:/,$line);
                   13345:             if ($protocol ne 'https') {
                   13346:                 $protocol = 'http';
                   13347:             }
                   13348: 	    $alldns{$host} = $protocol;
1.979     raeburn  13349:         }
1.1172.2.96  raeburn  13350:         close($config);
1.869     albertel 13351:     }
                   13352:     while (%alldns) {
1.1172.2.52  raeburn  13353: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 13354: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  13355:         $ua->timeout(30);
1.979     raeburn  13356: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 13357: 	my $response=$ua->request($request);
1.979     raeburn  13358:         delete($alldns{$dns});
1.852     albertel 13359: 	next if ($response->is_error());
                   13360: 	my @content = split("\n",$response->content);
1.1172.2.17  raeburn  13361:         unless ($nocache) {
1.1172.2.23  raeburn  13362: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  13363:         }
                   13364: 	&$func(\@content,$hashref);
1.869     albertel 13365: 	return;
1.852     albertel 13366:     }
1.871     albertel 13367:     my $which = (split('/',$url))[3];
                   13368:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.105  raeburn  13369:     if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   13370:         my @content = <$config>;
                   13371:         &$func(\@content,$hashref);
                   13372:     }
1.1172.2.17  raeburn  13373:     return;
                   13374: }
                   13375: 
                   13376: # ------------------------------------------------------Get DNS checksums file
                   13377: sub parse_dns_checksums_tab {
                   13378:     my ($lines,$hashref) = @_;
1.1172.2.53  raeburn  13379:     my $lonhost = $perlvar{'lonHostID'};
                   13380:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17  raeburn  13381:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53  raeburn  13382:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   13383:     my $webconfdir = '/etc/httpd/conf';
                   13384:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   13385:         $webconfdir = '/etc/apache2';
                   13386:     } elsif ($distro =~ /^sles(\d+)$/) {
                   13387:         if ($1 >= 10) {
                   13388:             $webconfdir = '/etc/apache2';
                   13389:         }
                   13390:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   13391:         if ($1 >= 10.0) {
                   13392:             $webconfdir = '/etc/apache2';
                   13393:         }
                   13394:     }
1.1172.2.17  raeburn  13395:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13396:     my (%chksum,%revnum);
                   13397:     if (ref($lines) eq 'ARRAY') {
                   13398:         chomp(@{$lines});
1.1172.2.34  raeburn  13399:         my $version = shift(@{$lines});
                   13400:         if ($version eq $release) {
1.1172.2.17  raeburn  13401:             foreach my $line (@{$lines}) {
1.1172.2.34  raeburn  13402:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53  raeburn  13403:                 if ($file =~ m{^/etc/httpd/conf}) {
                   13404:                     if ($webconfdir eq '/etc/apache2') {
                   13405:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   13406:                     }
                   13407:                 }
1.1172.2.34  raeburn  13408:                 $chksum{$file} = $shasum;
                   13409:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  13410:             }
                   13411:             if (ref($hashref) eq 'HASH') {
                   13412:                 %{$hashref} = (
                   13413:                                 sums     => \%chksum,
                   13414:                                 versions => \%revnum,
                   13415:                               );
                   13416:             }
                   13417:         }
                   13418:     }
1.869     albertel 13419:     return;
1.852     albertel 13420: }
1.1172.2.17  raeburn  13421: 
                   13422: sub fetch_dns_checksums {
                   13423:     my %checksums;
1.1172.2.34  raeburn  13424:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48  raeburn  13425:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34  raeburn  13426:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13427:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  13428:              \%checksums);
                   13429:     return \%checksums;
                   13430: }
                   13431: 
1.327     albertel 13432: # ------------------------------------------------------------ Read domain file
                   13433: {
1.852     albertel 13434:     my $loaded;
1.846     albertel 13435:     my %domain;
                   13436: 
1.852     albertel 13437:     sub parse_domain_tab {
                   13438: 	my ($lines) = @_;
                   13439: 	foreach my $line (@$lines) {
                   13440: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      13441: 
1.846     albertel 13442: 	    chomp($line);
1.852     albertel 13443: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 13444: 	    my %this_domain;
                   13445: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   13446: 			       'lang_def', 'city', 'longi', 'lati',
                   13447: 			       'primary') {
                   13448: 		$this_domain{$field} = shift(@elements);
                   13449: 	    }
                   13450: 	    $domain{$name} = \%this_domain;
1.852     albertel 13451: 	}
                   13452:     }
1.864     albertel 13453: 
                   13454:     sub reset_domain_info {
                   13455: 	undef($loaded);
                   13456: 	undef(%domain);
                   13457:     }
                   13458: 
1.852     albertel 13459:     sub load_domain_tab {
1.1172.2.70  raeburn  13460: 	my ($ignore_cache,$nocache) = @_;
                   13461: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 13462: 	my $fh;
1.1172.2.96  raeburn  13463: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 13464: 	    my @lines = <$fh>;
                   13465: 	    &parse_domain_tab(\@lines);
1.448     albertel 13466: 	}
1.852     albertel 13467: 	close($fh);
                   13468: 	$loaded = 1;
1.327     albertel 13469:     }
1.846     albertel 13470: 
                   13471:     sub domain {
1.852     albertel 13472: 	&load_domain_tab() if (!$loaded);
                   13473: 
1.846     albertel 13474: 	my ($name,$what) = @_;
                   13475: 	return if ( !exists($domain{$name}) );
                   13476: 
                   13477: 	if (!$what) {
                   13478: 	    return $domain{$name}{'description'};
                   13479: 	}
                   13480: 	return $domain{$name}{$what};
                   13481:     }
1.974     raeburn  13482: 
                   13483:     sub domain_info {
                   13484:         &load_domain_tab() if (!$loaded);
                   13485:         return %domain;
                   13486:     }
                   13487: 
1.327     albertel 13488: }
                   13489: 
                   13490: 
1.1       albertel 13491: # ------------------------------------------------------------- Read hosts file
                   13492: {
1.838     albertel 13493:     my %hostname;
1.844     albertel 13494:     my %hostdom;
1.845     albertel 13495:     my %libserv;
1.852     albertel 13496:     my $loaded;
1.888     albertel 13497:     my %name_to_host;
1.1074    raeburn  13498:     my %internetdom;
1.1107    raeburn  13499:     my %LC_dns_serv;
1.852     albertel 13500: 
                   13501:     sub parse_hosts_tab {
                   13502: 	my ($file) = @_;
                   13503: 	foreach my $configline (@$file) {
                   13504: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  13505:             chomp($configline);
                   13506: 	    if ($configline =~ /^\^/) {
                   13507:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   13508:                     $LC_dns_serv{$1} = 1;
                   13509:                 }
                   13510:                 next;
                   13511:             }
1.1074    raeburn  13512: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 13513: 	    $name=~s/\s//g;
                   13514: 	    if ($id && $domain && $role && $name) {
1.1172.2.96  raeburn  13515:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   13516:                     my $curr = $hostname{$id};
                   13517:                     my $skip;
                   13518:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   13519:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   13520:                             $skip = 1;
                   13521:                         } else {
                   13522:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   13523:                         }
                   13524:                     }
                   13525:                     unless ($skip) {
                   13526:                         push(@{$name_to_host{$name}},$id);
                   13527:                     }
                   13528:                 } else {
                   13529:                     push(@{$name_to_host{$name}},$id);
                   13530:                 }
1.852     albertel 13531: 		$hostname{$id}=$name;
                   13532: 		$hostdom{$id}=$domain;
                   13533: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  13534:                 if (defined($protocol)) {
                   13535:                     if ($protocol eq 'https') {
                   13536:                         $protocol{$id} = $protocol;
                   13537:                     } else {
                   13538:                         $protocol{$id} = 'http'; 
                   13539:                     }
1.968     raeburn  13540:                 } else {
1.969     raeburn  13541:                     $protocol{$id} = 'http';
1.968     raeburn  13542:                 }
1.1074    raeburn  13543:                 if (defined($intdom)) {
                   13544:                     $internetdom{$id} = $intdom;
                   13545:                 }
1.852     albertel 13546: 	    }
                   13547: 	}
                   13548:     }
1.864     albertel 13549:     
                   13550:     sub reset_hosts_info {
1.897     albertel 13551: 	&purge_remembered();
1.864     albertel 13552: 	&reset_domain_info();
                   13553: 	&reset_hosts_ip_info();
1.892     albertel 13554: 	undef(%name_to_host);
1.864     albertel 13555: 	undef(%hostname);
                   13556: 	undef(%hostdom);
                   13557: 	undef(%libserv);
                   13558: 	undef($loaded);
                   13559:     }
1.1       albertel 13560: 
1.852     albertel 13561:     sub load_hosts_tab {
1.1172.2.70  raeburn  13562: 	my ($ignore_cache,$nocache) = @_;
                   13563: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96  raeburn  13564: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 13565: 	my @config = <$config>;
                   13566: 	&parse_hosts_tab(\@config);
                   13567: 	close($config);
                   13568: 	$loaded=1;
1.1       albertel 13569:     }
1.852     albertel 13570: 
1.838     albertel 13571:     sub hostname {
1.852     albertel 13572: 	&load_hosts_tab() if (!$loaded);
                   13573: 
1.838     albertel 13574: 	my ($lonid) = @_;
                   13575: 	return $hostname{$lonid};
                   13576:     }
1.845     albertel 13577: 
1.838     albertel 13578:     sub all_hostnames {
1.852     albertel 13579: 	&load_hosts_tab() if (!$loaded);
                   13580: 
1.838     albertel 13581: 	return %hostname;
                   13582:     }
1.845     albertel 13583: 
1.888     albertel 13584:     sub all_names {
1.1172.2.70  raeburn  13585:         my ($ignore_cache,$nocache) = @_;
                   13586: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 13587: 
                   13588: 	return %name_to_host;
                   13589:     }
                   13590: 
1.974     raeburn  13591:     sub all_host_domain {
                   13592:         &load_hosts_tab() if (!$loaded);
                   13593:         return %hostdom;
                   13594:     }
                   13595: 
1.845     albertel 13596:     sub is_library {
1.852     albertel 13597: 	&load_hosts_tab() if (!$loaded);
                   13598: 
1.845     albertel 13599: 	return exists($libserv{$_[0]});
                   13600:     }
                   13601: 
                   13602:     sub all_library {
1.852     albertel 13603: 	&load_hosts_tab() if (!$loaded);
                   13604: 
1.845     albertel 13605: 	return %libserv;
                   13606:     }
                   13607: 
1.1062    droeschl 13608:     sub unique_library {
                   13609: 	#2x reverse removes all hostnames that appear more than once
                   13610:         my %unique = reverse &all_library();
                   13611:         return reverse %unique;
                   13612:     }
                   13613: 
1.841     albertel 13614:     sub get_servers {
1.852     albertel 13615: 	&load_hosts_tab() if (!$loaded);
                   13616: 
1.841     albertel 13617: 	my ($domain,$type) = @_;
                   13618: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   13619: 	                                          : %hostname;
                   13620: 	my %result;
1.842     albertel 13621: 	if (ref($domain) eq 'ARRAY') {
                   13622: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 13623: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 13624: 		    $result{$host} = $hostname;
                   13625: 		}
                   13626: 	    }
                   13627: 	} else {
                   13628: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   13629: 		if ($hostdom{$host} eq $domain) {
                   13630: 		    $result{$host} = $hostname;
                   13631: 		}
1.841     albertel 13632: 	    }
                   13633: 	}
                   13634: 	return %result;
                   13635:     }
1.845     albertel 13636: 
1.1062    droeschl 13637:     sub get_unique_servers {
                   13638:         my %unique = reverse &get_servers(@_);
                   13639: 	return reverse %unique;
                   13640:     }
                   13641: 
1.844     albertel 13642:     sub host_domain {
1.852     albertel 13643: 	&load_hosts_tab() if (!$loaded);
                   13644: 
1.844     albertel 13645: 	my ($lonid) = @_;
                   13646: 	return $hostdom{$lonid};
                   13647:     }
                   13648: 
1.841     albertel 13649:     sub all_domains {
1.852     albertel 13650: 	&load_hosts_tab() if (!$loaded);
                   13651: 
1.841     albertel 13652: 	my %seen;
                   13653: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   13654: 	return @uniq;
                   13655:     }
1.1074    raeburn  13656: 
                   13657:     sub internet_dom {
                   13658:         &load_hosts_tab() if (!$loaded);
                   13659: 
                   13660:         my ($lonid) = @_;
                   13661:         return $internetdom{$lonid};
                   13662:     }
1.1107    raeburn  13663: 
                   13664:     sub is_LC_dns {
                   13665:         &load_hosts_tab() if (!$loaded);
                   13666: 
                   13667:         my ($hostname) = @_;
                   13668:         return exists($LC_dns_serv{$hostname});
                   13669:     }
                   13670: 
1.1       albertel 13671: }
                   13672: 
1.847     albertel 13673: { 
                   13674:     my %iphost;
1.856     albertel 13675:     my %name_to_ip;
                   13676:     my %lonid_to_ip;
1.869     albertel 13677: 
1.847     albertel 13678:     sub get_hosts_from_ip {
                   13679: 	my ($ip) = @_;
                   13680: 	my %iphosts = &get_iphost();
                   13681: 	if (ref($iphosts{$ip})) {
                   13682: 	    return @{$iphosts{$ip}};
                   13683: 	}
                   13684: 	return;
1.839     albertel 13685:     }
1.864     albertel 13686:     
                   13687:     sub reset_hosts_ip_info {
                   13688: 	undef(%iphost);
                   13689: 	undef(%name_to_ip);
                   13690: 	undef(%lonid_to_ip);
                   13691:     }
1.856     albertel 13692: 
                   13693:     sub get_host_ip {
                   13694: 	my ($lonid) = @_;
                   13695: 	if (exists($lonid_to_ip{$lonid})) {
                   13696: 	    return $lonid_to_ip{$lonid};
                   13697: 	}
                   13698: 	my $name=&hostname($lonid);
                   13699:    	my $ip = gethostbyname($name);
                   13700: 	return if (!$ip || length($ip) ne 4);
                   13701: 	$ip=inet_ntoa($ip);
                   13702: 	$name_to_ip{$name}   = $ip;
                   13703: 	$lonid_to_ip{$lonid} = $ip;
                   13704: 	return $ip;
                   13705:     }
1.847     albertel 13706:     
                   13707:     sub get_iphost {
1.1172.2.70  raeburn  13708: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 13709: 
1.869     albertel 13710: 	if (!$ignore_cache) {
                   13711: 	    if (%iphost) {
                   13712: 		return %iphost;
                   13713: 	    }
                   13714: 	    my ($ip_info,$cached)=
                   13715: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   13716: 	    if ($cached) {
                   13717: 		%iphost      = %{$ip_info->[0]};
                   13718: 		%name_to_ip  = %{$ip_info->[1]};
                   13719: 		%lonid_to_ip = %{$ip_info->[2]};
                   13720: 		return %iphost;
                   13721: 	    }
                   13722: 	}
1.894     albertel 13723: 
                   13724: 	# get yesterday's info for fallback
                   13725: 	my %old_name_to_ip;
                   13726: 	my ($ip_info,$cached)=
                   13727: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   13728: 	if ($cached) {
                   13729: 	    %old_name_to_ip = %{$ip_info->[1]};
                   13730: 	}
                   13731: 
1.1172.2.70  raeburn  13732: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 13733: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 13734: 	    my $ip;
                   13735: 	    if (!exists($name_to_ip{$name})) {
                   13736: 		$ip = gethostbyname($name);
                   13737: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 13738: 		    if (defined($old_name_to_ip{$name})) {
                   13739: 			$ip = $old_name_to_ip{$name};
                   13740: 			&logthis("Can't find $name defaulting to old $ip");
                   13741: 		    } else {
                   13742: 			&logthis("Name $name no IP found");
                   13743: 			next;
                   13744: 		    }
                   13745: 		} else {
                   13746: 		    $ip=inet_ntoa($ip);
1.847     albertel 13747: 		}
                   13748: 		$name_to_ip{$name} = $ip;
                   13749: 	    } else {
                   13750: 		$ip = $name_to_ip{$name};
1.653     albertel 13751: 	    }
1.888     albertel 13752: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   13753: 		$lonid_to_ip{$id} = $ip;
                   13754: 	    }
                   13755: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 13756: 	}
1.1172.2.70  raeburn  13757:         unless ($nocache) {
                   13758: 	    &do_cache_new('iphost','iphost',
                   13759: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   13760: 		          48*60*60);
                   13761:         }
1.869     albertel 13762: 
1.847     albertel 13763: 	return %iphost;
1.598     albertel 13764:     }
                   13765: 
1.992     raeburn  13766:     #
                   13767:     #  Given a DNS returns the loncapa host name for that DNS 
                   13768:     # 
                   13769:     sub host_from_dns {
                   13770:         my ($dns) = @_;
                   13771:         my @hosts;
                   13772:         my $ip;
                   13773: 
1.993     raeburn  13774:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  13775:             $ip = $name_to_ip{$dns};
                   13776:         }
                   13777:         if (!$ip) {
                   13778:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   13779:             if (length($ip) == 4) { 
                   13780: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   13781:             }
                   13782:         }
                   13783:         if ($ip) {
                   13784: 	    @hosts = get_hosts_from_ip($ip);
                   13785: 	    return $hosts[0];
                   13786:         }
                   13787:         return undef;
1.986     foxr     13788:     }
1.992     raeburn  13789: 
1.1074    raeburn  13790:     sub get_internet_names {
                   13791:         my ($lonid) = @_;
                   13792:         return if ($lonid eq '');
                   13793:         my ($idnref,$cached)=
                   13794:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   13795:         if ($cached) {
                   13796:             return $idnref;
                   13797:         }
                   13798:         my $ip = &get_host_ip($lonid);
                   13799:         my @hosts = &get_hosts_from_ip($ip);
                   13800:         my %iphost = &get_iphost();
                   13801:         my (@idns,%seen);
                   13802:         foreach my $id (@hosts) {
                   13803:             my $dom = &host_domain($id);
                   13804:             my $prim_id = &domain($dom,'primary');
                   13805:             my $prim_ip = &get_host_ip($prim_id);
                   13806:             next if ($seen{$prim_ip});
                   13807:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   13808:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   13809:                     my $intdom = &internet_dom($id);
                   13810:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   13811:                         push(@idns,$intdom);
                   13812:                     }
                   13813:                 }
                   13814:             }
                   13815:             $seen{$prim_ip} = 1;
                   13816:         }
1.1172.2.23  raeburn  13817:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  13818:     }
                   13819: 
1.986     foxr     13820: }
                   13821: 
1.1079    raeburn  13822: sub all_loncaparevs {
1.1172.2.39  raeburn  13823:     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  13824: }
                   13825: 
1.1172.2.27  raeburn  13826: # ------------------------------------------------------- Read loncaparev table
                   13827: {
                   13828:     sub load_loncaparevs {
                   13829:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96  raeburn  13830:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27  raeburn  13831:                 while (my $configline=<$config>) {
                   13832:                     chomp($configline);
                   13833:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   13834:                     $loncaparevs{$hostid}=$loncaparev;
                   13835:                 }
                   13836:                 close($config);
                   13837:             }
                   13838:         }
                   13839:     }
                   13840: }
                   13841: 
                   13842: # ----------------------------------------------------- Read serverhostID table
                   13843: {
                   13844:     sub load_serverhomeIDs {
                   13845:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96  raeburn  13846:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27  raeburn  13847:                 while (my $configline=<$config>) {
                   13848:                     chomp($configline);
                   13849:                     my ($name,$id)=split(/:/,$configline);
                   13850:                     $serverhomeIDs{$name}=$id;
                   13851:                 }
                   13852:                 close($config);
                   13853:             }
                   13854:         }
                   13855:     }
                   13856: }
                   13857: 
                   13858: 
1.862     albertel 13859: BEGIN {
                   13860: 
                   13861: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   13862:     unless ($readit) {
                   13863: {
                   13864:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   13865:     %perlvar = (%perlvar,%{$configvars});
                   13866: }
                   13867: 
                   13868: 
1.1       albertel 13869: # ------------------------------------------------------ Read spare server file
                   13870: {
1.1172.2.96  raeburn  13871:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 13872: 
                   13873:     while (my $configline=<$config>) {
                   13874:        chomp($configline);
1.284     matthew  13875:        if ($configline) {
1.784     albertel 13876: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 13877: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 13878: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 13879:        }
                   13880:     }
1.448     albertel 13881:     close($config);
1.1       albertel 13882: }
1.11      www      13883: # ------------------------------------------------------------ Read permissions
                   13884: {
1.1172.2.96  raeburn  13885:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      13886: 
                   13887:     while (my $configline=<$config>) {
1.448     albertel 13888: 	chomp($configline);
                   13889: 	if ($configline) {
                   13890: 	    my ($role,$perm)=split(/ /,$configline);
                   13891: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   13892: 	}
1.11      www      13893:     }
1.448     albertel 13894:     close($config);
1.11      www      13895: }
                   13896: 
                   13897: # -------------------------------------------- Read plain texts for permissions
                   13898: {
1.1172.2.96  raeburn  13899:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      13900: 
                   13901:     while (my $configline=<$config>) {
1.448     albertel 13902: 	chomp($configline);
                   13903: 	if ($configline) {
1.742     raeburn  13904: 	    my ($short,@plain)=split(/:/,$configline);
                   13905:             %{$prp{$short}} = ();
                   13906: 	    if (@plain > 0) {
                   13907:                 $prp{$short}{'std'} = $plain[0];
                   13908:                 for (my $i=1; $i<@plain; $i++) {
                   13909:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   13910:                 }
                   13911:             }
1.448     albertel 13912: 	}
1.135     www      13913:     }
1.448     albertel 13914:     close($config);
1.135     www      13915: }
                   13916: 
                   13917: # ---------------------------------------------------------- Read package table
                   13918: {
1.1172.2.96  raeburn  13919:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      13920: 
                   13921:     while (my $configline=<$config>) {
1.483     albertel 13922: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 13923: 	chomp($configline);
                   13924: 	my ($short,$plain)=split(/:/,$configline);
                   13925: 	my ($pack,$name)=split(/\&/,$short);
                   13926: 	if ($plain ne '') {
                   13927: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   13928: 	    $packagetab{$short}=$plain; 
                   13929: 	}
1.11      www      13930:     }
1.448     albertel 13931:     close($config);
1.329     matthew  13932: }
                   13933: 
1.1172.2.27  raeburn  13934: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  13935: 
1.1172.2.27  raeburn  13936: &load_loncaparevs();
                   13937: 
                   13938: # ------------------------------------------------------- Read serverhostID table
                   13939: 
                   13940: &load_serverhomeIDs();
1.1074    raeburn  13941: 
1.1172.2.27  raeburn  13942: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  13943: {
                   13944:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   13945:     if (-e $file) {
                   13946:         my $parser = HTML::LCParser->new($file);
                   13947:         while (my $token = $parser->get_token()) {
                   13948:             if ($token->[0] eq 'S') {
                   13949:                 my $item = $token->[1];
                   13950:                 my $name = $token->[2]{'name'};
                   13951:                 my $value = $token->[2]{'value'};
                   13952:                 if ($item ne '' && $name ne '' && $value ne '') {
                   13953:                     my $release = $parser->get_text();
                   13954:                     $release =~ s/(^\s*|\s*$ )//gx;
                   13955:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   13956:                 }
                   13957:             }
                   13958:         }
                   13959:     }
1.1073    raeburn  13960: }
                   13961: 
1.1138    raeburn  13962: # ---------------------------------------------------------- Read managers table
                   13963: {
                   13964:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96  raeburn  13965:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  13966:             while (my $configline=<$config>) {
                   13967:                 chomp($configline);
                   13968:                 next if ($configline =~ /^\#/);
                   13969:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   13970:                     $managerstab{$configline} = 1;
                   13971:                 }
                   13972:             }
                   13973:             close($config);
                   13974:         }
                   13975:     }
                   13976: }
                   13977: 
1.329     matthew  13978: # ------------- set up temporary directory
                   13979: {
1.1117    foxr     13980:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  13981: 
1.11      www      13982: }
                   13983: 
1.1172.2.104  raeburn  13984: # ------------- set default texengine (domain default overrides this)
                   13985: {
                   13986:     $deftex = LONCAPA::texengine();
                   13987: }
                   13988: 
1.1172.2.114  raeburn  13989: # ------------- set default minimum length for passwords for internal auth users
                   13990: {
                   13991:     $passwdmin = LONCAPA::passwd_min();
                   13992: }
                   13993: 
1.794     albertel 13994: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   13995: 				'compress_threshold'=> 20_000,
                   13996:  			        });
1.185     www      13997: 
1.281     www      13998: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      13999: $dumpcount=0;
1.958     www      14000: $locknum=0;
1.22      www      14001: 
1.163     harris41 14002: &logtouch();
1.672     albertel 14003: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      14004: $readit=1;
1.564     albertel 14005:     {
                   14006: 	use integer;
                   14007: 	my $test=(2**32)+1;
1.568     albertel 14008: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 14009: 	&logthis(" Detected 64bit platform ($_64bit)");
                   14010:     }
1.195     www      14011: }
1.1       albertel 14012: }
1.179     www      14013: 
1.1       albertel 14014: 1;
1.191     harris41 14015: __END__
                   14016: 
1.243     albertel 14017: =pod
                   14018: 
1.191     harris41 14019: =head1 NAME
                   14020: 
1.243     albertel 14021: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 14022: 
                   14023: =head1 SYNOPSIS
                   14024: 
1.243     albertel 14025: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 14026: 
                   14027:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   14028: 
1.243     albertel 14029: Common parameters:
                   14030: 
                   14031: =over 4
                   14032: 
                   14033: =item *
                   14034: 
                   14035: $uname : an internal username (if $cname expecting a course Id specifically)
                   14036: 
                   14037: =item *
                   14038: 
                   14039: $udom : a domain (if $cdom expecting a course's domain specifically)
                   14040: 
                   14041: =item *
                   14042: 
                   14043: $symb : a resource instance identifier
                   14044: 
                   14045: =item *
                   14046: 
                   14047: $namespace : the name of a .db file that contains the data needed or
                   14048: being set.
                   14049: 
                   14050: =back
                   14051: 
1.394     bowersj2 14052: =head1 OVERVIEW
1.191     harris41 14053: 
1.394     bowersj2 14054: lonnet provides subroutines which interact with the
                   14055: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   14056: about classes, users, and resources.
1.243     albertel 14057: 
                   14058: For many of these objects you can also use this to store data about
                   14059: them or modify them in various ways.
1.191     harris41 14060: 
1.394     bowersj2 14061: =head2 Symbs
1.191     harris41 14062: 
1.394     bowersj2 14063: To identify a specific instance of a resource, LON-CAPA uses symbols
                   14064: or "symbs"X<symb>. These identifiers are built from the URL of the
                   14065: map, the resource number of the resource in the map, and the URL of
                   14066: the resource itself. The latter is somewhat redundant, but might help
                   14067: if maps change.
                   14068: 
                   14069: An example is
                   14070: 
                   14071:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   14072: 
                   14073: The respective map entry is
                   14074: 
                   14075:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   14076:   title="Problem 2">
                   14077:  </resource>
                   14078: 
                   14079: Symbs are used by the random number generator, as well as to store and
                   14080: restore data specific to a certain instance of for example a problem.
                   14081: 
                   14082: =head2 Storing And Retrieving Data
                   14083: 
                   14084: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   14085: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   14086: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   14087: is is the non-critical message twin of cstore. These functions are for
                   14088: handlers to store a perl hash to a user's permanent data space in an
                   14089: easy manner, and to retrieve it again on another call. It is expected
                   14090: that a handler would use this once at the beginning to retrieve data,
                   14091: and then again once at the end to send only the new data back.
                   14092: 
                   14093: The data is stored in the user's data directory on the user's
                   14094: homeserver under the ID of the course.
                   14095: 
                   14096: The hash that is returned by restore will have all of the previous
                   14097: value for all of the elements of the hash.
                   14098: 
                   14099: Example:
                   14100: 
                   14101:  #creating a hash
                   14102:  my %hash;
                   14103:  $hash{'foo'}='bar';
                   14104: 
                   14105:  #storing it
                   14106:  &Apache::lonnet::cstore(\%hash);
                   14107: 
                   14108:  #changing a value
                   14109:  $hash{'foo'}='notbar';
                   14110: 
                   14111:  #adding a new value
                   14112:  $hash{'bar'}='foo';
                   14113:  &Apache::lonnet::cstore(\%hash);
                   14114: 
                   14115:  #retrieving the hash
                   14116:  my %history=&Apache::lonnet::restore();
                   14117: 
                   14118:  #print the hash
                   14119:  foreach my $key (sort(keys(%history))) {
                   14120:    print("\%history{$key} = $history{$key}");
                   14121:  }
                   14122: 
                   14123: Will print out:
1.191     harris41 14124: 
1.394     bowersj2 14125:  %history{1:foo} = bar
                   14126:  %history{1:keys} = foo:timestamp
                   14127:  %history{1:timestamp} = 990455579
                   14128:  %history{2:bar} = foo
                   14129:  %history{2:foo} = notbar
                   14130:  %history{2:keys} = foo:bar:timestamp
                   14131:  %history{2:timestamp} = 990455580
                   14132:  %history{bar} = foo
                   14133:  %history{foo} = notbar
                   14134:  %history{timestamp} = 990455580
                   14135:  %history{version} = 2
                   14136: 
                   14137: Note that the special hash entries C<keys>, C<version> and
                   14138: C<timestamp> were added to the hash. C<version> will be equal to the
                   14139: total number of versions of the data that have been stored. The
                   14140: C<timestamp> attribute will be the UNIX time the hash was
                   14141: stored. C<keys> is available in every historical section to list which
                   14142: keys were added or changed at a specific historical revision of a
                   14143: hash.
                   14144: 
                   14145: B<Warning>: do not store the hash that restore returns directly. This
                   14146: will cause a mess since it will restore the historical keys as if the
                   14147: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 14148: 
1.394     bowersj2 14149: Calling convention:
1.191     harris41 14150: 
1.1172.2.27  raeburn  14151:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64  raeburn  14152:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 14153: 
1.394     bowersj2 14154: For more detailed information, see lonnet specific documentation.
1.191     harris41 14155: 
1.394     bowersj2 14156: =head1 RETURN MESSAGES
1.191     harris41 14157: 
1.394     bowersj2 14158: =over 4
1.191     harris41 14159: 
1.394     bowersj2 14160: =item * B<con_lost>: unable to contact remote host
1.191     harris41 14161: 
1.394     bowersj2 14162: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   14163: when the connection is brought back up
1.191     harris41 14164: 
1.394     bowersj2 14165: =item * B<con_failed>: unable to contact remote host and unable to save message
                   14166: for later delivery
1.191     harris41 14167: 
1.967     bisitz   14168: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 14169: 
1.394     bowersj2 14170: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 14171: that was requested
1.191     harris41 14172: 
1.243     albertel 14173: =back
1.191     harris41 14174: 
1.243     albertel 14175: =head1 PUBLIC SUBROUTINES
1.191     harris41 14176: 
1.243     albertel 14177: =head2 Session Environment Functions
1.191     harris41 14178: 
1.243     albertel 14179: =over 4
1.191     harris41 14180: 
1.394     bowersj2 14181: =item * 
                   14182: X<appenv()>
1.949     raeburn  14183: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 14184: the user envirnoment file, and will be restored for each access this
1.620     albertel 14185: user makes during this session, also modifies the %env for the current
1.949     raeburn  14186: process. Optional rolesarrayref - if defined contains a reference to an array
                   14187: of roles which are exempt from the restriction on modifying user.role entries 
                   14188: in the user's environment.db and in %env.    
1.191     harris41 14189: 
                   14190: =item *
1.394     bowersj2 14191: X<delenv()>
1.987     raeburn  14192: B<delenv($delthis,$regexp)>: removes all items from the session
                   14193: environment file that begin with $delthis. If the 
                   14194: optional second arg - $regexp - is true, $delthis is treated as a 
                   14195: regular expression, otherwise \Q$delthis\E is used. 
                   14196: The values are also deleted from the current processes %env.
1.191     harris41 14197: 
1.795     albertel 14198: =item * get_env_multiple($name) 
                   14199: 
                   14200: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   14201: values may be defined and end up as an array ref.
                   14202: 
                   14203: returns an array of values
                   14204: 
1.243     albertel 14205: =back
                   14206: 
                   14207: =head2 User Information
1.191     harris41 14208: 
1.243     albertel 14209: =over 4
1.191     harris41 14210: 
                   14211: =item *
1.394     bowersj2 14212: X<queryauthenticate()>
                   14213: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 14214: authentication scheme
                   14215: 
                   14216: =item *
1.394     bowersj2 14217: X<authenticate()>
1.1073    raeburn  14218: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 14219: authenticate user from domain's lib servers (first use the current
                   14220: one). C<$upass> should be the users password.
1.1073    raeburn  14221: $checkdefauth is optional (value is 1 if a check should be made to
                   14222:    authenticate user using default authentication method, and allow
                   14223:    account creation if username does not have account in the domain).
                   14224: $clientcancheckhost is optional (value is 1 if checking whether the
                   14225:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 14226: 
                   14227: =item *
1.394     bowersj2 14228: X<homeserver()>
                   14229: B<homeserver($uname,$udom)>: find the server which has
                   14230: the user's directory and files (there must be only one), this caches
                   14231: the answer, and also caches if there is a borken connection.
1.191     harris41 14232: 
                   14233: =item *
1.394     bowersj2 14234: X<idget()>
                   14235: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   14236: (IDs are a unique resource in a domain, there must be only 1 ID per
                   14237: username, and only 1 username per ID in a specific domain) (returns
                   14238: hash: id=>name,id=>name)
1.191     harris41 14239: 
                   14240: =item *
1.394     bowersj2 14241: X<idrget()>
                   14242: B<idrget($udom,@unames)>: find the IDs behind a list of
                   14243: usernames (returns hash: name=>id,name=>id)
1.191     harris41 14244: 
                   14245: =item *
1.394     bowersj2 14246: X<idput()>
                   14247: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 14248: 
                   14249: =item *
1.394     bowersj2 14250: X<rolesinit()>
1.1169    droeschl 14251: B<rolesinit($udom,$username)>: get user privileges.
                   14252: returns user role, first access and timer interval hashes
1.243     albertel 14253: 
                   14254: =item *
1.1171    droeschl 14255: X<privileged()>
                   14256: B<privileged($username,$domain)>: returns a true if user has a
                   14257: privileged and active role (i.e. su or dc), false otherwise.
                   14258: 
                   14259: =item *
1.551     albertel 14260: X<getsection()>
                   14261: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 14262: course $cname, return section name/number or '' for "not in course"
                   14263: and '-1' for "no section"
                   14264: 
                   14265: =item *
1.394     bowersj2 14266: X<userenvironment()>
                   14267: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 14268: passed in @what from the requested user's environment, returns a hash
                   14269: 
1.858     raeburn  14270: =item * 
                   14271: X<userlog_query()>
1.859     albertel 14272: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   14273: activity.log file. %filters defines filters applied when parsing the
                   14274: log file. These can be start or end timestamps, or the type of action
                   14275: - log to look for Login or Logout events, check for Checkin or
                   14276: Checkout, role for role selection. The response is in the form
                   14277: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   14278: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  14279: 
1.243     albertel 14280: =back
                   14281: 
                   14282: =head2 User Roles
                   14283: 
                   14284: =over 4
                   14285: 
                   14286: =item *
                   14287: 
1.1172.2.65  raeburn  14288: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   14289: returns codes for allowed actions.
                   14290: 
                   14291: The first argument is required, all others are optional.
                   14292: 
                   14293: $priv is the privilege being checked.
                   14294: $uri contains additional information about what is being checked for access (e.g.,
                   14295: URL, course ID etc.).
                   14296: $symb is the unique resource instance identifier in a course; if needed,
                   14297: but not provided, it will be retrieved via a call to &symbread().
                   14298: $role is the role for which a priv is being checked (only used if priv is evb).
                   14299: $clientip is the user's IP address (only used when checking for access to portfolio
                   14300: files).
                   14301: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
                   14302: prevents recursive calls to &allowed.
                   14303: 
1.243     albertel 14304:  F: full access
                   14305:  U,I,K: authentication modes (cxx only)
                   14306:  '': forbidden
                   14307:  1: user needs to choose course
                   14308:  2: browse allowed
1.766     albertel 14309:  A: passphrase authentication needed
1.1172.2.65  raeburn  14310:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 14311: 
                   14312: =item *
                   14313: 
1.1172.2.13  raeburn  14314: constructaccess($url,$setpriv) : check for access to construction space URL
                   14315: 
                   14316: See if the owner domain and name in the URL match those in the
                   14317: expected environment.  If so, return three element list
                   14318: ($ownername,$ownerdomain,$ownerhome).
                   14319: 
                   14320: Otherwise return the null string.
                   14321: 
                   14322: If second argument 'setpriv' is true, it assigns the privileges,
                   14323: and returns the same three element list, unless the owner has
                   14324: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   14325: in which case the null string is returned.
                   14326: 
                   14327: =item *
                   14328: 
1.1172.2.84  raeburn  14329: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   14330: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   14331: for system, domain, and course level. $uname and $udom are optional (current
                   14332: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 14333: 
                   14334: =item *
                   14335: 
1.988     raeburn  14336: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   14337: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  14338: $type is Course (default) or Community.
1.988     raeburn  14339: If $forcedefault evaluates to true, text returned will be default 
                   14340: text for $type. Otherwise, if this is a course, the text returned 
                   14341: will be a custom name for the role (if defined in the course's 
                   14342: environment).  If no custom name is defined the default is returned.
                   14343:    
1.832     raeburn  14344: =item *
                   14345: 
1.1172.2.23  raeburn  14346: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  14347: All arguments are optional. Returns a hash of a roles, either for
                   14348: co-author/assistant author roles for a user's Construction Space
1.906     albertel 14349: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  14350: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   14351: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   14352: For each key, value is set to colon-separated start and end times for
                   14353: the role.  If no username and domain are specified, will default to
1.934     raeburn  14354: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  14355: of role statuses (active, future or previous), roles 
                   14356: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   14357: to restrict the list of roles reported. If no array ref is 
                   14358: provided for types, will default to return only active roles.
1.834     albertel 14359: 
1.1172.2.13  raeburn  14360: =item *
                   14361: 
                   14362: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   14363: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   14364: 
                   14365: Additional optional arguments are: $type (if role checking is to be restricted
                   14366: to certain user status types -- previous (expired roles), active (currently
                   14367: available roles) or future (roles available in the future), and
                   14368: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  14369: have active Domain Coordinator role in course's domain or in additional
                   14370: domains (specified in 'Domains to check for privileged users' in course
                   14371: environment -- set via:  Course Settings -> Classlists and staff listing).
                   14372: 
                   14373: =item *
                   14374: 
                   14375: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   14376: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   14377: $possdomains and $possroles are optional array refs -- to domains to check and
                   14378: roles to check.  If $possdomains is not specified, a dump will be done of the
                   14379: users' roles.db to check for a dc or su role in any domain. This can be
                   14380: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   14381: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   14382: this then allows &privileged_by_domain() to be used, which caches the identity
                   14383: of privileged users, eliminating the need for repeated calls to &dump().
                   14384: 
                   14385: =item *
                   14386: 
                   14387: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   14388: where the outer hash keys are domains specified in the $possdomains array ref,
                   14389: next inner hash keys are privileged roles specified in the $roles array ref,
                   14390: and the innermost hash contains key = value pairs for username:domain = end:start
                   14391: for active or future "privileged" users with that role in that domain. To avoid
                   14392: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   14393: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  14394: 
1.243     albertel 14395: =back
                   14396: 
                   14397: =head2 User Modification
                   14398: 
                   14399: =over 4
                   14400: 
                   14401: =item *
                   14402: 
1.957     raeburn  14403: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 14404: user for the level given by URL.  Optional start and end dates (leave empty
                   14405: string or zero for "no date")
1.191     harris41 14406: 
                   14407: =item *
                   14408: 
1.243     albertel 14409: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   14410: change a users, password, possible return values are: ok,
                   14411: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   14412: refused
1.191     harris41 14413: 
                   14414: =item *
                   14415: 
1.243     albertel 14416: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 14417: 
                   14418: =item *
                   14419: 
1.1058    raeburn  14420: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   14421:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   14422: 
                   14423: will update user information (firstname,middlename,lastname,generation,
                   14424: permanentemail), and if forceid is true, student/employee ID also.
                   14425: A user's institutional affiliation(s) can also be updated.
                   14426: User information fields will not be overwritten with empty entries 
                   14427: unless the field is included in the $candelete array reference.
                   14428: This array is included when a single user is modified via "Manage Users",
                   14429: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 14430: 
                   14431: =item *
                   14432: 
1.286     matthew  14433: modifystudent
                   14434: 
1.957     raeburn  14435: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  14436: The course id is resolved based on the current user's environment.  
                   14437: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  14438: associated with a course.
                   14439: 
1.297     matthew  14440: This call is essentially a wrapper for lonnet::modifyuser and
                   14441: lonnet::modify_student_enrollment
1.286     matthew  14442: 
                   14443: Inputs: 
                   14444: 
                   14445: =over 4
                   14446: 
1.957     raeburn  14447: =item B<$udom> Student's loncapa domain
1.286     matthew  14448: 
1.957     raeburn  14449: =item B<$uname> Student's loncapa login name
1.286     matthew  14450: 
1.964     bisitz   14451: =item B<$uid> Student/Employee ID
1.286     matthew  14452: 
1.957     raeburn  14453: =item B<$umode> Student's authentication mode
1.286     matthew  14454: 
1.957     raeburn  14455: =item B<$upass> Student's password
1.286     matthew  14456: 
1.957     raeburn  14457: =item B<$first> Student's first name
1.286     matthew  14458: 
1.957     raeburn  14459: =item B<$middle> Student's middle name
1.286     matthew  14460: 
1.957     raeburn  14461: =item B<$last> Student's last name
1.286     matthew  14462: 
1.957     raeburn  14463: =item B<$gene> Student's generation
1.286     matthew  14464: 
1.957     raeburn  14465: =item B<$usec> Student's section in course
1.286     matthew  14466: 
                   14467: =item B<$end> Unix time of the roles expiration
                   14468: 
                   14469: =item B<$start> Unix time of the roles start date
                   14470: 
                   14471: =item B<$forceid> If defined, allow $uid to be changed
                   14472: 
                   14473: =item B<$desiredhome> server to use as home server for student
                   14474: 
1.957     raeburn  14475: =item B<$email> Student's permanent e-mail address
                   14476: 
                   14477: =item B<$type> Type of enrollment (auto or manual)
                   14478: 
1.963     raeburn  14479: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   14480: 
                   14481: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  14482: 
1.963     raeburn  14483: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  14484: 
1.963     raeburn  14485: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  14486: 
1.1172.2.19  raeburn  14487: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   14488: 
                   14489: =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  14490: 
1.286     matthew  14491: =back
1.297     matthew  14492: 
                   14493: =item *
                   14494: 
                   14495: modify_student_enrollment
                   14496: 
1.1172.2.31  raeburn  14497: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  14498: 'role.request.course' must be defined for this function to proceed.
                   14499: 
                   14500: Inputs:
                   14501: 
                   14502: =over 4
                   14503: 
1.1172.2.31  raeburn  14504: =item $udom, student's domain
1.297     matthew  14505: 
1.1172.2.31  raeburn  14506: =item $uname, student's name
1.297     matthew  14507: 
1.1172.2.31  raeburn  14508: =item $uid, student's user id
1.297     matthew  14509: 
1.1172.2.31  raeburn  14510: =item $first, student's first name
1.297     matthew  14511: 
                   14512: =item $middle
                   14513: 
                   14514: =item $last
                   14515: 
                   14516: =item $gene
                   14517: 
                   14518: =item $usec
                   14519: 
                   14520: =item $end
                   14521: 
                   14522: =item $start
                   14523: 
1.957     raeburn  14524: =item $type
                   14525: 
                   14526: =item $locktype
                   14527: 
                   14528: =item $cid
                   14529: 
                   14530: =item $selfenroll
                   14531: 
                   14532: =item $context
                   14533: 
1.1172.2.19  raeburn  14534: =item $credits, number of credits student will earn from this class
                   14535: 
1.1172.2.76  raeburn  14536: =item $instsec, institutional course section code for student
                   14537: 
1.297     matthew  14538: =back
                   14539: 
1.191     harris41 14540: 
                   14541: =item *
                   14542: 
1.243     albertel 14543: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   14544: custom role; give a custom role to a user for the level given by URL.  Specify
                   14545: name and domain of role author, and role name
1.191     harris41 14546: 
                   14547: =item *
                   14548: 
1.243     albertel 14549: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 14550: 
                   14551: =item *
                   14552: 
1.243     albertel 14553: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   14554: 
                   14555: =back
                   14556: 
                   14557: =head2 Course Infomation
                   14558: 
                   14559: =over 4
1.191     harris41 14560: 
                   14561: =item *
                   14562: 
1.1118    foxr     14563: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 14564: specified course id, including all environment settings for the
                   14565: course, the description of the course will be in the hash under the
                   14566: key 'description'
1.191     harris41 14567: 
1.1118    foxr     14568: $options is an optional parameter that if supplied is a hash reference that controls
                   14569: what how this function works.  It has the following key/values:
                   14570: 
                   14571: =over 4
                   14572: 
                   14573: =item freshen_cache
                   14574: 
                   14575: If defined, and the environment cache for the course is valid, it is 
                   14576: returned in the returned hash.
                   14577: 
                   14578: =item one_time
                   14579: 
                   14580: If defined, the last cache time is set to _now_
                   14581: 
                   14582: =item user
                   14583: 
                   14584: If defined, the supplied username is used instead of the current user.
                   14585: 
                   14586: 
                   14587: =back
                   14588: 
1.191     harris41 14589: =item *
                   14590: 
1.624     albertel 14591: resdata($name,$domain,$type,@which) : request for current parameter
                   14592: setting for a specific $type, where $type is either 'course' or 'user',
                   14593: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  14594: answers for 10 minutes.
1.243     albertel 14595: 
1.877     foxr     14596: =item *
                   14597: 
                   14598: get_courseresdata($courseid, $domain) : dump the entire course resource
                   14599: data base, returning a hash that is keyed by the resource name and has
                   14600: values that are the resource value.  I believe that the timestamps and
                   14601: versions are also returned.
                   14602: 
1.1172.2.31  raeburn  14603: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   14604: supplemental content area. This routine caches the number of files for
                   14605: 10 minutes.
                   14606: 
1.243     albertel 14607: =back
                   14608: 
                   14609: =head2 Course Modification
                   14610: 
                   14611: =over 4
1.191     harris41 14612: 
                   14613: =item *
                   14614: 
1.243     albertel 14615: writecoursepref($courseid,%prefs) : write preferences (environment
                   14616: database) for a course
1.191     harris41 14617: 
                   14618: =item *
                   14619: 
1.1011    raeburn  14620: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   14621: 
                   14622: =item *
                   14623: 
1.1038    raeburn  14624: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 14625: 
1.1167    droeschl 14626: =item *
                   14627: 
                   14628: is_course($courseid), is_course($cdom, $cnum)
                   14629: 
                   14630: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   14631: two component version $cdom, $cnum. It checks if the specified course exists.
                   14632: 
                   14633: Returns:
                   14634:     undef if the course doesn't exist, otherwise
                   14635:     in scalar context the combined courseid.
                   14636:     in list context the two components of the course identifier, domain and 
                   14637:     courseid.    
                   14638: 
1.243     albertel 14639: =back
                   14640: 
1.1172.2.109  raeburn  14641: =head2 Bubblesheet Configuration
                   14642: 
                   14643: =over 4
                   14644: 
                   14645: =item *
                   14646: 
                   14647: get_scantron_config($which)
                   14648: 
                   14649: $which - the name of the configuration to parse from the file.
                   14650: 
                   14651: Parses and returns the bubblesheet configuration line selected as a
                   14652: hash of configuration file fields.
                   14653: 
                   14654: 
                   14655: Returns:
                   14656:     If the named configuration is not in the file, an empty
                   14657:     hash is returned.
                   14658: 
                   14659:     a hash with the fields
                   14660:       name         - internal name for the this configuration setup
                   14661:       description  - text to display to operator that describes this config
                   14662:       CODElocation - if 0 or the string 'none'
                   14663:                           - no CODE exists for this config
                   14664:                      if -1 || the string 'letter'
                   14665:                           - a CODE exists for this config and is
                   14666:                             a string of letters
                   14667:                      Unsupported value (but planned for future support)
                   14668:                           if a positive integer
                   14669:                                - The CODE exists as the first n items from
                   14670:                                  the question section of the form
                   14671:                           if the string 'number'
                   14672:                                - The CODE exists for this config and is
                   14673:                                  a string of numbers
                   14674:       CODEstart   - (only matter if a CODE exists) column in the line where
                   14675:                      the CODE starts
                   14676:       CODElength  - length of the CODE
                   14677:       IDstart     - column where the student/employee ID starts
                   14678:       IDlength    - length of the student/employee ID info
                   14679:       Qstart      - column where the information from the bubbled
                   14680:                     'questions' start
                   14681:       Qlength     - number of columns comprising a single bubble line from
                   14682:                     the sheet. (usually either 1 or 10)
                   14683:       Qon         - either a single character representing the character used
                   14684:                     to signal a bubble was chosen in the positional setup, or
                   14685:                     the string 'letter' if the letter of the chosen bubble is
                   14686:                     in the final, or 'number' if a number representing the
                   14687:                     chosen bubble is in the file (1->A 0->J)
                   14688:       Qoff        - the character used to represent that a bubble was
                   14689:                     left blank
                   14690:       PaperID     - if the scanning process generates a unique number for each
                   14691:                     sheet scanned the column that this ID number starts in
                   14692:       PaperIDlength - number of columns that comprise the unique ID number
                   14693:                       for the sheet of paper
                   14694:       FirstName   - column that the first name starts in
                   14695:       FirstNameLength - number of columns that the first name spans
                   14696:       LastName    - column that the last name starts in
                   14697:       LastNameLength - number of columns that the last name spans
                   14698:       BubblesPerRow - number of bubbles available in each row used to
                   14699:                       bubble an answer. (If not specified, 10 assumed).
                   14700: 
                   14701: 
                   14702: =item *
                   14703: 
                   14704: get_scantronformat_file($cdom)
                   14705: 
                   14706: $cdom - the course's domain (optional); if not supplied, uses
                   14707: domain for current $env{'request.course.id'}.
                   14708: 
                   14709: Returns an array containing lines from the scantron format file for
                   14710: the domain of the course.
                   14711: 
                   14712: If a url for a custom.tab file is listed in domain's configuration.db,
                   14713: lines are from this file.
                   14714: 
                   14715: Otherwise, if a default.tab has been published in RES space by the
                   14716: domainconfig user, lines are from this file.
                   14717: 
                   14718: Otherwise, fall back to getting lines from the legacy file on the
                   14719: local server:  /home/httpd/lonTabs/default_scantronformat.tab
                   14720: 
                   14721: =back
                   14722: 
1.243     albertel 14723: =head2 Resource Subroutines
                   14724: 
                   14725: =over 4
1.191     harris41 14726: 
                   14727: =item *
                   14728: 
1.243     albertel 14729: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 14730: 
                   14731: =item *
                   14732: 
1.243     albertel 14733: repcopy($filename) : subscribes to the requested file, and attempts to
                   14734: replicate from the owning library server, Might return
1.607     raeburn  14735: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   14736: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 14737: resource. Expects the local filesystem pathname
                   14738: (/home/httpd/html/res/....)
                   14739: 
                   14740: =back
                   14741: 
                   14742: =head2 Resource Information
                   14743: 
                   14744: =over 4
1.191     harris41 14745: 
                   14746: =item *
                   14747: 
1.1172.2.28  raeburn  14748: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   14749: and returns the value of a variety of different possible values,
                   14750: $varname should be a request string, and the other parameters can be
                   14751: used to specify who and what one is asking about. Ordinarily, $cid 
                   14752: does not need to be specified, as it is retrived from 
                   14753: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   14754: within lonuserstate::loadmap() when initializing a course, before
                   14755: $env{'request.course.id'} has been set, so it needs to be provided
                   14756: in that one case.
1.243     albertel 14757: 
                   14758: Possible values for $varname are environment.lastname (or other item
                   14759: from the envirnment hash), user.name (or someother aspect about the
                   14760: user), resource.0.maxtries (or some other part and parameter of a
                   14761: resource)
1.204     albertel 14762: 
                   14763: =item *
                   14764: 
1.243     albertel 14765: directcondval($number) : get current value of a condition; reads from a state
                   14766: string
1.204     albertel 14767: 
                   14768: =item *
                   14769: 
1.243     albertel 14770: condval($condidx) : value of condition index based on state
1.204     albertel 14771: 
                   14772: =item *
                   14773: 
1.243     albertel 14774: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   14775: resource's metadata, $what should be either a specific key, or either
                   14776: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   14777: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   14778: 
                   14779: this function automatically caches all requests
1.191     harris41 14780: 
                   14781: =item *
                   14782: 
1.243     albertel 14783: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   14784: network of library servers; returns file handle of where SQL and regex results
                   14785: will be stored for query
1.191     harris41 14786: 
                   14787: =item *
                   14788: 
1.1172.2.66  raeburn  14789: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
                   14790: return symbolic list entry (all arguments optional).
                   14791: 
                   14792: Args: filename is the filename (including path) for the file for which a symb
                   14793: is required; donotrecurse, if true will prevent calls to allowed() being made
                   14794: to check access status if more than one resource was found in the bighash
                   14795: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
                   14796: a randompick); ignorecachednull, if true will prevent a symb of '' being
                   14797: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   14798: cause possible symbs to be checked to determine if they are subject to content
                   14799: blocking, if so they will not be included as possible symbs; possibles is a
                   14800: ref to a hash, which, as a side effect, will be populated with all possible
                   14801: symbs (content blocking not tested).
                   14802: 
1.243     albertel 14803: returns the data handle
1.191     harris41 14804: 
                   14805: =item *
                   14806: 
1.1172.2.17  raeburn  14807: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  14808: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 14809: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  14810: on failure, user must be in a course, as it assumes the existence of
                   14811: the course initial hash, and uses $env('request.course.id'}.  The third
                   14812: arg is an optional reference to a scalar.  If this arg is passed in the
                   14813: call to symbverify, it will be set to 1 if the symb has been set to be 
                   14814: encrypted; otherwise it will be null.
1.243     albertel 14815: 
1.191     harris41 14816: =item *
                   14817: 
1.243     albertel 14818: symbclean($symb) : removes versions numbers from a symb, returns the
                   14819: cleaned symb
1.191     harris41 14820: 
                   14821: =item *
                   14822: 
1.243     albertel 14823: is_on_map($uri) : checks if the $uri is somewhere on the current
                   14824: course map, user must be in a course for it to work.
1.191     harris41 14825: 
                   14826: =item *
                   14827: 
1.243     albertel 14828: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 14829: 
                   14830: =item *
                   14831: 
1.243     albertel 14832: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   14833: a random seed, all arguments are optional, if they aren't sent it uses the
                   14834: environment to derive them. Note: if symb isn't sent and it can't get one
                   14835: from &symbread it will use the current time as its return value
1.191     harris41 14836: 
                   14837: =item *
                   14838: 
1.243     albertel 14839: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   14840: unfakeable, receipt
1.191     harris41 14841: 
                   14842: =item *
                   14843: 
1.620     albertel 14844: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 14845: 
                   14846: =item *
                   14847: 
1.243     albertel 14848: countacc($url) : count the number of accesses to a given URL
1.191     harris41 14849: 
                   14850: =item *
                   14851: 
1.243     albertel 14852: 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 14853: 
                   14854: =item *
                   14855: 
1.243     albertel 14856: 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 14857: 
                   14858: =item *
                   14859: 
1.243     albertel 14860: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 14861: 
                   14862: =item *
                   14863: 
1.243     albertel 14864: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   14865: forcing spreadsheet to reevaluate the resource scores next time.
                   14866: 
1.1172.2.13  raeburn  14867: =item *
                   14868: 
                   14869: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   14870: when viewing in course context.
                   14871: 
                   14872:  input: six args -- filename (decluttered), course number, course domain,
                   14873:                     url, symb (if registered) and group (if this is a
                   14874:                     group item -- e.g., bulletin board, group page etc.).
                   14875: 
                   14876:  output: array of five scalars --
                   14877:          $cfile -- url for file editing if editable on current server
                   14878:          $home -- homeserver of resource (i.e., for author if published,
                   14879:                                           or course if uploaded.).
                   14880:          $switchserver --  1 if server switch will be needed.
                   14881:          $forceedit -- 1 if icon/link should be to go to edit mode
                   14882:          $forceview -- 1 if icon/link should be to go to view mode
                   14883: 
                   14884: =item *
                   14885: 
                   14886: is_course_upload($file,$cnum,$cdom)
                   14887: 
                   14888: Used in course context to determine if current file was uploaded to
                   14889: the course (i.e., would be found in /userfiles/docs on the course's
                   14890: homeserver.
                   14891: 
                   14892:   input: 3 args -- filename (decluttered), course number and course domain.
                   14893:   output: boolean -- 1 if file was uploaded.
                   14894: 
1.243     albertel 14895: =back
                   14896: 
                   14897: =head2 Storing/Retreiving Data
                   14898: 
                   14899: =over 4
1.191     harris41 14900: 
                   14901: =item *
                   14902: 
1.1172.2.64  raeburn  14903: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
                   14904: permanently for this url; hashref needs to be given and should be a \%hashname;
                   14905: the remaining args aren't required and if they aren't passed or are '' they will
                   14906: be derived from the env (with the exception of $laststore, which is an
                   14907: optional arg used when a user's submission is stored in grading).
                   14908: $laststore is $version=$timestamp, where $version is the most recent version
                   14909: number retrieved for the corresponding $symb in the $namespace db file, and
                   14910: $timestamp is the timestamp for that transaction (UNIX time).
                   14911: $laststore is currently only passed when cstore() is called by
                   14912: structuretags::finalize_storage().
1.191     harris41 14913: 
                   14914: =item *
                   14915: 
1.1172.2.64  raeburn  14916: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
                   14917: but uses critical subroutine
1.191     harris41 14918: 
                   14919: =item *
                   14920: 
1.243     albertel 14921: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   14922: all args are optional
1.191     harris41 14923: 
                   14924: =item *
                   14925: 
1.717     albertel 14926: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   14927: dumps the complete (or key matching regexp) namespace into a hash
                   14928: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   14929: normally &store()ed into
                   14930: 
                   14931: $range should be either an integer '100' (give me the first 100
                   14932:                                            matching records)
                   14933:               or be  two integers sperated by a - with no spaces
                   14934:                  '30-50' (give me the 30th through the 50th matching
                   14935:                           records)
                   14936: 
                   14937: 
                   14938: =item *
                   14939: 
1.1172.2.59  raeburn  14940: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 14941: replaces a &store() version of data with a replacement set of data
                   14942: for a particular resource in a namespace passed in the $storehash hash 
1.1172.2.59  raeburn  14943: reference. If $tolog is true, the transaction is logged in the courselog
                   14944: with an action=PUTSTORE.
1.717     albertel 14945: 
                   14946: =item *
                   14947: 
1.243     albertel 14948: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   14949: works very similar to store/cstore, but all data is stored in a
                   14950: temporary location and can be reset using tmpreset, $storehash should
                   14951: be a hash reference, returns nothing on success
1.191     harris41 14952: 
                   14953: =item *
                   14954: 
1.243     albertel 14955: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   14956: similar to restore, but all data is stored in a temporary location and
                   14957: can be reset using tmpreset. Returns a hash of values on success,
                   14958: error string otherwise.
1.191     harris41 14959: 
                   14960: =item *
                   14961: 
1.243     albertel 14962: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   14963: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 14964: 
                   14965: =item *
                   14966: 
1.243     albertel 14967: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14968: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 14969: 
                   14970: =item *
                   14971: 
1.243     albertel 14972: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   14973: namesp ($udom and $uname are optional)
1.191     harris41 14974: 
                   14975: =item *
                   14976: 
1.702     albertel 14977: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 14978: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 14979: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  14980: 
1.702     albertel 14981: $range should be either an integer '100' (give me the first 100
                   14982:                                            matching records)
                   14983:               or be  two integers sperated by a - with no spaces
                   14984:                  '30-50' (give me the 30th through the 50th matching
                   14985:                           records)
1.449     matthew  14986: =item *
                   14987: 
                   14988: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   14989: $store can be a scalar, an array reference, or if the amount to be 
                   14990: incremented is > 1, a hash reference.
                   14991: 
                   14992: ($udom and $uname are optional)
1.191     harris41 14993: 
                   14994: =item *
                   14995: 
1.243     albertel 14996: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   14997: ($udom and $uname are optional)
1.191     harris41 14998: 
                   14999: =item *
                   15000: 
1.243     albertel 15001: cput($namespace,$storehash,$udom,$uname) : critical put
                   15002: ($udom and $uname are optional)
1.191     harris41 15003: 
                   15004: =item *
                   15005: 
1.748     albertel 15006: newput($namespace,$storehash,$udom,$uname) :
                   15007: 
                   15008: Attempts to store the items in the $storehash, but only if they don't
                   15009: currently exist, if this succeeds you can be certain that you have 
                   15010: successfully created a new key value pair in the $namespace db.
                   15011: 
                   15012: 
                   15013: Args:
                   15014:  $namespace: name of database to store values to
                   15015:  $storehash: hashref to store to the db
                   15016:  $udom: (optional) domain of user containing the db
                   15017:  $uname: (optional) name of user caontaining the db
                   15018: 
                   15019: Returns:
                   15020:  'ok' -> succeeded in storing all keys of $storehash
                   15021:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   15022:                         least <key> already existed in the db (other
                   15023:                         requested keys may also already exist)
1.967     bisitz   15024:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 15025:  'con_lost' -> unable to contact request server
                   15026:  'refused' -> action was not allowed by remote machine
                   15027: 
                   15028: 
                   15029: =item *
                   15030: 
1.243     albertel 15031: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15032: reference filled in from namesp (encrypts the return communication)
                   15033: ($udom and $uname are optional)
1.191     harris41 15034: 
                   15035: =item *
                   15036: 
1.243     albertel 15037: log($udom,$name,$home,$message) : write to permanent log for user; use
                   15038: critical subroutine
                   15039: 
1.806     raeburn  15040: =item *
                   15041: 
1.860     raeburn  15042: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   15043: array reference filled in from namespace found in domain level on either
                   15044: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  15045: 
                   15046: =item *
                   15047: 
1.860     raeburn  15048: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   15049: domain level either on specified domain server ($uhome) or primary domain 
                   15050: server ($udom and $uhome are optional)
1.806     raeburn  15051: 
1.943     raeburn  15052: =item * 
                   15053: 
1.1172.2.35  raeburn  15054: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
                   15055: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   15056: the target domain.
                   15057: 
                   15058: May also include additional key => value pairs for the following groups:
                   15059: 
                   15060: =over
                   15061: 
                   15062: =item
                   15063: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   15064: 
                   15065: =over
                   15066: 
                   15067: =item defaultquota, authorquota
                   15068: 
                   15069: =back
                   15070: 
                   15071: =item
                   15072: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   15073: portfolio for users).
                   15074: 
                   15075: =over
                   15076: 
                   15077: =item
                   15078: aboutme, blog, webdav, portfolio
                   15079: 
                   15080: =back
                   15081: 
                   15082: =item
                   15083: requestcourses: ability to request courses, and how requests are processed.
                   15084: 
                   15085: =over
                   15086: 
                   15087: =item
1.1172.2.37  raeburn  15088: official, unofficial, community, textbook
1.1172.2.35  raeburn  15089: 
                   15090: =back
                   15091: 
                   15092: =item
                   15093: inststatus: types of institutional affiliation, and order in which they are displayed.
                   15094: 
                   15095: =over
                   15096: 
                   15097: =item
1.1172.2.44  raeburn  15098: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35  raeburn  15099: 
                   15100: =back
                   15101: 
                   15102: =item
                   15103: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   15104: for course's uploaded content.
                   15105: 
                   15106: =over
                   15107: 
                   15108: =item
1.1172.2.68  raeburn  15109: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
                   15110: communityquota, textbookquota
1.1172.2.35  raeburn  15111: 
                   15112: =back
                   15113: 
                   15114: =item
                   15115: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   15116: on your servers.
                   15117: 
                   15118: =over
                   15119: 
                   15120: =item
                   15121: remotesessions, hostedsessions
                   15122: 
                   15123: =back
                   15124: 
                   15125: =back
                   15126: 
                   15127: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   15128: utility to create a configuration.db file on a domain's primary library server
                   15129: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   15130: -- corresponding values are authentication type (internal, krb4, krb5,
                   15131: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
                   15132: will be available. Values are retrieved from cache (if current), unless the
                   15133: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   15134: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   15135: 
                   15136: Typical usage:
1.943     raeburn  15137: 
1.1172.2.35  raeburn  15138: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  15139: 
1.243     albertel 15140: =back
                   15141: 
                   15142: =head2 Network Status Functions
                   15143: 
                   15144: =over 4
1.191     harris41 15145: 
                   15146: =item *
                   15147: 
1.1137    raeburn  15148: dirlist() : return directory list based on URI (first arg).
                   15149: 
                   15150: Inputs: 1 required, 5 optional.
                   15151: 
                   15152: =over
                   15153: 
                   15154: =item 
                   15155: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   15156: 
                   15157: =item
                   15158: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   15159: 
                   15160: =item
                   15161: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   15162: 
                   15163: =item
                   15164: $getpropath - boolean: 1 if prepend path using &propath(). 
                   15165: 
                   15166: =item
                   15167: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   15168: 
                   15169: =item 
                   15170: $alternateRoot - path to prepend in place of path from $uri.
                   15171: 
                   15172: =back
                   15173: 
                   15174: Returns: Array of up to two items.
                   15175: 
                   15176: =over
                   15177: 
                   15178: a reference to an array of files/subdirectories
                   15179: 
                   15180: =over
                   15181: 
                   15182: Each element in the array of files/subdirectories is a & separated list of
                   15183: item name and the result of running stat on the item.  If dirlist was requested
                   15184: for a file instead of a directory, the item name will be ''. For a directory 
                   15185: listing, if the item is a metadata file, the element will end &N&M 
                   15186: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   15187: default copyright set (1).  
                   15188: 
                   15189: =back
                   15190: 
                   15191: a scalar containing error condition (if encountered).
                   15192: 
                   15193: =over
                   15194: 
                   15195: =item 
                   15196: no_host (no homeserver identified for $username:$domain).
                   15197: 
                   15198: =item 
                   15199: no_such_host (server contacted for listing not identified as valid host).
                   15200: 
                   15201: =item 
                   15202: con_lost (connection to remote server failed).
                   15203: 
                   15204: =item 
                   15205: refused (invalid $username:$domain received on lond side).
                   15206: 
                   15207: =item 
                   15208: no_such_dir (directory at specified path on lond side does not exist). 
                   15209: 
                   15210: =item 
                   15211: empty (directory at specified path on lond side is empty).
                   15212: 
                   15213: =over
                   15214: 
                   15215: This is currently not encountered because the &ls3, &ls2, 
                   15216: &ls (_handler) routines on the lond side do not filter out
                   15217: . and .. from a directory listing. 
                   15218: 
                   15219: =back
                   15220: 
                   15221: =back
                   15222: 
                   15223: =back
1.191     harris41 15224: 
                   15225: =item *
                   15226: 
1.243     albertel 15227: spareserver() : find server with least workload from spare.tab
                   15228: 
1.986     foxr     15229: 
                   15230: =item *
                   15231: 
                   15232: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   15233: if there is no corresponding loncapa host.
                   15234: 
1.243     albertel 15235: =back
                   15236: 
1.986     foxr     15237: 
1.243     albertel 15238: =head2 Apache Request
                   15239: 
                   15240: =over 4
1.191     harris41 15241: 
                   15242: =item *
                   15243: 
1.243     albertel 15244: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   15245: localhost, posts hash
                   15246: 
                   15247: =back
                   15248: 
                   15249: =head2 Data to String to Data
                   15250: 
                   15251: =over 4
1.191     harris41 15252: 
                   15253: =item *
                   15254: 
1.243     albertel 15255: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   15256: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 15257: 
                   15258: =item *
                   15259: 
1.243     albertel 15260: hashref2str($hashref) : convert a hashref into a string complete with
                   15261: escaping and '=' and '&' separators, supports elements that are
                   15262: arrayrefs and hashrefs
1.191     harris41 15263: 
                   15264: =item *
                   15265: 
1.243     albertel 15266: arrayref2str($arrayref) : convert an arrayref into a string complete
                   15267: with escaping and '&' separators, supports elements that are arrayrefs
                   15268: and hashrefs
1.191     harris41 15269: 
                   15270: =item *
                   15271: 
1.243     albertel 15272: str2hash($string) : convert string to hash using unescaping and
                   15273: splitting on '=' and '&', supports elements that are arrayrefs and
                   15274: hashrefs
1.191     harris41 15275: 
                   15276: =item *
                   15277: 
1.243     albertel 15278: str2array($string) : convert string to hash using unescaping and
                   15279: splitting on '&', supports elements that are arrayrefs and hashrefs
                   15280: 
                   15281: =back
                   15282: 
                   15283: =head2 Logging Routines
                   15284: 
                   15285: 
                   15286: These routines allow one to make log messages in the lonnet.log and
                   15287: lonnet.perm logfiles.
1.191     harris41 15288: 
1.1119    foxr     15289: =over 4
                   15290: 
1.191     harris41 15291: =item *
                   15292: 
1.243     albertel 15293: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 15294: 
                   15295: =item *
                   15296: 
1.243     albertel 15297: logthis() : append message to the normal lonnet.log file, it gets
                   15298: preiodically rolled over and deleted.
1.191     harris41 15299: 
                   15300: =item *
                   15301: 
1.243     albertel 15302: logperm() : append a permanent message to lonnet.perm.log, this log
                   15303: file never gets deleted by any automated portion of the system, only
                   15304: messages of critical importance should go in here.
                   15305: 
1.1119    foxr     15306: 
1.243     albertel 15307: =back
                   15308: 
                   15309: =head2 General File Helper Routines
                   15310: 
                   15311: =over 4
1.191     harris41 15312: 
                   15313: =item *
                   15314: 
1.481     raeburn  15315: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   15316: (a) files in /uploaded
                   15317:   (i) If a local copy of the file exists - 
                   15318:       compares modification date of local copy with last-modified date for 
                   15319:       definitive version stored on home server for course. If local copy is 
                   15320:       stale, requests a new version from the home server and stores it. 
                   15321:       If the original has been removed from the home server, then local copy 
                   15322:       is unlinked.
                   15323:   (ii) If local copy does not exist -
                   15324:       requests the file from the home server and stores it. 
                   15325:   
                   15326:   If $caller is 'uploadrep':  
                   15327:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   15328:     for request for files originally uploaded via DOCS. 
                   15329:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   15330:   
                   15331:   Otherwise:
                   15332:      This indicates a call from the content generation phase of the request.
                   15333:      -  returns the entire contents of the file or -1.
                   15334:      
                   15335: (b) files in /res
                   15336:    - returns the entire contents of a file or -1; 
                   15337:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 15338: 
1.712     albertel 15339: 
                   15340: =item *
                   15341: 
                   15342: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   15343:                   reference
                   15344: 
                   15345: returns either a stat() list of data about the file or an empty list
                   15346: if the file doesn't exist or couldn't find out about it (connection
                   15347: problems or user unknown)
                   15348: 
1.191     harris41 15349: =item *
                   15350: 
1.243     albertel 15351: filelocation($dir,$file) : returns file system location of a file
                   15352: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   15353: directory that relative $file lookups are to looked in ($dir of /a/dir
                   15354: and a file of ../bob will become /a/bob)
1.191     harris41 15355: 
                   15356: =item *
                   15357: 
                   15358: hreflocation($dir,$file) : returns file system location or a URL; same as
                   15359: filelocation except for hrefs
                   15360: 
                   15361: =item *
                   15362: 
1.1172.2.49  raeburn  15363: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   15364: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 15365: 
1.243     albertel 15366: =back
                   15367: 
1.608     albertel 15368: =head2 Usererfile file routines (/uploaded*)
                   15369: 
                   15370: =over 4
                   15371: 
                   15372: =item *
                   15373: 
                   15374: userfileupload(): main rotine for putting a file in a user or course's
                   15375:                   filespace, arguments are,
                   15376: 
1.620     albertel 15377:  formname - required - this is the name of the element in $env where the
1.608     albertel 15378:            filename, and the contents of the file to create/modifed exist
1.620     albertel 15379:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   15380:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  15381:  context - if coursedoc, store the file in the course of the active role
                   15382:              of the current user; 
                   15383:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   15384:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 15385:  subdir - required - subdirectory to put the file in under ../userfiles/
                   15386:          if undefined, it will be placed in "unknown"
                   15387: 
                   15388:  (This routine calls clean_filename() to remove any dangerous
                   15389:  characters from the filename, and then calls finuserfileupload() to
                   15390:  complete the transaction)
                   15391: 
                   15392:  returns either the url of the uploaded file (/uploaded/....) if successful
                   15393:  and /adm/notfound.html if unsuccessful
                   15394: 
                   15395: =item *
                   15396: 
                   15397: clean_filename(): routine for cleaing a filename up for storage in
                   15398:                  userfile space, argument is:
                   15399: 
                   15400:  filename - proposed filename
                   15401: 
                   15402: returns: the new clean filename
                   15403: 
                   15404: =item *
                   15405: 
1.1090    raeburn  15406: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 15407: userspace, probably shouldn't be called directly
                   15408: 
                   15409:   docuname: username or courseid of destination for the file
                   15410:   docudom: domain of user/course of destination for the file
                   15411:   formname: same as for userfileupload()
1.1090    raeburn  15412:   fname: filename (including subdirectories) for the file
                   15413:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1172.2.109  raeburn  15414:           if hashref, and context is scantron, will convert csv format to standard format
1.1090    raeburn  15415:   allfiles: reference to hash used to store objects found by parser
                   15416:   codebase: reference to hash used for codebases of java objects found by parser
                   15417:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   15418:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   15419:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   15420:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   15421:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   15422:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  15423:   mimetype: reference to scalar to accommodate mime type determined
                   15424:             from File::MMagic if $parser = parse.
1.608     albertel 15425: 
                   15426:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  15427:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   15428:  was 'overwrite').
                   15429:  
1.608     albertel 15430: 
                   15431: =item *
                   15432: 
                   15433: renameuserfile(): renames an existing userfile to a new name
                   15434: 
                   15435:   Args:
                   15436:    docuname: username or courseid of destination for the file
                   15437:    docudom: domain of user/course of destination for the file
                   15438:    old: current file name (including any subdirs under userfiles)
                   15439:    new: desired file name (including any subdirs under userfiles)
                   15440: 
                   15441: =item *
                   15442: 
                   15443: mkdiruserfile(): creates a directory is a userfiles dir
                   15444: 
                   15445:   Args:
                   15446:    docuname: username or courseid of destination for the file
                   15447:    docudom: domain of user/course of destination for the file
                   15448:    dir: dir to create (including any subdirs under userfiles)
                   15449: 
                   15450: =item *
                   15451: 
                   15452: removeuserfile(): removes a file that exists in userfiles
                   15453: 
                   15454:   Args:
                   15455:    docuname: username or courseid of destination for the file
                   15456:    docudom: domain of user/course of destination for the file
                   15457:    fname: filname to delete (including any subdirs under userfiles)
                   15458: 
                   15459: =item *
                   15460: 
                   15461: removeuploadedurl(): convience function for removeuserfile()
                   15462: 
                   15463:   Args:
                   15464:    url:  a full /uploaded/... url to delete
                   15465: 
1.747     albertel 15466: =item * 
                   15467: 
                   15468: get_portfile_permissions():
                   15469:   Args:
                   15470:     domain: domain of user or course contain the portfolio files
                   15471:     user: name of user or num of course contain the portfolio files
                   15472:   Returns:
                   15473:     hashref of a dump of the proper file_permissions.db
                   15474:    
                   15475: 
                   15476: =item * 
                   15477: 
                   15478: get_access_controls():
                   15479: 
                   15480: Args:
                   15481:   current_permissions: the hash ref returned from get_portfile_permissions()
                   15482:   group: (optional) the group you want the files associated with
                   15483:   file: (optional) the file you want access info on
                   15484: 
                   15485: Returns:
1.749     raeburn  15486:     a hash (keys are file names) of hashes containing
                   15487:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   15488:         values are XML containing access control settings (see below) 
1.747     albertel 15489: 
                   15490: Internal notes:
                   15491: 
1.749     raeburn  15492:  access controls are stored in file_permissions.db as key=value pairs.
                   15493:     key -> path to file/file_name\0uniqueID:scope_end_start
                   15494:         where scope -> public,guest,course,group,domains or users.
                   15495:               end -> UNIX time for end of access (0 -> no end date)
                   15496:               start -> UNIX time for start of access
                   15497: 
                   15498:     value -> XML description of access control
                   15499:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   15500:             <start></start>
                   15501:             <end></end>
                   15502: 
                   15503:             <password></password>  for scope type = guest
                   15504: 
                   15505:             <domain></domain>     for scope type = course or group
                   15506:             <number></number>
                   15507:             <roles id="">
                   15508:              <role></role>
                   15509:              <access></access>
                   15510:              <section></section>
                   15511:              <group></group>
                   15512:             </roles>
                   15513: 
                   15514:             <dom></dom>         for scope type = domains
                   15515: 
                   15516:             <users>             for scope type = users
                   15517:              <user>
                   15518:               <uname></uname>
                   15519:               <udom></udom>
                   15520:              </user>
                   15521:             </users>
                   15522:            </scope> 
                   15523:               
                   15524:  Access data is also aggregated for each file in an additional key=value pair:
                   15525:  key -> path to file/file_name\0accesscontrol 
                   15526:  value -> reference to hash
                   15527:           hash contains key = value pairs
                   15528:           where key = uniqueID:scope_end_start
                   15529:                 value = UNIX time record was last updated
                   15530: 
                   15531:           Used to improve speed of look-ups of access controls for each file.  
                   15532:  
                   15533:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   15534: 
1.1172.2.13  raeburn  15535: =item *
                   15536: 
1.749     raeburn  15537: modify_access_controls():
                   15538: 
                   15539: Modifies access controls for a portfolio file
                   15540: Args
                   15541: 1. file name
                   15542: 2. reference to hash of required changes,
                   15543: 3. domain
                   15544: 4. username
                   15545:   where domain,username are the domain of the portfolio owner 
                   15546:   (either a user or a course) 
                   15547: 
                   15548: Returns:
                   15549: 1. result of additions or updates ('ok' or 'error', with error message). 
                   15550: 2. result of deletions ('ok' or 'error', with error message).
                   15551: 3. reference to hash of any new or updated access controls.
                   15552: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   15553:    key = integer (inbound ID)
1.1172.2.13  raeburn  15554:    value = uniqueID
                   15555: 
                   15556: =item *
                   15557: 
                   15558: get_timebased_id():
                   15559: 
                   15560: Attempts to get a unique timestamp-based suffix for use with items added to a
                   15561: course via the Course Editor (e.g., folders, composite pages,
                   15562: group bulletin boards).
                   15563: 
                   15564: Args: (first three required; six others optional)
                   15565: 
                   15566: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   15567:    docssequence, or name of group
                   15568: 
                   15569: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   15570:    e.g., num, boardids
                   15571: 
                   15572: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   15573:    file will be named nohist_namespace.db
                   15574: 
                   15575: 4. cdom: domain of course; default is current course domain from %env
                   15576: 
                   15577: 5. cnum: course number; default is current course number from %env
                   15578: 
                   15579: 6. idtype: set to concat if an additional digit is to be appended to the
                   15580:    unix timestamp to form the suffix, if the plain timestamp is already
                   15581:    in use.  Default is to not do this, but simply increment the unix
                   15582:    timestamp by 1 until a unique key is obtained.
                   15583: 
                   15584: 7. who: holder of locking key; defaults to user:domain for user.
                   15585: 
                   15586: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   15587:    retrying); default is 3.
                   15588: 
                   15589: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   15590: 
                   15591: Returns:
                   15592: 
                   15593: 1. suffix obtained (numeric)
                   15594: 
                   15595: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   15596: 
                   15597: 3. error: contains (localized) error message if an error occurred.
                   15598: 
1.747     albertel 15599: 
1.608     albertel 15600: =back
                   15601: 
1.243     albertel 15602: =head2 HTTP Helper Routines
                   15603: 
                   15604: =over 4
                   15605: 
1.191     harris41 15606: =item *
                   15607: 
                   15608: escape() : unpack non-word characters into CGI-compatible hex codes
                   15609: 
                   15610: =item *
                   15611: 
                   15612: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   15613: 
1.243     albertel 15614: =back
                   15615: 
                   15616: =head1 PRIVATE SUBROUTINES
                   15617: 
                   15618: =head2 Underlying communication routines (Shouldn't call)
                   15619: 
                   15620: =over 4
                   15621: 
                   15622: =item *
                   15623: 
                   15624: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   15625: 
                   15626: =item *
                   15627: 
                   15628: reply() : uses subreply to send a message to remote machine, logs all failures
                   15629: 
                   15630: =item *
                   15631: 
                   15632: critical() : passes a critical message to another server; if cannot
                   15633: get through then place message in connection buffer directory and
                   15634: returns con_delayed, if incapable of saving message, returns
                   15635: con_failed
                   15636: 
                   15637: =item *
                   15638: 
                   15639: reconlonc() : tries to reconnect lonc client processes.
                   15640: 
                   15641: =back
                   15642: 
                   15643: =head2 Resource Access Logging
                   15644: 
                   15645: =over 4
                   15646: 
                   15647: =item *
                   15648: 
                   15649: flushcourselogs() : flush (save) buffer logs and access logs
                   15650: 
                   15651: =item *
                   15652: 
                   15653: courselog($what) : save message for course in hash
                   15654: 
                   15655: =item *
                   15656: 
                   15657: courseacclog($what) : save message for course using &courselog().  Perform
                   15658: special processing for specific resource types (problems, exams, quizzes, etc).
                   15659: 
1.191     harris41 15660: =item *
                   15661: 
                   15662: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   15663: as a PerlChildExitHandler
1.243     albertel 15664: 
                   15665: =back
                   15666: 
                   15667: =head2 Other
                   15668: 
                   15669: =over 4
                   15670: 
                   15671: =item *
                   15672: 
                   15673: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 15674: 
                   15675: =back
                   15676: 
                   15677: =cut
1.877     foxr     15678: 

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