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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.48! raeburn     4: # $Id: lonnet.pm,v 1.1172.2.47 2014/05/05 11:53:37 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.8       www        74: use LWP::UserAgent();
1.486     www        75: use HTTP::Date;
1.977     amueller   76: use Image::Magick;
                     77: 
1.1172.2.36  raeburn    78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138    raeburn    79:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
                     80:             %managerstab);
1.871     albertel   81: 
                     82: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     83:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     84:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        85:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        86: 
1.1       albertel   87: use IO::Socket;
1.31      www        88: use GDBM_File;
1.208     albertel   89: use HTML::LCParser;
1.88      www        90: use Fcntl qw(:flock);
1.870     albertel   91: use Storable qw(thaw nfreeze);
1.539     albertel   92: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   93: use Cache::Memcached;
1.676     albertel   94: use Digest::MD5;
1.790     albertel   95: use Math::Random;
1.1024    raeburn    96: use File::MMagic;
1.807     albertel   97: use LONCAPA qw(:DEFAULT :match);
1.740     www        98: use LONCAPA::Configuration;
1.1160    www        99: use LONCAPA::lonmetadata;
1.1172.2.22  raeburn   100: use LONCAPA::Lond;
1.1117    foxr      101: 
1.1090    raeburn   102: use File::Copy;
1.676     albertel  103: 
1.195     www       104: my $readit;
1.550     foxr      105: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel  106: 
1.619     albertel  107: require Exporter;
                    108: 
                    109: our @ISA = qw (Exporter);
                    110: our @EXPORT = qw(%env);
                    111: 
1.1172.2.9  raeburn   112: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729     www       113: {
                    114:     my $logid;
1.1172.2.9  raeburn   115:     sub write_log {
                    116: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    117:         if ($context eq 'course') {
                    118:             if (($cnum eq '') || ($cdom eq '')) {
                    119:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    120:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    121:             }
1.957     raeburn   122:         }
1.1172.2.13  raeburn   123: 	$logid ++;
1.957     raeburn   124:         my $now = time();
                    125: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.1172.2.9  raeburn   126:         my $logentry = {
                    127:                          $id => {
                    128:                                   'exe_uname' => $env{'user.name'},
                    129:                                   'exe_udom'  => $env{'user.domain'},
                    130:                                   'exe_time'  => $now,
                    131:                                   'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    132:                                   'delflag'   => $delflag,
                    133:                                   'logentry'  => $storehash,
                    134:                                   'uname'     => $uname,
                    135:                                   'udom'      => $udom,
                    136:                                 }
                    137:                        };
                    138:         return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729     www       139:     }
                    140: }
1.1       albertel  141: 
1.163     harris41  142: sub logtouch {
                    143:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  144:     unless (-e "$execdir/logs/lonnet.log") {	
                    145: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  146: 	close $fh;
                    147:     }
                    148:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    149:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    150: }
                    151: 
1.1       albertel  152: sub logthis {
                    153:     my $message=shift;
                    154:     my $execdir=$perlvar{'lonDaemons'};
                    155:     my $now=time;
                    156:     my $local=localtime($now);
1.448     albertel  157:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986     foxr      158: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    159: 	print $fh $logstring;
1.448     albertel  160: 	close($fh);
                    161:     }
1.1       albertel  162:     return 1;
                    163: }
                    164: 
                    165: sub logperm {
                    166:     my $message=shift;
                    167:     my $execdir=$perlvar{'lonDaemons'};
                    168:     my $now=time;
                    169:     my $local=localtime($now);
1.448     albertel  170:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    171: 	print $fh "$now:$message:$local\n";
                    172: 	close($fh);
                    173:     }
1.1       albertel  174:     return 1;
                    175: }
                    176: 
1.850     albertel  177: sub create_connection {
1.853     albertel  178:     my ($hostname,$lonid) = @_;
1.851     albertel  179:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  180: 				     Type    => SOCK_STREAM,
                    181: 				     Timeout => 10);
                    182:     return 0 if (!$client);
1.890     albertel  183:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  184:     my $result = <$client>;
                    185:     chomp($result);
                    186:     return 1 if ($result eq 'done');
                    187:     return 0;
                    188: }
                    189: 
1.983     raeburn   190: sub get_server_timezone {
                    191:     my ($cnum,$cdom) = @_;
                    192:     my $home=&homeserver($cnum,$cdom);
                    193:     if ($home ne 'no_host') {
                    194:         my $cachetime = 24*3600;
                    195:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    196:         if (defined($cached)) {
                    197:             return $timezone;
                    198:         } else {
                    199:             my $timezone = &reply('servertimezone',$home);
                    200:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    201:         }
                    202:     }
                    203: }
1.850     albertel  204: 
1.1106    raeburn   205: sub get_server_distarch {
                    206:     my ($lonhost,$ignore_cache) = @_;
                    207:     if (defined($lonhost)) {
                    208:         if (!defined(&hostname($lonhost))) {
                    209:             return;
                    210:         }
                    211:         my $cachetime = 12*3600;
                    212:         if (!$ignore_cache) {
                    213:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    214:             if (defined($cached)) {
                    215:                 return $distarch;
                    216:             }
                    217:         }
                    218:         my $rep = &reply('serverdistarch',$lonhost);
                    219:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    220:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    221:                 $rep eq '') {
                    222:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    223:         }
                    224:     }
                    225:     return;
                    226: }
                    227: 
1.993     raeburn   228: sub get_server_loncaparev {
1.1073    raeburn   229:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   230:     if (defined($lonhost)) {
                    231:         if (!defined(&hostname($lonhost))) {
                    232:             undef($lonhost);
                    233:         }
                    234:     }
                    235:     if (!defined($lonhost)) {
                    236:         if (defined(&domain($dom,'primary'))) {
                    237:             $lonhost=&domain($dom,'primary');
                    238:             if ($lonhost eq 'no_host') {
                    239:                 undef($lonhost);
                    240:             }
                    241:         }
                    242:     }
                    243:     if (defined($lonhost)) {
1.1073    raeburn   244:         my $cachetime = 12*3600;
                    245:         if (!$ignore_cache) {
                    246:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    247:             if (defined($cached)) {
                    248:                 return $loncaparev;
                    249:             }
                    250:         }
                    251:         my ($answer,$loncaparev);
                    252:         my @ids=&current_machine_ids();
                    253:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    254:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   255:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   256:                 $loncaparev = $1;
                    257:             }
                    258:         } else {
                    259:             $answer = &reply('serverloncaparev',$lonhost);
                    260:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    261:                 if ($caller eq 'loncron') {
                    262:                     my $ua=new LWP::UserAgent;
1.1082    raeburn   263:                     $ua->timeout(4);
1.1073    raeburn   264:                     my $protocol = $protocol{$lonhost};
                    265:                     $protocol = 'http' if ($protocol ne 'https');
                    266:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
                    267:                     my $request=new HTTP::Request('GET',$url);
                    268:                     my $response=$ua->request($request);
                    269:                     unless ($response->is_error()) {
                    270:                         my $content = $response->content;
1.1081    raeburn   271:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   272:                             $loncaparev = $1;
                    273:                         }
                    274:                     }
                    275:                 } else {
                    276:                     $loncaparev = $loncaparevs{$lonhost};
                    277:                 }
1.1081    raeburn   278:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   279:                 $loncaparev = $1;
                    280:             }
1.993     raeburn   281:         }
1.1073    raeburn   282:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   283:     }
                    284: }
                    285: 
1.1074    raeburn   286: sub get_server_homeID {
                    287:     my ($hostname,$ignore_cache,$caller) = @_;
                    288:     unless ($ignore_cache) {
                    289:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    290:         if (defined($cached)) {
                    291:             return $serverhomeID;
                    292:         }
                    293:     }
                    294:     my $cachetime = 12*3600;
                    295:     my $serverhomeID;
                    296:     if ($caller eq 'loncron') { 
                    297:         my @machine_ids = &machine_ids($hostname);
                    298:         foreach my $id (@machine_ids) {
                    299:             my $response = &reply('serverhomeID',$id);
                    300:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    301:                 $serverhomeID = $response;
                    302:                 last;
                    303:             }
                    304:         }
                    305:         if ($serverhomeID eq '') {
                    306:             $serverhomeID = $machine_ids[-1];
                    307:         }
                    308:     } else {
                    309:         $serverhomeID = $serverhomeIDs{$hostname};
                    310:     }
                    311:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    312: }
                    313: 
1.1121    raeburn   314: sub get_remote_globals {
                    315:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   316:     my ($result,%returnhash,%whatneeded);
                    317:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   318:         foreach my $what (sort(keys(%{$whathash}))) {
                    319:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   320:             my ($response,$cached);
1.1121    raeburn   321:             unless ($ignore_cache) {
1.1125    raeburn   322:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   323:             }
                    324:             if (defined($cached)) {
1.1125    raeburn   325:                 $returnhash{$what} = $response;
1.1121    raeburn   326:             } else {
1.1125    raeburn   327:                 $whatneeded{$what} = 1;
1.1121    raeburn   328:             }
                    329:         }
1.1125    raeburn   330:         if (keys(%whatneeded) == 0) {
                    331:             $result = 'ok';
                    332:         } else {
1.1121    raeburn   333:             my $requested = &freeze_escape(\%whatneeded);
                    334:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   335:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    336:                 ($rep eq 'unknown_cmd')) {
                    337:                 $result = $rep;
                    338:             } else {
                    339:                 $result = 'ok';
1.1121    raeburn   340:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   341:                 foreach my $item (@pairs) {
                    342:                     my ($key,$value)=split(/=/,$item,2);
                    343:                     my $what = &unescape($key);
                    344:                     my $hashid = $lonhost.'-'.$what;
                    345:                     $returnhash{$what}=&thaw_unescape($value);
                    346:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   347:                 }
                    348:             }
                    349:         }
                    350:     }
1.1125    raeburn   351:     return ($result,\%returnhash);
1.1121    raeburn   352: }
                    353: 
1.1124    raeburn   354: sub remote_devalidate_cache {
1.1172.2.35  raeburn   355:     my ($lonhost,$cachekeys) = @_;
                    356:     my $items;
                    357:     return unless (ref($cachekeys) eq 'ARRAY');
                    358:     my $cachestr = join('&',@{$cachekeys});
                    359:     return &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124    raeburn   360: }
                    361: 
1.1       albertel  362: # -------------------------------------------------- Non-critical communication
                    363: sub subreply {
                    364:     my ($cmd,$server)=@_;
1.838     albertel  365:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      366:     #
                    367:     #  With loncnew process trimming, there's a timing hole between lonc server
                    368:     #  process exit and the master server picking up the listen on the AF_UNIX
                    369:     #  socket.  In that time interval, a lock file will exist:
                    370: 
                    371:     my $lockfile=$peerfile.".lock";
                    372:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    373: 	sleep(1);
                    374:     }
                    375:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      376:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      377:     #
1.550     foxr      378:     #   We'll give the connection a few tries before abandoning it.  If
                    379:     #   connection is not possible, we'll con_lost back to the client.
                    380:     #   
                    381:     my $client;
                    382:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    383: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    384: 				      Type    => SOCK_STREAM,
                    385: 				      Timeout => 10);
1.869     albertel  386: 	if ($client) {
1.550     foxr      387: 	    last;		# Connected!
1.850     albertel  388: 	} else {
1.853     albertel  389: 	    &create_connection(&hostname($server),$server);
1.550     foxr      390: 	}
1.850     albertel  391:         sleep(1);		# Try again later if failed connection.
1.550     foxr      392:     }
                    393:     my $answer;
                    394:     if ($client) {
1.704     albertel  395: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      396: 	$answer=<$client>;
                    397: 	if (!$answer) { $answer="con_lost"; }
                    398: 	chomp($answer);
                    399:     } else {
                    400: 	$answer = 'con_lost';	# Failed connection.
                    401:     }
1.1       albertel  402:     return $answer;
                    403: }
                    404: 
                    405: sub reply {
                    406:     my ($cmd,$server)=@_;
1.838     albertel  407:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  408:     my $answer=subreply($cmd,$server);
1.65      www       409:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  410:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       411:                 " $cmd to $server returned $answer</font>");
                    412:     }
1.1       albertel  413:     return $answer;
                    414: }
                    415: 
                    416: # ----------------------------------------------------------- Send USR1 to lonc
                    417: 
                    418: sub reconlonc {
1.891     albertel  419:     my ($lonid) = @_;
                    420:     my $hostname = &hostname($lonid);
                    421:     if ($lonid) {
                    422: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    423: 	if ($hostname && -e $peerfile) {
                    424: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    425: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    426: 					     Type    => SOCK_STREAM,
                    427: 					     Timeout => 10);
                    428: 	    if ($client) {
                    429: 		print $client ("reset_retries\n");
                    430: 		my $answer=<$client>;
                    431: 		#reset just this one.
                    432: 	    }
                    433: 	}
                    434: 	return;
                    435:     }
                    436: 
1.836     www       437:     &logthis("Trying to reconnect lonc");
1.1       albertel  438:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  439:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  440: 	my $loncpid=<$fh>;
                    441:         chomp($loncpid);
                    442:         if (kill 0 => $loncpid) {
                    443: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    444:             kill USR1 => $loncpid;
                    445:             sleep 1;
1.836     www       446:          } else {
1.12      www       447: 	    &logthis(
1.672     albertel  448:                "<font color=\"blue\">WARNING:".
1.12      www       449:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  450:         }
                    451:     } else {
1.836     www       452: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  453:     }
                    454: }
                    455: 
                    456: # ------------------------------------------------------ Critical communication
1.12      www       457: 
1.1       albertel  458: sub critical {
                    459:     my ($cmd,$server)=@_;
1.838     albertel  460:     unless (&hostname($server)) {
1.672     albertel  461:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       462:                " Critical message to unknown server ($server)</font>");
                    463:         return 'no_such_host';
                    464:     }
1.1       albertel  465:     my $answer=reply($cmd,$server);
                    466:     if ($answer eq 'con_lost') {
                    467: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  468: 	my $answer=reply($cmd,$server);
1.1       albertel  469:         if ($answer eq 'con_lost') {
                    470:             my $now=time;
                    471:             my $middlename=$cmd;
1.5       www       472:             $middlename=substr($middlename,0,16);
1.1       albertel  473:             $middlename=~s/\W//g;
                    474:             my $dfilename=
1.305     www       475:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    476:             $dumpcount++;
1.1       albertel  477:             {
1.448     albertel  478: 		my $dfh;
                    479: 		if (open($dfh,">$dfilename")) {
                    480: 		    print $dfh "$cmd\n"; 
                    481: 		    close($dfh);
                    482: 		}
1.1       albertel  483:             }
                    484:             sleep 2;
                    485:             my $wcmd='';
                    486:             {
1.448     albertel  487: 		my $dfh;
                    488: 		if (open($dfh,"<$dfilename")) {
                    489: 		    $wcmd=<$dfh>; 
                    490: 		    close($dfh);
                    491: 		}
1.1       albertel  492:             }
                    493:             chomp($wcmd);
1.7       www       494:             if ($wcmd eq $cmd) {
1.672     albertel  495: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       496:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  497:                 &logperm("D:$server:$cmd");
                    498: 	        return 'con_delayed';
                    499:             } else {
1.672     albertel  500:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       501:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  502:                 &logperm("F:$server:$cmd");
                    503:                 return 'con_failed';
                    504:             }
                    505:         }
                    506:     }
                    507:     return $answer;
1.405     albertel  508: }
                    509: 
1.755     albertel  510: # ------------------------------------------- check if return value is an error
                    511: 
                    512: sub error {
                    513:     my ($result) = @_;
1.756     albertel  514:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  515: 	if ($2 == 2) { return undef; }
                    516: 	return $1;
                    517:     }
                    518:     return undef;
                    519: }
                    520: 
1.783     albertel  521: sub convert_and_load_session_env {
                    522:     my ($lonidsdir,$handle)=@_;
                    523:     my @profile;
                    524:     {
1.917     albertel  525: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    526: 	if (!$opened) {
1.915     albertel  527: 	    return 0;
                    528: 	}
1.783     albertel  529: 	flock($idf,LOCK_SH);
                    530: 	@profile=<$idf>;
                    531: 	close($idf);
                    532:     }
                    533:     my %temp_env;
                    534:     foreach my $line (@profile) {
1.786     albertel  535: 	if ($line !~ m/=/) {
                    536: 	    return 0;
                    537: 	}
1.783     albertel  538: 	chomp($line);
                    539: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    540: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    541:     }
                    542:     unlink("$lonidsdir/$handle.id");
                    543:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    544: 	    0640)) {
                    545: 	%disk_env = %temp_env;
                    546: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    547: 	untie(%disk_env);
                    548:     }
1.786     albertel  549:     return 1;
1.783     albertel  550: }
                    551: 
1.374     www       552: # ------------------------------------------- Transfer profile into environment
1.780     albertel  553: my $env_loaded;
                    554: sub transfer_profile_to_env {
1.788     albertel  555:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    556:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       557: 
1.720     albertel  558:     if (!defined($lonidsdir)) {
                    559: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    560:     }
                    561:     if (!defined($handle)) {
                    562:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    563:     }
                    564: 
1.786     albertel  565:     my $convert;
                    566:     {
1.917     albertel  567:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    568: 	if (!$opened) {
1.915     albertel  569: 	    return;
                    570: 	}
1.786     albertel  571: 	flock($idf,LOCK_SH);
                    572: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    573: 		&GDBM_READER(),0640)) {
                    574: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    575: 	    untie(%disk_env);
                    576: 	} else {
                    577: 	    $convert = 1;
                    578: 	}
                    579:     }
                    580:     if ($convert) {
                    581: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    582: 	    &logthis("Failed to load session, or convert session.");
                    583: 	}
1.374     www       584:     }
1.783     albertel  585: 
1.786     albertel  586:     my %remove;
1.783     albertel  587:     while ( my $envname = each(%env) ) {
1.433     matthew   588:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    589:             if ($time < time-300) {
1.783     albertel  590:                 $remove{$key}++;
1.433     matthew   591:             }
                    592:         }
                    593:     }
1.783     albertel  594: 
1.619     albertel  595:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  596:     $env_loaded=1;
1.783     albertel  597:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   598:         &delenv($expired_key);
1.374     www       599:     }
1.1       albertel  600: }
                    601: 
1.916     albertel  602: # ---------------------------------------------------- Check for valid session 
                    603: sub check_for_valid_session {
1.1172.2.36  raeburn   604:     my ($r,$name,$userhashref) = @_;
1.916     albertel  605:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155    raeburn   606:     if ($name eq '') {
                    607:         $name = 'lonID';
                    608:     }
                    609:     my $lonid=$cookies{$name};
1.916     albertel  610:     return undef if (!$lonid);
                    611: 
                    612:     my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155    raeburn   613:     my $lonidsdir;
                    614:     if ($name eq 'lonDAV') {
                    615:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    616:     } else {
                    617:         $lonidsdir=$r->dir_config('lonIDsDir');
                    618:     }
1.916     albertel  619:     return undef if (!-e "$lonidsdir/$handle.id");
                    620: 
1.917     albertel  621:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    622:     return undef if (!$opened);
1.916     albertel  623: 
                    624:     flock($idf,LOCK_SH);
                    625:     my %disk_env;
                    626:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    627: 	    &GDBM_READER(),0640)) {
                    628: 	return undef;	
                    629:     }
                    630: 
                    631:     if (!defined($disk_env{'user.name'})
                    632: 	|| !defined($disk_env{'user.domain'})) {
                    633: 	return undef;
                    634:     }
1.1172.2.18  raeburn   635: 
1.1172.2.36  raeburn   636:     if (ref($userhashref) eq 'HASH') {
                    637:         $userhashref->{'name'} = $disk_env{'user.name'};
                    638:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1172.2.18  raeburn   639:     }
                    640: 
1.916     albertel  641:     return $handle;
                    642: }
                    643: 
1.830     albertel  644: sub timed_flock {
                    645:     my ($file,$lock_type) = @_;
                    646:     my $failed=0;
                    647:     eval {
                    648: 	local $SIG{__DIE__}='DEFAULT';
                    649: 	local $SIG{ALRM}=sub {
                    650: 	    $failed=1;
                    651: 	    die("failed lock");
                    652: 	};
                    653: 	alarm(13);
                    654: 	flock($file,$lock_type);
                    655: 	alarm(0);
                    656:     };
                    657:     if ($failed) {
                    658: 	return undef;
                    659:     } else {
                    660: 	return 1;
                    661:     }
                    662: }
                    663: 
1.5       www       664: # ---------------------------------------------------------- Append Environment
                    665: 
                    666: sub appenv {
1.949     raeburn   667:     my ($newenv,$roles) = @_;
                    668:     if (ref($newenv) eq 'HASH') {
                    669:         foreach my $key (keys(%{$newenv})) {
                    670:             my $refused = 0;
                    671: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    672:                 $refused = 1;
                    673:                 if (ref($roles) eq 'ARRAY') {
1.1172.2.40  raeburn   674:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   675:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    676:                         $refused = 0;
                    677:                     }
                    678:                 }
                    679:             }
                    680:             if ($refused) {
                    681:                 &logthis("<font color=\"blue\">WARNING: ".
                    682:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    683:                          .'</font>');
                    684: 	        delete($newenv->{$key});
                    685:             } else {
                    686:                 $env{$key}=$newenv->{$key};
                    687:             }
                    688:         }
                    689:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    690:         if ($opened
                    691: 	    && &timed_flock($env_file,LOCK_EX)
                    692: 	    &&
                    693: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    694: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    695: 	    while (my ($key,$value) = each(%{$newenv})) {
                    696: 	        $disk_env{$key} = $value;
                    697: 	    }
                    698: 	    untie(%disk_env);
1.35      www       699:         }
1.191     harris41  700:     }
1.56      www       701:     return 'ok';
                    702: }
                    703: # ----------------------------------------------------- Delete from Environment
                    704: 
                    705: sub delenv {
1.1104    raeburn   706:     my ($delthis,$regexp,$roles) = @_;
                    707:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    708:         my $refused = 1;
                    709:         if (ref($roles) eq 'ARRAY') {
                    710:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    711:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    712:                 $refused = 0;
                    713:             }
                    714:         }
                    715:         if ($refused) {
                    716:             &logthis("<font color=\"blue\">WARNING: ".
                    717:                      "Attempt to delete from environment ".$delthis);
                    718:             return 'error';
                    719:         }
1.56      www       720:     }
1.917     albertel  721:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    722:     if ($opened
1.915     albertel  723: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  724: 	&&
                    725: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    726: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  727: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   728: 	    if ($regexp) {
                    729:                 if ($key=~/^$delthis/) {
                    730:                     delete($env{$key});
                    731:                     delete($disk_env{$key});
                    732:                 } 
                    733:             } else {
                    734:                 if ($key=~/^\Q$delthis\E/) {
                    735: 		    delete($env{$key});
                    736: 		    delete($disk_env{$key});
                    737: 	        }
                    738:             }
1.448     albertel  739: 	}
1.783     albertel  740: 	untie(%disk_env);
1.5       www       741:     }
                    742:     return 'ok';
1.369     albertel  743: }
                    744: 
1.790     albertel  745: sub get_env_multiple {
                    746:     my ($name) = @_;
                    747:     my @values;
                    748:     if (defined($env{$name})) {
                    749:         # exists is it an array
                    750:         if (ref($env{$name})) {
                    751:             @values=@{ $env{$name} };
                    752:         } else {
                    753:             $values[0]=$env{$name};
                    754:         }
                    755:     }
                    756:     return(@values);
                    757: }
                    758: 
1.958     www       759: # ------------------------------------------------------------------- Locking
                    760: 
                    761: sub set_lock {
                    762:     my ($text)=@_;
                    763:     $locknum++;
                    764:     my $id=$$.'-'.$locknum;
                    765:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    766:              'session.lock.'.$id => $text});
                    767:     return $id;
                    768: }
                    769: 
                    770: sub get_locks {
                    771:     my $num=0;
                    772:     my %texts=();
                    773:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    774:        if ($lock=~/\w/) {
                    775:           $num++;
                    776:           $texts{$lock}=$env{'session.lock.'.$lock};
                    777:        }
                    778:    }
                    779:    return ($num,%texts);
                    780: }
                    781: 
                    782: sub remove_lock {
                    783:     my ($id)=@_;
                    784:     my $newlocks='';
                    785:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    786:        if (($lock=~/\w/) && ($lock ne $id)) {
                    787:           $newlocks.=','.$lock;
                    788:        }
                    789:     }
                    790:     &appenv({'session.locks' => $newlocks});
                    791:     &delenv('session.lock.'.$id);
                    792: }
                    793: 
                    794: sub remove_all_locks {
                    795:     my $activelocks=$env{'session.locks'};
                    796:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    797:        if ($lock=~/\w/) {
                    798:           &remove_lock($lock);
                    799:        }
                    800:     }
                    801: }
                    802: 
                    803: 
1.369     albertel  804: # ------------------------------------------ Find out current server userload
                    805: sub userload {
                    806:     my $numusers=0;
                    807:     {
                    808: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    809: 	my $filename;
                    810: 	my $curtime=time;
                    811: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  812: 	    next if ($filename eq '.' || $filename eq '..');
                    813: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  814: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  815: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  816: 	}
                    817: 	closedir(LONIDS);
                    818:     }
                    819:     my $userloadpercent=0;
                    820:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    821:     if ($maxuserload) {
1.371     albertel  822: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  823:     }
1.372     albertel  824:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  825:     return $userloadpercent;
1.283     www       826: }
                    827: 
1.1       albertel  828: # ------------------------------ Find server with least workload from spare.tab
1.11      www       829: 
1.1       albertel  830: sub spareserver {
1.1083    raeburn   831:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  832:     my $spare_server;
1.370     albertel  833:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  834:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    835:                                                      :  $userloadpercent;
1.1083    raeburn   836:     my ($uint_dom,$remotesessions);
                    837:     if (($udom ne '') && (&domain($udom) ne '')) {
                    838:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    839:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    840:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    841:         $remotesessions = $udomdefaults{'remotesessions'};
                    842:     }
1.1123    raeburn   843:     my $spareshash = &this_host_spares($udom);
                    844:     if (ref($spareshash) eq 'HASH') {
                    845:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    846:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    847:                 if ($uint_dom) {
                    848:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    849:                                                  $try_server));
                    850:                 }
                    851: 	        ($spare_server, $lowest_load) =
                    852: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    853:             }
1.1083    raeburn   854:         }
1.784     albertel  855: 
1.1123    raeburn   856:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    857: 
                    858:         if (!$found_server) {
                    859:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    860: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
                    861:                     if ($uint_dom) {
                    862:                         next unless (&spare_can_host($udom,$uint_dom,
                    863:                                                      $remotesessions,$try_server));
                    864:                     }
                    865: 	            ($spare_server, $lowest_load) =
                    866: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    867:                 }
                    868: 	    }
                    869:         }
1.784     albertel  870:     }
                    871: 
                    872:     if (!$want_server_name) {
1.968     raeburn   873:         my $protocol = 'http';
                    874:         if ($protocol{$spare_server} eq 'https') {
                    875:             $protocol = $protocol{$spare_server};
                    876:         }
1.1001    raeburn   877:         if (defined($spare_server)) {
                    878:             my $hostname = &hostname($spare_server);
1.1083    raeburn   879:             if (defined($hostname)) {
1.1001    raeburn   880: 	        $spare_server = $protocol.'://'.$hostname;
                    881:             }
                    882:         }
1.784     albertel  883:     }
                    884:     return $spare_server;
                    885: }
                    886: 
                    887: sub compare_server_load {
1.1172.2.41  raeburn   888:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                    889: 
                    890:     if ($required) {
                    891:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                    892:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                    893:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                    894:         if (($major eq '' && $minor eq '') ||
                    895:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                    896:             return ($spare_server,$lowest_load);
                    897:         }
                    898:     }
1.784     albertel  899: 
                    900:     my $loadans     = &reply('load',    $try_server);
                    901:     my $userloadans = &reply('userload',$try_server);
                    902: 
                    903:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   904: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  905:     }
                    906: 
                    907:     my $load;
                    908:     if ($loadans =~ /\d/) {
                    909: 	if ($userloadans =~ /\d/) {
                    910: 	    #both are numbers, pick the bigger one
                    911: 	    $load = ($loadans > $userloadans) ? $loadans 
                    912: 		                              : $userloadans;
1.411     albertel  913: 	} else {
1.784     albertel  914: 	    $load = $loadans;
1.411     albertel  915: 	}
1.784     albertel  916:     } else {
                    917: 	$load = $userloadans;
                    918:     }
                    919: 
                    920:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    921: 	$spare_server = $try_server;
                    922: 	$lowest_load  = $load;
1.370     albertel  923:     }
1.784     albertel  924:     return ($spare_server,$lowest_load);
1.202     matthew   925: }
1.914     albertel  926: 
                    927: # --------------------------- ask offload servers if user already has a session
                    928: sub find_existing_session {
                    929:     my ($udom,$uname) = @_;
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'} }) {
                    934:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    935:             }
                    936:         }
                    937:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                    938:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                    939:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    940:             }
                    941:         }
1.914     albertel  942:     }
                    943:     return;
                    944: }
                    945: 
                    946: # -------------------------------- ask if server already has a session for user
                    947: sub has_user_session {
                    948:     my ($lonid,$udom,$uname) = @_;
                    949:     my $result = &reply(join(':','userhassession',
                    950: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    951:     return 1 if ($result eq 'ok');
                    952: 
                    953:     return 0;
                    954: }
                    955: 
1.1076    raeburn   956: # --------- determine least loaded server in a user's domain which allows login
                    957: 
                    958: sub choose_server {
1.1172.2.47  raeburn   959:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn   960:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn   961:     my %servers = &get_servers($udom);
1.1076    raeburn   962:     my $lowest_load = 30000;
1.1172.2.47  raeburn   963:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                    964:     if ($skiploadbal) {
                    965:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                    966:         unless (defined($cached)) {
                    967:             my $cachetime = 60*60*24;
                    968:             my %domconfig =
                    969:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                    970:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                    971:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                    972:                                            $cachetime);
                    973:             }
                    974:         }
                    975:     }
1.1076    raeburn   976:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn   977:         my $loginvia;
1.1172.2.47  raeburn   978:         if ($skiploadbal) {
                    979:             if (ref($balancers) eq 'HASH') {
                    980:                 next if (exists($balancers->{$lonhost}));
                    981:             }
                    982:         }
1.1115    raeburn   983:         if ($checkloginvia) {
                    984:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn   985:             if ($loginvia) {
                    986:                 my ($server,$path) = split(/:/,$loginvia);
                    987:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn   988:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn   989:                 if ($login_host eq $server) {
                    990:                     $portal_path = $path;
1.1151    raeburn   991:                     $isredirect = 1;
1.1116    raeburn   992:                 }
                    993:             } else {
                    994:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn   995:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn   996:                 if ($login_host eq $lonhost) {
                    997:                     $portal_path = '';
1.1151    raeburn   998:                     $isredirect = ''; 
1.1116    raeburn   999:                 }
                   1000:             }
                   1001:         } else {
1.1076    raeburn  1002:             ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1003:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1004:         }
                   1005:     }
                   1006:     if ($login_host ne '') {
1.1116    raeburn  1007:         $hostname = &hostname($login_host);
1.1076    raeburn  1008:     }
1.1151    raeburn  1009:     return ($login_host,$hostname,$portal_path,$isredirect);
1.1076    raeburn  1010: }
                   1011: 
1.202     matthew  1012: # --------------------------------------------- Try to change a user's password
                   1013: 
                   1014: sub changepass {
1.799     raeburn  1015:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1016:     $currentpass = &escape($currentpass);
                   1017:     $newpass     = &escape($newpass);
1.1030    raeburn  1018:     my $lonhost = $perlvar{'lonHostID'};
                   1019:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1020: 		       $server);
                   1021:     if (! $answer) {
                   1022: 	&logthis("No reply on password change request to $server ".
                   1023: 		 "by $uname in domain $udom.");
                   1024:     } elsif ($answer =~ "^ok") {
                   1025:         &logthis("$uname in $udom successfully changed their password ".
                   1026: 		 "on $server.");
                   1027:     } elsif ($answer =~ "^pwchange_failure") {
                   1028: 	&logthis("$uname in $udom was unable to change their password ".
                   1029: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1030: 		 "or pwchange");
                   1031:     } elsif ($answer =~ "^non_authorized") {
                   1032:         &logthis("$uname in $udom did not get their password correct when ".
                   1033: 		 "attempting to change it on $server.");
                   1034:     } elsif ($answer =~ "^auth_mode_error") {
                   1035:         &logthis("$uname in $udom attempted to change their password despite ".
                   1036: 		 "not being locally or internally authenticated on $server.");
                   1037:     } elsif ($answer =~ "^unknown_user") {
                   1038:         &logthis("$uname in $udom attempted to change their password ".
                   1039: 		 "on $server but were unable to because $server is not ".
                   1040: 		 "their home server.");
                   1041:     } elsif ($answer =~ "^refused") {
                   1042: 	&logthis("$server refused to change $uname in $udom password because ".
                   1043: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1044:     } elsif ($answer =~ "invalid_client") {
                   1045:         &logthis("$server refused to change $uname in $udom password because ".
                   1046:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1047:     }
                   1048:     return $answer;
1.1       albertel 1049: }
                   1050: 
1.169     harris41 1051: # ----------------------- Try to determine user's current authentication scheme
                   1052: 
                   1053: sub queryauthenticate {
                   1054:     my ($uname,$udom)=@_;
1.456     albertel 1055:     my $uhome=&homeserver($uname,$udom);
                   1056:     if (!$uhome) {
                   1057: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1058: 	return 'no_host';
                   1059:     }
                   1060:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1061:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1062: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1063:     }
1.456     albertel 1064:     return $answer;
1.169     harris41 1065: }
                   1066: 
1.1       albertel 1067: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1068: 
1.1       albertel 1069: sub authenticate {
1.1073    raeburn  1070:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1071:     $upass=&escape($upass);
                   1072:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1073:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1074:     my $newhome;
1.836     www      1075:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1076: # Maybe the machine was offline and only re-appeared again recently?
                   1077:         &reconlonc();
                   1078: # One more
1.952     raeburn  1079: 	$uhome=&homeserver($uname,$udom,1);
                   1080:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1081:             if (defined(&domain($udom,'primary'))) {
                   1082:                 $newhome=&domain($udom,'primary');
                   1083:             }
                   1084:             if ($newhome ne '') {
                   1085:                 $uhome = $newhome;
                   1086:             }
                   1087:         }
1.836     www      1088: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1089: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1090: 	    return 'no_host';
                   1091:         }
1.1       albertel 1092:     }
1.1073    raeburn  1093:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1094:     if ($answer eq 'authorized') {
1.952     raeburn  1095:         if ($newhome) {
                   1096:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1097:             return 'no_account_on_host'; 
                   1098:         } else {
                   1099:             &logthis("User $uname at $udom authorized by $uhome");
                   1100:             return $uhome;
                   1101:         }
1.471     albertel 1102:     }
                   1103:     if ($answer eq 'non_authorized') {
                   1104: 	&logthis("User $uname at $udom rejected by $uhome");
                   1105: 	return 'no_host'; 
1.9       www      1106:     }
1.471     albertel 1107:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1108:     return 'no_host';
                   1109: }
                   1110: 
1.1073    raeburn  1111: sub can_host_session {
1.1074    raeburn  1112:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1113:     my $canhost = 1;
1.1074    raeburn  1114:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1115:     if (ref($remotesessions) eq 'HASH') {
                   1116:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1117:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1118:                 $canhost = 0;
                   1119:             } else {
                   1120:                 $canhost = 1;
                   1121:             }
                   1122:         }
                   1123:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1124:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1125:                 $canhost = 1;
                   1126:             } else {
                   1127:                 $canhost = 0;
                   1128:             }
                   1129:         }
                   1130:         if ($canhost) {
                   1131:             if ($remotesessions->{'version'} ne '') {
                   1132:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1133:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1134:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1135:                         my $major = $1;
                   1136:                         my $minor = $2;
                   1137:                         if (($major < $reqmajor ) ||
                   1138:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1139:                             $canhost = 0;
                   1140:                         }
                   1141:                     } else {
                   1142:                         $canhost = 0;
                   1143:                     }
                   1144:                 }
                   1145:             }
                   1146:         }
                   1147:     }
                   1148:     if ($canhost) {
                   1149:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1150:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1151:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1152:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1153:                 if (($uint_dom ne '') && 
                   1154:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1155:                     $canhost = 0;
                   1156:                 } else {
                   1157:                     $canhost = 1;
                   1158:                 }
                   1159:             }
                   1160:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1161:                 if (($uint_dom ne '') && 
                   1162:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1163:                     $canhost = 1;
                   1164:                 } else {
                   1165:                     $canhost = 0;
                   1166:                 }
                   1167:             }
                   1168:         }
                   1169:     }
                   1170:     return $canhost;
                   1171: }
                   1172: 
1.1083    raeburn  1173: sub spare_can_host {
                   1174:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1175:     my $canhost=1;
                   1176:     my @intdoms;
                   1177:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
                   1178:     if (ref($internet_names) eq 'ARRAY') {
                   1179:         @intdoms = @{$internet_names};
                   1180:     }
                   1181:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1182:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
                   1183:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   1184:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   1185:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
                   1186:         $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1187:                                      $remotesessions,
                   1188:                                      $defdomdefaults{'hostedsessions'});
                   1189:     }
                   1190:     return $canhost;
                   1191: }
                   1192: 
1.1123    raeburn  1193: sub this_host_spares {
                   1194:     my ($dom) = @_;
1.1126    raeburn  1195:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1196:     my @hosts = &current_machine_ids();
                   1197:     foreach my $lonhost (@hosts) {
                   1198:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1199:             $dom_in_use = $dom;
                   1200:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1201:             last;
                   1202:         }
                   1203:     }
1.1126    raeburn  1204:     if ($dom_in_use ne '') {
                   1205:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1206:     }
                   1207:     if (ref($result) ne 'HASH') {
                   1208:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1209:         $dom_in_use = &host_domain($lonhost_in_use);
                   1210:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1211:         if (ref($result) ne 'HASH') {
                   1212:             $result = \%spareid;
                   1213:         }
                   1214:     }
                   1215:     return $result;
                   1216: }
                   1217: 
                   1218: sub spares_for_offload  {
                   1219:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1220:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1221:     if (defined($cached)) {
                   1222:         return $result;
                   1223:     } else {
1.1126    raeburn  1224:         my $cachetime = 60*60*24;
                   1225:         my %domconfig =
                   1226:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1227:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1228:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1229:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1230:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1231:                 }
                   1232:             }
                   1233:         }
                   1234:     }
1.1126    raeburn  1235:     return;
1.1123    raeburn  1236: }
                   1237: 
1.1129    raeburn  1238: sub get_lonbalancer_config {
                   1239:     my ($servers) = @_;
                   1240:     my ($currbalancer,$currtargets);
                   1241:     if (ref($servers) eq 'HASH') {
                   1242:         foreach my $server (keys(%{$servers})) {
                   1243:             my %what = (
                   1244:                          spareid => 1,
                   1245:                          perlvar => 1,
                   1246:                        );
                   1247:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1248:             if ($result eq 'ok') {
                   1249:                 if (ref($returnhash) eq 'HASH') {
                   1250:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1251:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1252:                             $currbalancer = $server;
                   1253:                             $currtargets = {};
                   1254:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1255:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1256:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1257:                                 }
                   1258:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1259:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1260:                                 }
                   1261:                             }
                   1262:                             last;
                   1263:                         }
                   1264:                     }
                   1265:                 }
                   1266:             }
                   1267:         }
                   1268:     }
                   1269:     return ($currbalancer,$currtargets);
                   1270: }
                   1271: 
                   1272: sub check_loadbalancing {
                   1273:     my ($uname,$udom) = @_;
1.1172.2.12  raeburn  1274:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
                   1275:         $rule_in_effect,$offloadto,$otherserver);
1.1129    raeburn  1276:     my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4  raeburn  1277:     my @hosts = &current_machine_ids();
1.1129    raeburn  1278:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1279:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1280:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1281:     my $serverhomedom = &host_domain($lonhost);
                   1282: 
                   1283:     my $cachetime = 60*60*24;
                   1284: 
                   1285:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1286:         $dom_in_use = $udom;
                   1287:         $homeintdom = 1;
                   1288:     } else {
                   1289:         $dom_in_use = $serverhomedom;
                   1290:     }
                   1291:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1292:     unless (defined($cached)) {
                   1293:         my %domconfig =
                   1294:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1295:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1296:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1297:         }
                   1298:     }
                   1299:     if (ref($result) eq 'HASH') {
1.1172.2.12  raeburn  1300:         ($is_balancer,$currtargets,$currrules) =
                   1301:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1302:         if ($is_balancer) {
                   1303:             if (ref($currrules) eq 'HASH') {
                   1304:                 if ($homeintdom) {
                   1305:                     if ($uname ne '') {
                   1306:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1307:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1308:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1309:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1310:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1311:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1312:                             }
                   1313:                         }
                   1314:                         if ($rule_in_effect eq '') {
                   1315:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1316:                             if ($userenv{'inststatus'} ne '') {
                   1317:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1318:                                 my ($othertitle,$usertypes,$types) =
                   1319:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1320:                                 if (ref($types) eq 'ARRAY') {
                   1321:                                     foreach my $type (@{$types}) {
                   1322:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1323:                                             if (exists($currrules->{$type})) {
                   1324:                                                 $rule_in_effect = $currrules->{$type};
                   1325:                                             }
                   1326:                                         }
                   1327:                                     }
                   1328:                                 }
                   1329:                             } else {
                   1330:                                 if (exists($currrules->{'default'})) {
                   1331:                                     $rule_in_effect = $currrules->{'default'};
                   1332:                                 }
                   1333:                             }
                   1334:                         }
                   1335:                     } else {
                   1336:                         if (exists($currrules->{'default'})) {
                   1337:                             $rule_in_effect = $currrules->{'default'};
                   1338:                         }
                   1339:                     }
                   1340:                 } else {
                   1341:                     if ($currrules->{'_LC_external'} ne '') {
                   1342:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1343:                     }
                   1344:                 }
                   1345:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1346:                                                        $uname,$udom);
                   1347:             }
                   1348:         }
                   1349:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35  raeburn  1350:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1351:         unless (defined($cached)) {
                   1352:             my %domconfig =
                   1353:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1354:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1355:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1356:             }
                   1357:         }
                   1358:         if (ref($result) eq 'HASH') {
1.1172.2.12  raeburn  1359:             ($is_balancer,$currtargets,$currrules) =
                   1360:                 &check_balancer_result($result,@hosts);
                   1361:             if ($is_balancer) {
1.1129    raeburn  1362:                 if (ref($currrules) eq 'HASH') {
                   1363:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1364:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1365:                     }
                   1366:                 }
                   1367:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1368:                                                        $uname,$udom);
                   1369:             }
                   1370:         } else {
                   1371:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1372:                 $is_balancer = 1;
                   1373:                 $offloadto = &this_host_spares($dom_in_use);
                   1374:             }
                   1375:         }
                   1376:     } else {
                   1377:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1378:             $is_balancer = 1;
                   1379:             $offloadto = &this_host_spares($dom_in_use);
                   1380:         }
                   1381:     }
1.1172.2.5  raeburn  1382:     if ($is_balancer) {
                   1383:         my $lowest_load = 30000;
                   1384:         if (ref($offloadto) eq 'HASH') {
                   1385:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1386:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1387:                     ($otherserver,$lowest_load) =
                   1388:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1389:                 }
1.1129    raeburn  1390:             }
1.1172.2.5  raeburn  1391:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1392: 
1.1172.2.5  raeburn  1393:             if (!$found_server) {
                   1394:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1395:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1396:                         ($otherserver,$lowest_load) =
                   1397:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1398:                     }
                   1399:                 }
                   1400:             }
                   1401:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1402:             if (@{$offloadto} == 1) {
                   1403:                 $otherserver = $offloadto->[0];
                   1404:             } elsif (@{$offloadto} > 1) {
                   1405:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1406:                     ($otherserver,$lowest_load) =
                   1407:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1408:                 }
                   1409:             }
                   1410:         }
1.1172.2.5  raeburn  1411:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1412:             $is_balancer = 0;
                   1413:             if ($uname ne '' && $udom ne '') {
                   1414:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1415: 
                   1416:                     &appenv({'user.loadbalexempt'     => $lonhost,
                   1417:                              'user.loadbalcheck.time' => time});
                   1418:                 }
1.1129    raeburn  1419:             }
                   1420:         }
                   1421:     }
                   1422:     return ($is_balancer,$otherserver);
                   1423: }
                   1424: 
1.1172.2.12  raeburn  1425: sub check_balancer_result {
                   1426:     my ($result,@hosts) = @_;
                   1427:     my ($is_balancer,$currtargets,$currrules);
                   1428:     if (ref($result) eq 'HASH') {
                   1429:         if ($result->{'lonhost'} ne '') {
                   1430:             my $currbalancer = $result->{'lonhost'};
                   1431:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1432:                 $is_balancer = 1;
                   1433:                 $currtargets = $result->{'targets'};
                   1434:                 $currrules = $result->{'rules'};
                   1435:             }
                   1436:         } else {
                   1437:             foreach my $key (keys(%{$result})) {
                   1438:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1439:                     (ref($result->{$key}) eq 'HASH')) {
                   1440:                     $is_balancer = 1;
                   1441:                     $currrules = $result->{$key}{'rules'};
                   1442:                     $currtargets = $result->{$key}{'targets'};
                   1443:                     last;
                   1444:                 }
                   1445:             }
                   1446:         }
                   1447:     }
                   1448:     return ($is_balancer,$currtargets,$currrules);
                   1449: }
                   1450: 
1.1129    raeburn  1451: sub get_loadbalancer_targets {
                   1452:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1453:     my $offloadto;
1.1172.2.4  raeburn  1454:     if ($rule_in_effect eq 'none') {
                   1455:         return [$perlvar{'lonHostID'}];
                   1456:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1457:         $offloadto = $currtargets;
                   1458:     } else {
                   1459:         if ($rule_in_effect eq 'homeserver') {
                   1460:             my $homeserver = &homeserver($uname,$udom);
                   1461:             if ($homeserver ne 'no_host') {
                   1462:                 $offloadto = [$homeserver];
                   1463:             }
                   1464:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1465:             my %domconfig =
                   1466:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1467:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1468:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1469:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1470:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1471:                     }
                   1472:                 }
                   1473:             } else {
1.1172.2.7  raeburn  1474:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1475:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1476:                 if (&hostname($remotebalancer) ne '') {
                   1477:                     $offloadto = [$remotebalancer];
                   1478:                 }
                   1479:             }
                   1480:         } elsif (&hostname($rule_in_effect) ne '') {
                   1481:             $offloadto = [$rule_in_effect];
                   1482:         }
                   1483:     }
                   1484:     return $offloadto;
                   1485: }
                   1486: 
1.1127    raeburn  1487: sub internet_dom_servers {
                   1488:     my ($dom) = @_;
                   1489:     my (%uniqservers,%servers);
                   1490:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1491:     my @machinedoms = &machine_domains($primaryserver);
                   1492:     foreach my $mdom (@machinedoms) {
                   1493:         my %currservers = %servers;
                   1494:         my %server = &get_servers($mdom);
                   1495:         %servers = (%currservers,%server);
                   1496:     }
                   1497:     my %by_hostname;
                   1498:     foreach my $id (keys(%servers)) {
                   1499:         push(@{$by_hostname{$servers{$id}}},$id);
                   1500:     }
                   1501:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1502:         if (@{$by_hostname{$hostname}} > 1) {
                   1503:             my $match = 0;
                   1504:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1505:                 if (&host_domain($id) eq $dom) {
                   1506:                     $uniqservers{$id} = $hostname;
                   1507:                     $match = 1;
                   1508:                 }
                   1509:             }
                   1510:             unless ($match) {
                   1511:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1512:             }
                   1513:         } else {
                   1514:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1515:         }
                   1516:     }
                   1517:     return %uniqservers;
                   1518: }
                   1519: 
1.1       albertel 1520: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1521: 
1.599     albertel 1522: my %homecache;
1.1       albertel 1523: sub homeserver {
1.230     stredwic 1524:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1525:     my $index="$uname:$udom";
1.426     albertel 1526: 
1.599     albertel 1527:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1528: 
                   1529:     my %servers = &get_servers($udom,'library');
                   1530:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1531:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1532: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1533: 
                   1534: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1535: 	if ($answer eq 'found') {
                   1536: 	    delete($badServerCache{$tryserver}); 
                   1537: 	    return $homecache{$index}=$tryserver;
                   1538: 	} elsif ($answer eq 'no_host') {
                   1539: 	    $badServerCache{$tryserver}=1;
                   1540: 	}
1.1       albertel 1541:     }    
                   1542:     return 'no_host';
1.70      www      1543: }
                   1544: 
                   1545: # ------------------------------------- Find the usernames behind a list of IDs
                   1546: 
                   1547: sub idget {
                   1548:     my ($udom,@ids)=@_;
                   1549:     my %returnhash=();
                   1550:     
1.841     albertel 1551:     my %servers = &get_servers($udom,'library');
                   1552:     foreach my $tryserver (keys(%servers)) {
                   1553: 	my $idlist=join('&',@ids);
                   1554: 	$idlist=~tr/A-Z/a-z/; 
                   1555: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1556: 	my @answer=();
                   1557: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1558: 	    @answer=split(/\&/,$reply);
                   1559: 	}                    ;
                   1560: 	my $i;
                   1561: 	for ($i=0;$i<=$#ids;$i++) {
                   1562: 	    if ($answer[$i]) {
                   1563: 		$returnhash{$ids[$i]}=$answer[$i];
                   1564: 	    } 
                   1565: 	}
                   1566:     } 
1.70      www      1567:     return %returnhash;
                   1568: }
                   1569: 
                   1570: # ------------------------------------- Find the IDs behind a list of usernames
                   1571: 
                   1572: sub idrget {
                   1573:     my ($udom,@unames)=@_;
                   1574:     my %returnhash=();
1.800     albertel 1575:     foreach my $uname (@unames) {
                   1576:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1577:     }
1.70      www      1578:     return %returnhash;
                   1579: }
                   1580: 
                   1581: # ------------------------------- Store away a list of names and associated IDs
                   1582: 
                   1583: sub idput {
                   1584:     my ($udom,%ids)=@_;
                   1585:     my %servers=();
1.800     albertel 1586:     foreach my $uname (keys(%ids)) {
                   1587: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1588:         my $uhom=&homeserver($uname,$udom);
1.70      www      1589:         if ($uhom ne 'no_host') {
1.800     albertel 1590:             my $id=&escape($ids{$uname});
1.70      www      1591:             $id=~tr/A-Z/a-z/;
1.800     albertel 1592:             my $esc_unam=&escape($uname);
1.70      www      1593: 	    if ($servers{$uhom}) {
1.800     albertel 1594: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1595:             } else {
1.800     albertel 1596:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1597:             }
                   1598:         }
1.191     harris41 1599:     }
1.800     albertel 1600:     foreach my $server (keys(%servers)) {
                   1601:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1602:     }
1.344     www      1603: }
                   1604: 
1.1172.2.30  raeburn  1605: # ---------------------------------------- Delete unwanted IDs from ids.db file
                   1606: 
                   1607: sub iddel {
                   1608:     my ($udom,$idshashref,$uhome)=@_;
                   1609:     my %result=();
                   1610:     unless (ref($idshashref) eq 'HASH') {
                   1611:         return %result;
                   1612:     }
                   1613:     my %servers=();
                   1614:     while (my ($id,$uname) = each(%{$idshashref})) {
                   1615:         my $uhom;
                   1616:         if ($uhome) {
                   1617:             $uhom = $uhome;
                   1618:         } else {
                   1619:             $uhom=&homeserver($uname,$udom);
                   1620:         }
                   1621:         if ($uhom ne 'no_host') {
                   1622:             if ($servers{$uhom}) {
                   1623:                 $servers{$uhom}.='&'.&escape($id);
                   1624:             } else {
                   1625:                 $servers{$uhom}=&escape($id);
                   1626:             }
                   1627:         }
                   1628:     }
                   1629:     foreach my $server (keys(%servers)) {
                   1630:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1631:     }
                   1632:     return %result;
                   1633: }
                   1634: 
1.1023    raeburn  1635: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1636: sub dump_dom {
1.1165    droeschl 1637:     my ($namespace, $udom, $regexp) = @_;
                   1638: 
                   1639:     $udom ||= $env{'user.domain'};
                   1640: 
                   1641:     return () unless $udom;
                   1642: 
                   1643:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1644: }
                   1645: 
1.1023    raeburn  1646: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1647: 
                   1648: sub get_dom {
1.860     raeburn  1649:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn  1650:     my $items='';
                   1651:     foreach my $item (@$storearr) {
                   1652:         $items.=&escape($item).'&';
                   1653:     }
                   1654:     $items=~s/\&$//;
1.860     raeburn  1655:     if (!$udom) {
                   1656:         $udom=$env{'user.domain'};
                   1657:         if (defined(&domain($udom,'primary'))) {
                   1658:             $uhome=&domain($udom,'primary');
                   1659:         } else {
1.874     albertel 1660:             undef($uhome);
1.860     raeburn  1661:         }
                   1662:     } else {
                   1663:         if (!$uhome) {
                   1664:             if (defined(&domain($udom,'primary'))) {
                   1665:                 $uhome=&domain($udom,'primary');
                   1666:             }
                   1667:         }
                   1668:     }
                   1669:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1670:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1671:         my %returnhash;
1.875     albertel 1672:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1673:             return %returnhash;
                   1674:         }
1.806     raeburn  1675:         my @pairs=split(/\&/,$rep);
                   1676:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1677:             return @pairs;
                   1678:         }
                   1679:         my $i=0;
                   1680:         foreach my $item (@$storearr) {
                   1681:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1682:             $i++;
                   1683:         }
                   1684:         return %returnhash;
                   1685:     } else {
1.880     banghart 1686:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1687:     }
                   1688: }
                   1689: 
                   1690: # -------------------------------------------- put items in domain db files 
                   1691: 
                   1692: sub put_dom {
1.860     raeburn  1693:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1694:     if (!$udom) {
                   1695:         $udom=$env{'user.domain'};
                   1696:         if (defined(&domain($udom,'primary'))) {
                   1697:             $uhome=&domain($udom,'primary');
                   1698:         } else {
1.874     albertel 1699:             undef($uhome);
1.860     raeburn  1700:         }
                   1701:     } else {
                   1702:         if (!$uhome) {
                   1703:             if (defined(&domain($udom,'primary'))) {
                   1704:                 $uhome=&domain($udom,'primary');
                   1705:             }
                   1706:         }
                   1707:     } 
                   1708:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1709:         my $items='';
                   1710:         foreach my $item (keys(%$storehash)) {
                   1711:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1712:         }
                   1713:         $items=~s/\&$//;
                   1714:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1715:     } else {
1.860     raeburn  1716:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1717:     }
                   1718: }
                   1719: 
1.1023    raeburn  1720: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1721: sub newput_dom {
1.1023    raeburn  1722:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1723:     my $result;
                   1724:     if (!$udom) {
                   1725:         $udom=$env{'user.domain'};
                   1726:     }
1.1023    raeburn  1727:     if ($udom) {
                   1728:         my $uname = &get_domainconfiguser($udom);
                   1729:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1730:     }
                   1731:     return $result;
                   1732: }
                   1733: 
1.1023    raeburn  1734: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1735: sub del_dom {
1.1023    raeburn  1736:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1737:     if (ref($storearr) eq 'ARRAY') {
                   1738:         if (!$udom) {
                   1739:             $udom=$env{'user.domain'};
                   1740:         }
1.1023    raeburn  1741:         if ($udom) {
                   1742:             my $uname = &get_domainconfiguser($udom); 
                   1743:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1744:         }
                   1745:     }
                   1746: }
                   1747: 
1.1023    raeburn  1748: # ----------------------------------construct domainconfig user for a domain 
                   1749: sub get_domainconfiguser {
                   1750:     my ($udom) = @_;
                   1751:     return $udom.'-domainconfig';
                   1752: }
                   1753: 
1.837     raeburn  1754: sub retrieve_inst_usertypes {
                   1755:     my ($udom) = @_;
                   1756:     my (%returnhash,@order);
1.989     raeburn  1757:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1758:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1759:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44  raeburn  1760:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  1761:     } else {
                   1762:         if (defined(&domain($udom,'primary'))) {
                   1763:             my $uhome=&domain($udom,'primary');
                   1764:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1765:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44  raeburn  1766:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  1767:                 return (\%returnhash,\@order);
                   1768:             }
                   1769:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1770:             my @pairs=split(/\&/,$hashitems);
                   1771:             foreach my $item (@pairs) {
                   1772:                 my ($key,$value)=split(/=/,$item,2);
                   1773:                 $key = &unescape($key);
                   1774:                 next if ($key =~ /^error: 2 /);
                   1775:                 $returnhash{$key}=&thaw_unescape($value);
                   1776:             }
                   1777:             my @esc_order = split(/\&/,$orderitems);
                   1778:             foreach my $item (@esc_order) {
                   1779:                 push(@order,&unescape($item));
                   1780:             }
                   1781:         } else {
1.1172.2.44  raeburn  1782:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  1783:         }
1.1172.2.44  raeburn  1784:         return (\%returnhash,\@order);
1.837     raeburn  1785:     }
                   1786: }
                   1787: 
1.868     raeburn  1788: sub is_domainimage {
                   1789:     my ($url) = @_;
                   1790:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1791:         if (&domain($1) ne '') {
                   1792:             return '1';
                   1793:         }
                   1794:     }
                   1795:     return;
                   1796: }
                   1797: 
1.899     raeburn  1798: sub inst_directory_query {
                   1799:     my ($srch) = @_;
                   1800:     my $udom = $srch->{'srchdomain'};
                   1801:     my %results;
                   1802:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1803:     my $outcome;
1.899     raeburn  1804:     if ($homeserver ne '') {
1.904     albertel 1805: 	my $queryid=&reply("querysend:instdirsearch:".
                   1806: 			   &escape($srch->{'srchby'}).':'.
                   1807: 			   &escape($srch->{'srchterm'}).':'.
                   1808: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1809: 	my $host=&hostname($homeserver);
                   1810: 	if ($queryid !~/^\Q$host\E\_/) {
                   1811: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1812: 	    return;
                   1813: 	}
                   1814: 	my $response = &get_query_reply($queryid);
                   1815: 	my $maxtries = 5;
                   1816: 	my $tries = 1;
                   1817: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1818: 	    $response = &get_query_reply($queryid);
                   1819: 	    $tries ++;
                   1820: 	}
                   1821: 
                   1822:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1823:             if ($response eq 'unavailable') {
                   1824:                 $outcome = $response;
                   1825:             } else {
                   1826:                 $outcome = 'ok';
                   1827:                 my @matches = split(/\n/,$response);
                   1828:                 foreach my $match (@matches) {
                   1829:                     my ($key,$value) = split(/=/,$match);
                   1830:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1831:                 }
1.899     raeburn  1832:             }
                   1833:         }
                   1834:     }
1.909     raeburn  1835:     return ($outcome,%results);
1.899     raeburn  1836: }
                   1837: 
                   1838: sub usersearch {
                   1839:     my ($srch) = @_;
                   1840:     my $dom = $srch->{'srchdomain'};
                   1841:     my %results;
                   1842:     my %libserv = &all_library();
                   1843:     my $query = 'usersearch';
                   1844:     foreach my $tryserver (keys(%libserv)) {
                   1845:         if (&host_domain($tryserver) eq $dom) {
                   1846:             my $host=&hostname($tryserver);
                   1847:             my $queryid=
1.911     raeburn  1848:                 &reply("querysend:".&escape($query).':'.
                   1849:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1850:                        &escape($srch->{'srchtype'}).':'.
                   1851:                        &escape($srch->{'srchterm'}),$tryserver);
                   1852:             if ($queryid !~/^\Q$host\E\_/) {
                   1853:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1854:                 next;
1.899     raeburn  1855:             }
                   1856:             my $reply = &get_query_reply($queryid);
                   1857:             my $maxtries = 1;
                   1858:             my $tries = 1;
                   1859:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1860:                 $reply = &get_query_reply($queryid);
                   1861:                 $tries ++;
                   1862:             }
                   1863:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1864:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1865:             } else {
1.911     raeburn  1866:                 my @matches;
                   1867:                 if ($reply =~ /\n/) {
                   1868:                     @matches = split(/\n/,$reply);
                   1869:                 } else {
                   1870:                     @matches = split(/\&/,$reply);
                   1871:                 }
1.899     raeburn  1872:                 foreach my $match (@matches) {
                   1873:                     my ($uname,$udom,%userhash);
1.911     raeburn  1874:                     foreach my $entry (split(/:/,$match)) {
                   1875:                         my ($key,$value) =
                   1876:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1877:                         $userhash{$key} = $value;
                   1878:                         if ($key eq 'username') {
                   1879:                             $uname = $value;
                   1880:                         } elsif ($key eq 'domain') {
                   1881:                             $udom = $value;
1.911     raeburn  1882:                         }
1.899     raeburn  1883:                     }
                   1884:                     $results{$uname.':'.$udom} = \%userhash;
                   1885:                 }
                   1886:             }
                   1887:         }
                   1888:     }
                   1889:     return %results;
                   1890: }
                   1891: 
1.912     raeburn  1892: sub get_instuser {
                   1893:     my ($udom,$uname,$id) = @_;
                   1894:     my $homeserver = &domain($udom,'primary');
                   1895:     my ($outcome,%results);
                   1896:     if ($homeserver ne '') {
                   1897:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1898:                            &escape($id).':'.&escape($udom),$homeserver);
                   1899:         my $host=&hostname($homeserver);
                   1900:         if ($queryid !~/^\Q$host\E\_/) {
                   1901:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1902:             return;
                   1903:         }
                   1904:         my $response = &get_query_reply($queryid);
                   1905:         my $maxtries = 5;
                   1906:         my $tries = 1;
                   1907:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1908:             $response = &get_query_reply($queryid);
                   1909:             $tries ++;
                   1910:         }
                   1911:         if (!&error($response) && $response ne 'refused') {
                   1912:             if ($response eq 'unavailable') {
                   1913:                 $outcome = $response;
                   1914:             } else {
                   1915:                 $outcome = 'ok';
                   1916:                 my @matches = split(/\n/,$response);
                   1917:                 foreach my $match (@matches) {
                   1918:                     my ($key,$value) = split(/=/,$match);
                   1919:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1920:                 }
                   1921:             }
                   1922:         }
                   1923:     }
                   1924:     my %userinfo;
                   1925:     if (ref($results{$uname}) eq 'HASH') {
                   1926:         %userinfo = %{$results{$uname}};
                   1927:     } 
                   1928:     return ($outcome,%userinfo);
                   1929: }
                   1930: 
                   1931: sub inst_rulecheck {
1.923     raeburn  1932:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1933:     my %returnhash;
                   1934:     if ($udom ne '') {
                   1935:         if (ref($rules) eq 'ARRAY') {
                   1936:             @{$rules} = map {&escape($_);} (@{$rules});
                   1937:             my $rulestr = join(':',@{$rules});
                   1938:             my $homeserver=&domain($udom,'primary');
                   1939:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1940:                 my $response;
                   1941:                 if ($item eq 'username') {                
                   1942:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1943:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1944:                                               $homeserver));
1.923     raeburn  1945:                 } elsif ($item eq 'id') {
                   1946:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1947:                                               ':'.&escape($id).':'.$rulestr,
                   1948:                                               $homeserver));
1.945     raeburn  1949:                 } elsif ($item eq 'selfcreate') {
                   1950:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1951:                                                &escape($udom).':'.&escape($uname).
                   1952:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1953:                 }
1.912     raeburn  1954:                 if ($response ne 'refused') {
                   1955:                     my @pairs=split(/\&/,$response);
                   1956:                     foreach my $item (@pairs) {
                   1957:                         my ($key,$value)=split(/=/,$item,2);
                   1958:                         $key = &unescape($key);
                   1959:                         next if ($key =~ /^error: 2 /);
                   1960:                         $returnhash{$key}=&thaw_unescape($value);
                   1961:                     }
                   1962:                 }
                   1963:             }
                   1964:         }
                   1965:     }
                   1966:     return %returnhash;
                   1967: }
                   1968: 
                   1969: sub inst_userrules {
1.923     raeburn  1970:     my ($udom,$check) = @_;
1.912     raeburn  1971:     my (%ruleshash,@ruleorder);
                   1972:     if ($udom ne '') {
                   1973:         my $homeserver=&domain($udom,'primary');
                   1974:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1975:             my $response;
                   1976:             if ($check eq 'id') {
                   1977:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1978:                                  $homeserver);
1.943     raeburn  1979:             } elsif ($check eq 'email') {
                   1980:                 $response=&reply('instemailrules:'.&escape($udom),
                   1981:                                  $homeserver);
1.923     raeburn  1982:             } else {
                   1983:                 $response=&reply('instuserrules:'.&escape($udom),
                   1984:                                  $homeserver);
                   1985:             }
1.912     raeburn  1986:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1987:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1988:                 ($response ne 'no_such_host')) {
                   1989:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1990:                 my @pairs=split(/\&/,$hashitems);
                   1991:                 foreach my $item (@pairs) {
                   1992:                     my ($key,$value)=split(/=/,$item,2);
                   1993:                     $key = &unescape($key);
                   1994:                     next if ($key =~ /^error: 2 /);
                   1995:                     $ruleshash{$key}=&thaw_unescape($value);
                   1996:                 }
                   1997:                 my @esc_order = split(/\&/,$orderitems);
                   1998:                 foreach my $item (@esc_order) {
                   1999:                     push(@ruleorder,&unescape($item));
                   2000:                 }
                   2001:             }
                   2002:         }
                   2003:     }
                   2004:     return (\%ruleshash,\@ruleorder);
                   2005: }
                   2006: 
1.976     raeburn  2007: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2008: 
                   2009: sub get_domain_defaults {
1.1172.2.35  raeburn  2010:     my ($domain,$ignore_cache) = @_;
                   2011:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2012:     my $cachetime = 60*60*24;
1.1172.2.35  raeburn  2013:     unless ($ignore_cache) {
                   2014:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2015:         if (defined($cached)) {
                   2016:             if (ref($result) eq 'HASH') {
                   2017:                 return %{$result};
                   2018:             }
1.943     raeburn  2019:         }
                   2020:     }
                   2021:     my %domdefaults;
                   2022:     my %domconfig =
1.989     raeburn  2023:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2024:                                   'requestcourses','inststatus',
1.1172.2.9  raeburn  2025:                                   'coursedefaults','usersessions',
1.1172.2.46  raeburn  2026:                                   'requestauthor','selfenrollment',
                   2027:                                   'coursecategories'],$domain);
1.1172.2.41  raeburn  2028:     my @coursetypes = ('official','unofficial','community','textbook');
1.943     raeburn  2029:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2030:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2031:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2032:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2033:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2034:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2035:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943     raeburn  2036:     } else {
                   2037:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2038:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2039:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2040:     }
1.976     raeburn  2041:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2042:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2043:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2044:         } else {
                   2045:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29  raeburn  2046:         }
1.1172.2.6  raeburn  2047:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2048:         foreach my $item (@usertools) {
                   2049:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2050:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2051:             }
                   2052:         }
1.1172.2.29  raeburn  2053:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2054:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2055:         }
1.976     raeburn  2056:     }
1.985     raeburn  2057:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37  raeburn  2058:         foreach my $item ('official','unofficial','community','textbook') {
1.985     raeburn  2059:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2060:         }
                   2061:     }
1.1172.2.9  raeburn  2062:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2063:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2064:     }
1.989     raeburn  2065:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44  raeburn  2066:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2067:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2068:         }
                   2069:     }
1.1047    raeburn  2070:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.41  raeburn  2071:         foreach my $type (@coursetypes) {
                   2072:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2073:                 unless ($type eq 'community') {
                   2074:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2075:                 }
                   2076:             }
                   2077:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2078:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2079:             }
1.1172.2.30  raeburn  2080:         }
1.1047    raeburn  2081:     }
1.1073    raeburn  2082:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2083:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2084:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2085:         }
                   2086:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2087:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2088:         }
                   2089:     }
1.1172.2.41  raeburn  2090:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2091:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2092:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2093:                             'approval','limit');
                   2094:             foreach my $type (@coursetypes) {
                   2095:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2096:                     my @mgrdc = ();
                   2097:                     foreach my $item (@settings) {
                   2098:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2099:                             push(@mgrdc,$item);
                   2100:                         }
                   2101:                     }
                   2102:                     if (@mgrdc) {
                   2103:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2104:                     }
                   2105:                 }
                   2106:             }
                   2107:         }
                   2108:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2109:             foreach my $type (@coursetypes) {
                   2110:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2111:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2112:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2113:                     }
                   2114:                 }
                   2115:             }
                   2116:         }
                   2117:     }
1.1172.2.46  raeburn  2118:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2119:         $domdefaults{'catauth'} = 'std';
                   2120:         $domdefaults{'catunauth'} = 'std';
                   2121:         if ($domconfig{'coursecategories'}{'auth'}) {
                   2122:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2123:         }
                   2124:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2125:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2126:         }
                   2127:     }
1.1172.2.23  raeburn  2128:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2129:     return %domdefaults;
                   2130: }
                   2131: 
1.344     www      2132: # --------------------------------------------------- Assign a key to a student
                   2133: 
                   2134: sub assign_access_key {
1.364     www      2135: #
                   2136: # a valid key looks like uname:udom#comments
                   2137: # comments are being appended
                   2138: #
1.498     www      2139:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2140:     $kdom=
1.620     albertel 2141:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2142:     $knum=
1.620     albertel 2143:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2144:     $cdom=
1.620     albertel 2145:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2146:     $cnum=
1.620     albertel 2147:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2148:     $udom=$env{'user.name'} unless (defined($udom));
                   2149:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2150:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2151:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2152:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2153:                                                   # assigned to this person
                   2154:                                                   # - this should not happen,
1.345     www      2155:                                                   # unless something went wrong
                   2156:                                                   # the first time around
                   2157: # ready to assign
1.364     www      2158:         $logentry=$1.'; '.$logentry;
1.496     www      2159:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2160:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2161: # key now belongs to user
1.346     www      2162: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2163:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2164:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2165:                 return 'ok';
                   2166:             } else {
                   2167:                 return 
                   2168:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2169: 	    }
                   2170:         } else {
                   2171:             return 'error: Could not assign key, try again later.';
                   2172:         }
1.364     www      2173:     } elsif (!$existing{$ckey}) {
1.345     www      2174: # the key does not exist
                   2175: 	return 'error: The key does not exist';
                   2176:     } else {
                   2177: # the key is somebody else's
                   2178: 	return 'error: The key is already in use';
                   2179:     }
1.344     www      2180: }
                   2181: 
1.364     www      2182: # ------------------------------------------ put an additional comment on a key
                   2183: 
                   2184: sub comment_access_key {
                   2185: #
                   2186: # a valid key looks like uname:udom#comments
                   2187: # comments are being appended
                   2188: #
                   2189:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2190:     $cdom=
1.620     albertel 2191:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2192:     $cnum=
1.620     albertel 2193:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2194:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2195:     if ($existing{$ckey}) {
                   2196:         $existing{$ckey}.='; '.$logentry;
                   2197: # ready to assign
1.367     www      2198:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2199:                                                  $cdom,$cnum) eq 'ok') {
                   2200: 	    return 'ok';
                   2201:         } else {
                   2202: 	    return 'error: Count not store comment.';
                   2203:         }
                   2204:     } else {
                   2205: # the key does not exist
                   2206: 	return 'error: The key does not exist';
                   2207:     }
                   2208: }
                   2209: 
1.344     www      2210: # ------------------------------------------------------ Generate a set of keys
                   2211: 
                   2212: sub generate_access_keys {
1.364     www      2213:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2214:     $cdom=
1.620     albertel 2215:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2216:     $cnum=
1.620     albertel 2217:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2218:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2219:     unless (($cdom) && ($cnum)) { return 0; }
                   2220:     if ($number>10000) { return 0; }
                   2221:     sleep(2); # make sure don't get same seed twice
                   2222:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2223:     my $total=0;
                   2224:     for (my $i=1;$i<=$number;$i++) {
                   2225:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2226:                   sprintf("%lx",int(100000*rand)).'-'.
                   2227:                   sprintf("%lx",int(100000*rand));
                   2228:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2229:        $newkey=~s/0/h/g; # and also 0 and O
                   2230:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2231:        if ($existing{$newkey}) {
                   2232:            $i--;
                   2233:        } else {
1.364     www      2234: 	  if (&put('accesskeys',
                   2235:               { $newkey => '# generated '.localtime().
1.620     albertel 2236:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2237:                            '; '.$logentry },
                   2238: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2239:               $total++;
                   2240: 	  }
                   2241:        }
                   2242:     }
1.620     albertel 2243:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2244:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2245:     return $total;
                   2246: }
                   2247: 
                   2248: # ------------------------------------------------------- Validate an accesskey
                   2249: 
                   2250: sub validate_access_key {
                   2251:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2252:     $cdom=
1.620     albertel 2253:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2254:     $cnum=
1.620     albertel 2255:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2256:     $udom=$env{'user.domain'} unless (defined($udom));
                   2257:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2258:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2259:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2260: }
                   2261: 
                   2262: # ------------------------------------- Find the section of student in a course
1.652     albertel 2263: sub devalidate_getsection_cache {
                   2264:     my ($udom,$unam,$courseid)=@_;
                   2265:     my $hashid="$udom:$unam:$courseid";
                   2266:     &devalidate_cache_new('getsection',$hashid);
                   2267: }
1.298     matthew  2268: 
1.815     albertel 2269: sub courseid_to_courseurl {
                   2270:     my ($courseid) = @_;
                   2271:     #already url style courseid
                   2272:     return $courseid if ($courseid =~ m{^/});
                   2273: 
                   2274:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2275: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2276: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2277: 	return "/$cdom/$cnum";
                   2278:     }
                   2279: 
                   2280:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2281:     if (exists($courseinfo{'num'})) {
                   2282: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2283:     }
                   2284: 
                   2285:     return undef;
                   2286: }
                   2287: 
1.298     matthew  2288: sub getsection {
                   2289:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2290:     my $cachetime=1800;
1.551     albertel 2291: 
                   2292:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2293:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2294:     if (defined($cached)) { return $result; }
                   2295: 
1.298     matthew  2296:     my %Pending; 
                   2297:     my %Expired;
                   2298:     #
                   2299:     # Each role can either have not started yet (pending), be active, 
                   2300:     #    or have expired.
                   2301:     #
                   2302:     # If there is an active role, we are done.
                   2303:     #
                   2304:     # If there is more than one role which has not started yet, 
                   2305:     #     choose the one which will start sooner
                   2306:     # If there is one role which has not started yet, return it.
                   2307:     #
                   2308:     # If there is more than one expired role, choose the one which ended last.
                   2309:     # If there is a role which has expired, return it.
                   2310:     #
1.815     albertel 2311:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2312:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2313:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2314:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2315:         my $section=$1;
                   2316:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2317:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2318:         my $now=time;
1.548     albertel 2319:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2320:             $Expired{$end}=$section;
                   2321:             next;
                   2322:         }
1.548     albertel 2323:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2324:             $Pending{$start}=$section;
                   2325:             next;
                   2326:         }
1.599     albertel 2327:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2328:     }
                   2329:     #
                   2330:     # Presumedly there will be few matching roles from the above
                   2331:     # loop and the sorting time will be negligible.
                   2332:     if (scalar(keys(%Pending))) {
                   2333:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2334:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2335:     } 
                   2336:     if (scalar(keys(%Expired))) {
                   2337:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2338:         my $time = pop(@sorted);
1.599     albertel 2339:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2340:     }
1.599     albertel 2341:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2342: }
1.70      www      2343: 
1.599     albertel 2344: sub save_cache {
                   2345:     &purge_remembered();
1.722     albertel 2346:     #&Apache::loncommon::validate_page();
1.620     albertel 2347:     undef(%env);
1.780     albertel 2348:     undef($env_loaded);
1.599     albertel 2349: }
1.452     albertel 2350: 
1.599     albertel 2351: my $to_remember=-1;
                   2352: my %remembered;
                   2353: my %accessed;
                   2354: my $kicks=0;
                   2355: my $hits=0;
1.849     albertel 2356: sub make_key {
                   2357:     my ($name,$id) = @_;
1.872     albertel 2358:     if (length($id) > 65 
                   2359: 	&& length(&escape($id)) > 200) {
                   2360: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2361:     }
1.849     albertel 2362:     return &escape($name.':'.$id);
                   2363: }
                   2364: 
1.599     albertel 2365: sub devalidate_cache_new {
                   2366:     my ($name,$id,$debug) = @_;
                   2367:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 2368:     $id=&make_key($name,$id);
1.599     albertel 2369:     $memcache->delete($id);
                   2370:     delete($remembered{$id});
                   2371:     delete($accessed{$id});
                   2372: }
                   2373: 
                   2374: sub is_cached_new {
                   2375:     my ($name,$id,$debug) = @_;
1.849     albertel 2376:     $id=&make_key($name,$id);
1.599     albertel 2377:     if (exists($remembered{$id})) {
1.1133    foxr     2378: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599     albertel 2379: 	$accessed{$id}=[&gettimeofday()];
                   2380: 	$hits++;
                   2381: 	return ($remembered{$id},1);
                   2382:     }
                   2383:     my $value = $memcache->get($id);
                   2384:     if (!(defined($value))) {
                   2385: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2386: 	return (undef,undef);
1.416     albertel 2387:     }
1.599     albertel 2388:     if ($value eq '__undef__') {
                   2389: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2390: 	$value=undef;
                   2391:     }
                   2392:     &make_room($id,$value,$debug);
                   2393:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2394:     return ($value,1);
                   2395: }
                   2396: 
                   2397: sub do_cache_new {
                   2398:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 2399:     $id=&make_key($name,$id);
1.599     albertel 2400:     my $setvalue=$value;
                   2401:     if (!defined($setvalue)) {
                   2402: 	$setvalue='__undef__';
                   2403:     }
1.623     albertel 2404:     if (!defined($time) ) {
                   2405: 	$time=600;
                   2406:     }
1.599     albertel 2407:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2408:     my $result = $memcache->set($id,$setvalue,$time);
                   2409:     if (! $result) {
1.872     albertel 2410: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2411: 	$memcache->disconnect_all();
1.872     albertel 2412:     }
1.600     albertel 2413:     # need to make a copy of $value
1.919     albertel 2414:     &make_room($id,$value,$debug);
1.599     albertel 2415:     return $value;
                   2416: }
                   2417: 
                   2418: sub make_room {
                   2419:     my ($id,$value,$debug)=@_;
1.919     albertel 2420: 
                   2421:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   2422:                                     : $value;
1.599     albertel 2423:     if ($to_remember<0) { return; }
                   2424:     $accessed{$id}=[&gettimeofday()];
                   2425:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2426:     my $to_kick;
                   2427:     my $max_time=0;
                   2428:     foreach my $other (keys(%accessed)) {
                   2429: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2430: 	    $to_kick=$other;
                   2431: 	    $max_time=&tv_interval($accessed{$other});
                   2432: 	}
                   2433:     }
                   2434:     delete($remembered{$to_kick});
                   2435:     delete($accessed{$to_kick});
                   2436:     $kicks++;
                   2437:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2438:     return;
                   2439: }
                   2440: 
1.599     albertel 2441: sub purge_remembered {
1.604     albertel 2442:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2443:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2444:     undef(%remembered);
                   2445:     undef(%accessed);
1.428     albertel 2446: }
1.70      www      2447: # ------------------------------------- Read an entry from a user's environment
                   2448: 
                   2449: sub userenvironment {
                   2450:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2451:     my $items;
                   2452:     foreach my $item (@what) {
                   2453:         $items.=&escape($item).'&';
                   2454:     }
                   2455:     $items=~s/\&$//;
1.70      www      2456:     my %returnhash=();
1.1009    raeburn  2457:     my $uhome = &homeserver($unam,$udom);
                   2458:     unless ($uhome eq 'no_host') {
                   2459:         my @answer=split(/\&/, 
                   2460:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2461:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2462:             return %returnhash;
                   2463:         }
1.1009    raeburn  2464:         my $i;
                   2465:         for ($i=0;$i<=$#what;$i++) {
                   2466: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2467:         }
1.70      www      2468:     }
                   2469:     return %returnhash;
1.1       albertel 2470: }
                   2471: 
1.617     albertel 2472: # ---------------------------------------------------------- Get a studentphoto
                   2473: sub studentphoto {
                   2474:     my ($udom,$unam,$ext) = @_;
                   2475:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2476:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2477:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2478:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2479:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2480:             } else {
                   2481:                 my ($result,$perm_reqd)=
1.707     albertel 2482: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2483:                 if ($result eq 'ok') {
                   2484:                     if (!($perm_reqd eq 'yes')) {
                   2485:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2486:                     }
                   2487:                 }
                   2488:             }
                   2489:         }
                   2490:     } else {
                   2491:         my ($result,$perm_reqd) = 
1.707     albertel 2492: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2493:         if ($result eq 'ok') {
                   2494:             if (!($perm_reqd eq 'yes')) {
                   2495:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2496:             }
                   2497:         }
                   2498:     }
                   2499:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2500: }
                   2501: 
                   2502: sub retrievestudentphoto {
                   2503:     my ($udom,$unam,$ext,$type) = @_;
                   2504:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2505:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2506:     if ($ret eq 'ok') {
                   2507:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2508:         if ($type eq 'thumbnail') {
                   2509:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2510:         }
                   2511:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2512:         return $tokenurl;
                   2513:     } else {
                   2514:         if ($type eq 'thumbnail') {
                   2515:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2516:         } else { 
                   2517:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2518:         }
1.617     albertel 2519:     }
                   2520: }
                   2521: 
1.263     www      2522: # -------------------------------------------------------------------- New chat
                   2523: 
                   2524: sub chatsend {
1.724     raeburn  2525:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2526:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2527:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2528:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2529:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2530: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2531: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2532: }
                   2533: 
                   2534: # ------------------------------------------ Find current version of a resource
                   2535: 
                   2536: sub getversion {
                   2537:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  2538:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2539:     return &currentversion(&filelocation('',$fname));
                   2540: }
                   2541: 
                   2542: sub currentversion {
                   2543:     my $fname=shift;
                   2544:     my $author=$fname;
                   2545:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2546:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2547:     my $home=&homeserver($uname,$udom);
1.292     www      2548:     if ($home eq 'no_host') { 
                   2549:         return -1; 
                   2550:     }
1.1112    www      2551:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2552:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2553: 	return -1;
                   2554:     }
1.1112    www      2555:     return $answer;
1.263     www      2556: }
                   2557: 
1.1111    www      2558: #
                   2559: # Return special version number of resource if set by override, empty otherwise
                   2560: #
                   2561: sub usedversion {
                   2562:     my $fname=shift;
                   2563:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2564:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2565:     if ($urlversion) { return $urlversion; }
                   2566:     return '';
                   2567: }
                   2568: 
1.1       albertel 2569: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2570: 
1.1       albertel 2571: sub subscribe {
                   2572:     my $fname=shift;
1.761     raeburn  2573:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2574:     $fname=~s/[\n\r]//g;
1.1       albertel 2575:     my $author=$fname;
                   2576:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2577:     my ($udom,$uname)=split(/\//,$author);
                   2578:     my $home=homeserver($uname,$udom);
1.335     albertel 2579:     if ($home eq 'no_host') {
                   2580:         return 'not_found';
1.1       albertel 2581:     }
                   2582:     my $answer=reply("sub:$fname",$home);
1.64      www      2583:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2584: 	$answer.=' by '.$home;
                   2585:     }
1.1       albertel 2586:     return $answer;
                   2587: }
                   2588:     
1.8       www      2589: # -------------------------------------------------------------- Replicate file
                   2590: 
                   2591: sub repcopy {
                   2592:     my $filename=shift;
1.23      www      2593:     $filename=~s/\/+/\//g;
1.1142    raeburn  2594:     my $londocroot = $perlvar{'lonDocRoot'};
                   2595:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2596:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2597:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2598: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2599: 	return &repcopy_userfile($filename);
                   2600:     }
1.532     albertel 2601:     $filename=~s/[\n\r]//g;
1.8       www      2602:     my $transname="$filename.in.transfer";
1.828     www      2603: # FIXME: this should flock
1.607     raeburn  2604:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2605:     my $remoteurl=subscribe($filename);
1.64      www      2606:     if ($remoteurl =~ /^con_lost by/) {
                   2607: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2608:            return 'unavailable';
1.8       www      2609:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2610: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2611: 	   return 'not_found';
1.64      www      2612:     } elsif ($remoteurl =~ /^rejected by/) {
                   2613: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2614:            return 'forbidden';
1.20      www      2615:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2616:            return 'ok';
1.8       www      2617:     } else {
1.290     www      2618:         my $author=$filename;
                   2619:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2620:         my ($udom,$uname)=split(/\//,$author);
                   2621:         my $home=homeserver($uname,$udom);
                   2622:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2623:            my @parts=split(/\//,$filename);
                   2624:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2625:            if ($path ne "$londocroot/res") {
1.8       www      2626:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2627: 	       return 'bad_request';
1.8       www      2628:            }
                   2629:            my $count;
                   2630:            for ($count=5;$count<$#parts;$count++) {
                   2631:                $path.="/$parts[$count]";
                   2632:                if ((-e $path)!=1) {
                   2633: 		   mkdir($path,0777);
                   2634:                }
                   2635:            }
                   2636:            my $ua=new LWP::UserAgent;
                   2637:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2638:            my $response=$ua->request($request,$transname);
                   2639:            if ($response->is_error()) {
                   2640: 	       unlink($transname);
                   2641:                my $message=$response->status_line;
1.672     albertel 2642:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2643:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2644:                return 'unavailable';
1.8       www      2645:            } else {
1.16      www      2646: 	       if ($remoteurl!~/\.meta$/) {
                   2647:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2648:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2649:                   if ($mresponse->is_error()) {
                   2650: 		      unlink($filename.'.meta');
                   2651:                       &logthis(
1.672     albertel 2652:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2653:                   }
                   2654: 	       }
1.8       www      2655:                rename($transname,$filename);
1.607     raeburn  2656:                return 'ok';
1.8       www      2657:            }
1.290     www      2658:        }
1.8       www      2659:     }
1.330     www      2660: }
                   2661: 
                   2662: # ------------------------------------------------ Get server side include body
                   2663: sub ssi_body {
1.381     albertel 2664:     my ($filelink,%form)=@_;
1.606     matthew  2665:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2666:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2667:     }
1.953     www      2668:     my $output='';
                   2669:     my $response;
1.980     raeburn  2670:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2671:        ($output,$response)=&externalssi($filelink);
1.953     www      2672:     } else {
1.1004    droeschl 2673:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2674:        $filelink .= 'inhibitmenu=yes';
1.953     www      2675:        ($output,$response)=&ssi($filelink,%form);
                   2676:     }
1.778     albertel 2677:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2678:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2679:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2680:     if (wantarray) {
                   2681:         return ($output, $response);
                   2682:     } else {
                   2683:         return $output;
                   2684:     }
1.8       www      2685: }
                   2686: 
1.15      www      2687: # --------------------------------------------------------- Server Side Include
                   2688: 
1.782     albertel 2689: sub absolute_url {
                   2690:     my ($host_name) = @_;
                   2691:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2692:     if ($host_name eq '') {
                   2693: 	$host_name = $ENV{'SERVER_NAME'};
                   2694:     }
                   2695:     return $protocol.$host_name;
                   2696: }
                   2697: 
1.942     foxr     2698: #
                   2699: #   Server side include.
                   2700: # Parameters:
                   2701: #  fn     Possibly encrypted resource name/id.
                   2702: #  form   Hash that describes how the rendering should be done
                   2703: #         and other things.
1.944     foxr     2704: # Returns:
1.950     raeburn  2705: #   Scalar context: The content of the response.
                   2706: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2707: #     
1.15      www      2708: sub ssi {
                   2709: 
1.944     foxr     2710:     my ($fn,%form)=@_;
1.15      www      2711:     my $ua=new LWP::UserAgent;
1.23      www      2712:     my $request;
1.711     albertel 2713: 
                   2714:     $form{'no_update_last_known'}=1;
1.895     albertel 2715:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2716:     if (%form) {
1.782     albertel 2717:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2718:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2719:     } else {
1.782     albertel 2720:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2721:     }
                   2722: 
1.15      www      2723:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.2  raeburn  2724:     my $response= $ua->request($request);
1.944     foxr     2725:     if (wantarray) {
1.1172.2.3  raeburn  2726: 	return ($response->content, $response);
1.944     foxr     2727:     } else {
1.1172.2.3  raeburn  2728: 	return $response->content;
1.942     foxr     2729:     }
1.324     www      2730: }
                   2731: 
                   2732: sub externalssi {
                   2733:     my ($url)=@_;
                   2734:     my $ua=new LWP::UserAgent;
                   2735:     my $request=new HTTP::Request('GET',$url);
                   2736:     my $response=$ua->request($request);
1.954     raeburn  2737:     if (wantarray) {
                   2738:         return ($response->content, $response);
                   2739:     } else {
                   2740:         return $response->content;
                   2741:     }
1.15      www      2742: }
1.254     www      2743: 
1.492     albertel 2744: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2745: 
                   2746: sub allowuploaded {
                   2747:     my ($srcurl,$url)=@_;
                   2748:     $url=&clutter(&declutter($url));
                   2749:     my $dir=$url;
                   2750:     $dir=~s/\/[^\/]+$//;
                   2751:     my %httpref=();
                   2752:     my $httpurl=&hreflocation('',$url);
                   2753:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2754:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2755: }
1.477     raeburn  2756: 
1.1172.2.13  raeburn  2757: #
                   2758: # Determine if the current user should be able to edit a particular resource,
                   2759: # when viewing in course context.
                   2760: # (a) When viewing resource used to determine if "Edit" item is included in
                   2761: #     Functions.
                   2762: # (b) When displaying folder contents in course editor, used to determine if
                   2763: #     "Edit" link will be displayed alongside resource.
                   2764: #
                   2765: #  input: six args -- filename (decluttered), course number, course domain,
                   2766: #                   url, symb (if registered) and group (if this is a group
                   2767: #                   item -- e.g., bulletin board, group page etc.).
                   2768: #  output: array of five scalars --
                   2769: #          $cfile -- url for file editing if editable on current server
                   2770: #          $home -- homeserver of resource (i.e., for author if published,
                   2771: #                                           or course if uploaded.).
                   2772: #          $switchserver --  1 if server switch will be needed.
                   2773: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   2774: #          $forceview -- 1 if icon/link should be to go to view mode
                   2775: #
                   2776: 
                   2777: sub can_edit_resource {
                   2778:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   2779:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   2780: #
                   2781: # For aboutme pages user can only edit his/her own.
                   2782: #
                   2783:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   2784:         my ($sdom,$sname) = ($1,$2);
                   2785:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   2786:             $home = $env{'user.home'};
                   2787:             $cfile = $resurl;
                   2788:             if ($env{'form.forceedit'}) {
                   2789:                 $forceview = 1;
                   2790:             } else {
                   2791:                 $forceedit = 1;
                   2792:             }
                   2793:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   2794:         } else {
                   2795:             return;
                   2796:         }
                   2797:     }
                   2798: 
                   2799:     if ($env{'request.course.id'}) {
                   2800:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   2801:         if ($group ne '') {
                   2802: # if this is a group homepage or group bulletin board, check group privs
                   2803:             my $allowed = 0;
                   2804:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   2805:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   2806:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   2807:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   2808:                     $allowed = 1;
                   2809:                 }
                   2810:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   2811:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   2812:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   2813:                     $allowed = 1;
                   2814:                 }
                   2815:             }
                   2816:             if ($allowed) {
                   2817:                 $home=&homeserver($cnum,$cdom);
                   2818:                 if ($env{'form.forceedit'}) {
                   2819:                     $forceview = 1;
                   2820:                 } else {
                   2821:                     $forceedit = 1;
                   2822:                 }
                   2823:                 $cfile = $resurl;
                   2824:             } else {
                   2825:                 return;
                   2826:             }
                   2827:         } else {
1.1172.2.15  raeburn  2828:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2829:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   2830:                     return;
                   2831:                 }
                   2832:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  2833: #
                   2834: # No edit allowed where CC has switched to student role.
                   2835: #
                   2836:                 return;
                   2837:             }
                   2838:         }
                   2839:     }
                   2840: 
                   2841:     if ($file ne '') {
                   2842:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   2843:             if (&is_course_upload($file,$cnum,$cdom)) {
                   2844:                 $uploaded = 1;
                   2845:                 $incourse = 1;
                   2846:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   2847:                     $cfile = &hreflocation('',$file);
                   2848:                     if ($env{'form.forceedit'}) {
                   2849:                         $forceview = 1;
                   2850:                     } else {
                   2851:                         $forceedit = 1;
                   2852:                     }
                   2853:                 }
                   2854:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   2855:                 $incourse = 1;
                   2856:                 if ($env{'form.forceedit'}) {
                   2857:                     $forceview = 1;
                   2858:                 } else {
                   2859:                     $forceedit = 1;
                   2860:                 }
                   2861:                 $cfile = $resurl;
                   2862:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   2863:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   2864:                     $incourse = 1;
                   2865:                     if ($env{'form.forceedit'}) {
                   2866:                         $forceview = 1;
                   2867:                     } else {
                   2868:                         $forceedit = 1;
                   2869:                     }
                   2870:                     $cfile = $resurl;
                   2871:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   2872:                     $incourse = 1;
                   2873:                     $cfile = $resurl.'/smpedit';
                   2874:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   2875:                     $incourse = 1;
                   2876:                     if ($env{'form.forceedit'}) {
                   2877:                         $forceview = 1;
                   2878:                     } else {
                   2879:                         $forceedit = 1;
                   2880:                     }
                   2881:                     $cfile = $resurl;
1.1172.2.15  raeburn  2882:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2883:                     $incourse = 1;
                   2884:                     if ($env{'form.forceedit'}) {
                   2885:                         $forceview = 1;
                   2886:                     } else {
                   2887:                         $forceedit = 1;
                   2888:                     }
                   2889:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  2890:                 }
                   2891:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   2892:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   2893:                 if (&is_on_map($template)) {
                   2894:                     $incourse = 1;
                   2895:                     $forceview = 1;
                   2896:                     $cfile = $template;
                   2897:                 }
                   2898:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   2899:                     $incourse = 1;
                   2900:                     if ($env{'form.forceedit'}) {
                   2901:                         $forceview = 1;
                   2902:                     } else {
                   2903:                         $forceedit = 1;
                   2904:                     }
                   2905:                     $cfile = $resurl;
                   2906:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   2907:                 $incourse = 1;
                   2908:                 $forceview = 1;
                   2909:                 if ($symb) {
                   2910:                     my ($map,$id,$res)=&decode_symb($symb);
                   2911:                     $env{'request.symb'} = $symb;
                   2912:                     $cfile = &clutter($res);
                   2913:                 } else {
                   2914:                     $cfile = $env{'form.suppurl'};
                   2915:                     $cfile =~ s{^http://}{};
                   2916:                     $cfile = '/adm/wrapper/ext/'.$cfile;
                   2917:                 }
1.1172.2.31  raeburn  2918:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2919:                 if ($env{'form.forceedit'}) {
                   2920:                     $forceview = 1;
                   2921:                 } else {
                   2922:                     $forceedit = 1;
                   2923:                 }
                   2924:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  2925:             }
                   2926:         }
                   2927:         if ($uploaded || $incourse) {
                   2928:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  2929:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  2930:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   2931:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   2932:             # Check that the user has permission to edit this resource
                   2933:             my $setpriv = 1;
                   2934:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   2935:             if (defined($cfudom)) {
                   2936:                 $home=&homeserver($cfuname,$cfudom);
                   2937:                 $cfile=$file;
                   2938:             }
                   2939:         }
                   2940:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   2941:             (($home ne '') && ($home ne 'no_host'))) {
                   2942:             my @ids=&current_machine_ids();
                   2943:             unless (grep(/^\Q$home\E$/,@ids)) {
                   2944:                 $switchserver=1;
                   2945:             }
                   2946:         }
                   2947:     }
                   2948:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   2949: }
                   2950: 
                   2951: sub is_course_upload {
                   2952:     my ($file,$cnum,$cdom) = @_;
                   2953:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   2954:     $uploadpath =~ s{^\/}{};
                   2955:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   2956:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   2957:         return 1;
                   2958:     }
                   2959:     return;
                   2960: }
                   2961: 
                   2962: sub in_course {
                   2963:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   2964:     if ($hideprivileged) {
                   2965:         my $skipuser;
1.1172.2.23  raeburn  2966:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   2967:         my @possdoms = ($cdom);
                   2968:         if ($coursehash{'checkforpriv'}) {
                   2969:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   2970:         }
                   2971:         if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13  raeburn  2972:             $skipuser = 1;
                   2973:             if ($coursehash{'nothideprivileged'}) {
                   2974:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2975:                     my $user;
                   2976:                     if ($item =~ /:/) {
                   2977:                         $user = $item;
                   2978:                     } else {
                   2979:                         $user = join(':',split(/[\@]/,$item));
                   2980:                     }
                   2981:                     if ($user eq $uname.':'.$udom) {
                   2982:                         undef($skipuser);
                   2983:                         last;
                   2984:                     }
                   2985:                 }
                   2986:             }
                   2987:             if ($skipuser) {
                   2988:                 return 0;
                   2989:             }
                   2990:         }
                   2991:     }
                   2992:     $type ||= 'any';
                   2993:     if (!defined($cdom) || !defined($cnum)) {
                   2994:         my $cid  = $env{'request.course.id'};
                   2995:         $cdom = $env{'course.'.$cid.'.domain'};
                   2996:         $cnum = $env{'course.'.$cid.'.num'};
                   2997:     }
                   2998:     my $typesref;
                   2999:     if (($type eq 'any') || ($type eq 'all')) {
                   3000:         $typesref = ['active','previous','future'];
                   3001:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3002:         $typesref = [$type];
                   3003:     }
                   3004:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3005:                               $typesref,undef,[$cdom]);
                   3006:     my ($tmp) = keys(%roles);
                   3007:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3008:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3009:     if (@course_roles > 0) {
                   3010:         return 1;
                   3011:     }
                   3012:     return 0;
                   3013: }
                   3014: 
1.478     albertel 3015: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3016: # input: action, courseID, current domain, intended
1.637     raeburn  3017: #        path to file, source of file, instruction to parse file for objects,
                   3018: #        ref to hash for embedded objects,
                   3019: #        ref to hash for codebase of java objects.
1.1095    raeburn  3020: #        reference to scalar to accommodate mime type determined
                   3021: #          from File::MMagic if $parser = parse.
1.637     raeburn  3022: #
1.485     raeburn  3023: # output: url to file (if action was uploaddoc), 
                   3024: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3025: #
1.478     albertel 3026: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3027: # course.
1.477     raeburn  3028: #
1.478     albertel 3029: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3030: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3031: #          course's home server.
1.477     raeburn  3032: #
1.478     albertel 3033: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3034: #          be copied from $source (current location) to 
                   3035: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3036: #         and will then be copied to
                   3037: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3038: #         course's home server.
1.485     raeburn  3039: #
1.481     raeburn  3040: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3041: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3042: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3043: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3044: #         in course's home server.
1.637     raeburn  3045: #
1.477     raeburn  3046: 
                   3047: sub process_coursefile {
1.1095    raeburn  3048:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3049:         $mimetype)=@_;
1.477     raeburn  3050:     my $fetchresult;
1.638     albertel 3051:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3052:     if ($action eq 'propagate') {
1.638     albertel 3053:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3054: 			     $home);
1.481     raeburn  3055:     } else {
1.477     raeburn  3056:         my $fpath = '';
                   3057:         my $fname = $file;
1.478     albertel 3058:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3059:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3060:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3061:         if ($action eq 'copy') {
                   3062:             if ($source eq '') {
                   3063:                 $fetchresult = 'no source file';
                   3064:                 return $fetchresult;
                   3065:             } else {
                   3066:                 my $destination = $filepath.'/'.$fname;
                   3067:                 rename($source,$destination);
                   3068:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3069:                                  $home);
1.481     raeburn  3070:             }
                   3071:         } elsif ($action eq 'uploaddoc') {
                   3072:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 3073:             print $fh $env{'form.'.$source};
1.481     raeburn  3074:             close($fh);
1.637     raeburn  3075:             if ($parser eq 'parse') {
1.1024    raeburn  3076:                 my $mm = new File::MMagic;
1.1095    raeburn  3077:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3078:                 if ($type eq 'text/html') {
1.1024    raeburn  3079:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3080:                     unless ($parse_result eq 'ok') {
                   3081:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3082:                     }
1.637     raeburn  3083:                 }
1.1095    raeburn  3084:                 if (ref($mimetype)) {
                   3085:                     $$mimetype = $type;
                   3086:                 } 
1.637     raeburn  3087:             }
1.477     raeburn  3088:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3089:                                  $home);
1.481     raeburn  3090:             if ($fetchresult eq 'ok') {
                   3091:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3092:             } else {
                   3093:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3094:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3095:                 return '/adm/notfound.html';
                   3096:             }
1.477     raeburn  3097:         }
                   3098:     }
1.485     raeburn  3099:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3100:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3101:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3102:     }
                   3103:     return $fetchresult;
                   3104: }
                   3105: 
1.637     raeburn  3106: sub build_filepath {
                   3107:     my ($fpath) = @_;
                   3108:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3109:     unless ($fpath eq '') {
                   3110:         my @parts=split('/',$fpath);
                   3111:         foreach my $part (@parts) {
                   3112:             $filepath.= '/'.$part;
                   3113:             if ((-e $filepath)!=1) {
                   3114:                 mkdir($filepath,0777);
                   3115:             }
                   3116:         }
                   3117:     }
                   3118:     return $filepath;
                   3119: }
                   3120: 
                   3121: sub store_edited_file {
1.638     albertel 3122:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3123:     my $file = $primary_url;
                   3124:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3125:     my $fpath = '';
                   3126:     my $fname = $file;
                   3127:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3128:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3129:     my $filepath = &build_filepath($fpath);
                   3130:     open(my $fh,'>'.$filepath.'/'.$fname);
                   3131:     print $fh $content;
                   3132:     close($fh);
1.638     albertel 3133:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3134:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3135: 			  $home);
1.637     raeburn  3136:     if ($$fetchresult eq 'ok') {
                   3137:         return '/uploaded/'.$fpath.'/'.$fname;
                   3138:     } else {
1.638     albertel 3139:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3140: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3141:         return '/adm/notfound.html';
                   3142:     }
                   3143: }
                   3144: 
1.531     albertel 3145: sub clean_filename {
1.831     albertel 3146:     my ($fname,$args)=@_;
1.315     www      3147: # Replace Windows backslashes by forward slashes
1.257     www      3148:     $fname=~s/\\/\//g;
1.831     albertel 3149:     if (!$args->{'keep_path'}) {
                   3150:         # Get rid of everything but the actual filename
                   3151: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3152:     }
1.315     www      3153: # Replace spaces by underscores
                   3154:     $fname=~s/\s+/\_/g;
                   3155: # Replace all other weird characters by nothing
1.831     albertel 3156:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3157: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3158: # numbers
                   3159:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3160:     return $fname;
                   3161: }
1.1051    raeburn  3162: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3163: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3164: # image with the same aspect ratio as the original, but with dimensions which do 
                   3165: # not exceed $resizewidth and $resizeheight.
                   3166:  
1.984     neumanie 3167: sub resizeImage {
1.1051    raeburn  3168:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3169:     my $ima = Image::Magick->new;
                   3170:     my $resized;
                   3171:     if (-e $img_path) {
                   3172:         $ima->Read($img_path);
                   3173:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3174:             my $width = $ima->Get('width');
                   3175:             my $height = $ima->Get('height');
                   3176:             if ($width > $resizewidth) {
                   3177: 	        my $factor = $width/$resizewidth;
                   3178:                 my $newheight = $height/$factor;
                   3179:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3180:                 $resized = 1;
                   3181:             }
                   3182:         }
                   3183:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3184:             my $width = $ima->Get('width');
                   3185:             my $height = $ima->Get('height');
                   3186:             if ($height > $resizeheight) {
                   3187:                 my $factor = $height/$resizeheight;
                   3188:                 my $newwidth = $width/$factor;
                   3189:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3190:                 $resized = 1;
                   3191:             }
                   3192:         }
                   3193:         if ($resized) {
                   3194:             $ima->Write($img_path);
                   3195:         }
                   3196:     }
                   3197:     return;
1.977     amueller 3198: }
                   3199: 
1.608     albertel 3200: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3201: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3202: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3203: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3204: #                                    canceloverwrite, or ''. 
                   3205: #                   if 'coursedoc': upload to the current course
                   3206: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3207: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3208: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3209: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3210: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3211: #        $allfiles - reference to hash for embedded objects
                   3212: #        $codebase - reference to hash for codebase of java objects
                   3213: #        $desuname - username for permanent storage of uploaded file
                   3214: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3215: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3216: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3217: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3218: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3219: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3220: #                    from File::MMagic.
1.858     raeburn  3221: # 
1.686     albertel 3222: # output: url of file in userspace, or error: <message> 
                   3223: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3224: 
1.531     albertel 3225: sub userfileupload {
1.1090    raeburn  3226:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3227:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3228:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3229:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3230:     $fname=&clean_filename($fname);
1.1090    raeburn  3231:     # See if there is anything left
1.257     www      3232:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3233:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3234:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3235:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3236:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3237:         my $now = time;
1.1090    raeburn  3238:         my $filepath;
1.1095    raeburn  3239:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3240:              $filepath = 'tmp/helprequests/'.$now;
                   3241:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3242:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3243:                          '_'.$env{'user.domain'}.'/pending';
                   3244:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3245:             my ($docuname,$docudom);
                   3246:             if ($destudom) {
                   3247:                 $docudom = $destudom;
                   3248:             } else {
                   3249:                 $docudom = $env{'user.domain'};
                   3250:             }
                   3251:             if ($destuname) {
                   3252:                 $docuname = $destuname;
                   3253:             } else {
                   3254:                 $docuname = $env{'user.name'};
                   3255:             }
                   3256:             if (exists($env{'form.group'})) {
                   3257:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3258:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3259:             }
                   3260:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3261:             if ($context eq 'canceloverwrite') {
                   3262:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3263:                 if (-e  $tempfile) {
                   3264:                     my @info = stat($tempfile);
                   3265:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3266:                         unlink($tempfile);
                   3267:                     }
                   3268:                 }
                   3269:                 return;
1.523     raeburn  3270:             }
                   3271:         }
1.1090    raeburn  3272:         # Create the directory if not present
1.741     raeburn  3273:         my @parts=split(/\//,$filepath);
                   3274:         my $fullpath = $perlvar{'lonDaemons'};
                   3275:         for (my $i=0;$i<@parts;$i++) {
                   3276:             $fullpath .= '/'.$parts[$i];
                   3277:             if ((-e $fullpath)!=1) {
                   3278:                 mkdir($fullpath,0777);
                   3279:             }
                   3280:         }
                   3281:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   3282:         print $fh $env{'form.'.$formname};
                   3283:         close($fh);
1.1090    raeburn  3284:         if ($context eq 'existingfile') {
                   3285:             my @info = stat($fullpath.'/'.$fname);
                   3286:             return ($fullpath.'/'.$fname,$info[9]);
                   3287:         } else {
                   3288:             return $fullpath.'/'.$fname;
                   3289:         }
1.523     raeburn  3290:     }
1.995     raeburn  3291:     if ($subdir eq 'scantron') {
                   3292:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3293:     } else {
1.995     raeburn  3294:         $fname="$subdir/$fname";
                   3295:     }
1.1090    raeburn  3296:     if ($context eq 'coursedoc') {
1.638     albertel 3297: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3298: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3299:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3300:             return &finishuserfileupload($docuname,$docudom,
                   3301: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3302: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3303:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3304:         } else {
1.1172.2.21  raeburn  3305:             if ($env{'form.folder'}) {
                   3306:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3307:             }
1.638     albertel 3308:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3309: 				       $fname,$formname,$parser,
1.1095    raeburn  3310: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3311:         }
1.719     banghart 3312:     } elsif (defined($destuname)) {
                   3313:         my $docuname=$destuname;
                   3314:         my $docudom=$destudom;
1.860     raeburn  3315: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3316: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3317:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3318:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3319:     } else {
1.638     albertel 3320:         my $docuname=$env{'user.name'};
                   3321:         my $docudom=$env{'user.domain'};
1.1172.2.23  raeburn  3322:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3323:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3324:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3325:         }
1.860     raeburn  3326: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3327: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3328:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3329:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3330:     }
1.271     www      3331: }
                   3332: 
                   3333: sub finishuserfileupload {
1.860     raeburn  3334:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3335:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3336:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3337:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3338:   
1.860     raeburn  3339:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3340:     $file=$fname;
                   3341:     if ($fname=~m|/|) {
                   3342:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3343: 	$path.=$fnamepath.'/';
                   3344:     }
1.259     www      3345:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3346:     my $count;
                   3347:     for ($count=4;$count<=$#parts;$count++) {
                   3348:         $filepath.="/$parts[$count]";
                   3349:         if ((-e $filepath)!=1) {
                   3350: 	    mkdir($filepath,0777);
                   3351:         }
                   3352:     }
1.984     neumanie 3353: 
1.258     www      3354: # Save the file
                   3355:     {
1.701     albertel 3356: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   3357: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3358: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3359: 	    return '/adm/notfound.html';
                   3360: 	}
1.1090    raeburn  3361:         if ($context eq 'overwrite') {
1.1117    foxr     3362:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3363:             my $target = $filepath.'/'.$file;
                   3364:             if (-e $source) {
                   3365:                 my @info = stat($source);
                   3366:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3367:                     unless (&File::Copy::move($source,$target)) {
                   3368:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3369:                         return "Moving from $source failed";
                   3370:                     }
                   3371:                 } else {
                   3372:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3373:                 }
                   3374:             } else {
                   3375:                 return "Temporary file: $source missing";
                   3376:             }
                   3377:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3378: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3379: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3380: 	    return '/adm/notfound.html';
                   3381: 	}
1.570     albertel 3382: 	close(FH);
1.1051    raeburn  3383:         if ($resizewidth && $resizeheight) {
                   3384:             my $mm = new File::MMagic;
                   3385:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3386:             if ($mime_type =~ m{^image/}) {
                   3387: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3388:             }  
1.977     amueller 3389: 	}
1.258     www      3390:     }
1.1152    raeburn  3391:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3392:         if (ref($mimetype)) {
                   3393:             if ($$mimetype eq '') {
                   3394:                 my $mm = new File::MMagic;
                   3395:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3396:                 $$mimetype = $type;
                   3397:             }
                   3398:         }
                   3399:     }
1.637     raeburn  3400:     if ($parser eq 'parse') {
1.1152    raeburn  3401:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3402:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3403:                                                        $allfiles,$codebase);
                   3404:             unless ($parse_result eq 'ok') {
                   3405:                 &logthis('Failed to parse '.$filepath.$file.
                   3406: 	   	         ' for embedded media: '.$parse_result); 
                   3407:             }
1.637     raeburn  3408:         }
                   3409:     }
1.860     raeburn  3410:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3411:         my $input = $filepath.'/'.$file;
                   3412:         my $output = $filepath.'/'.'tn-'.$file;
                   3413:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3414:         system("convert -sample $thumbsize $input $output");
                   3415:         if (-e $filepath.'/'.'tn-'.$file) {
                   3416:             $fetchthumb  = 1; 
                   3417:         }
                   3418:     }
1.858     raeburn  3419:  
1.259     www      3420: # Notify homeserver to grep it
                   3421: #
1.984     neumanie 3422:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3423:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3424:     if ($fetchresult eq 'ok') {
1.860     raeburn  3425:         if ($fetchthumb) {
                   3426:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3427:             if ($thumbresult ne 'ok') {
                   3428:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3429:                          $docuhome.': '.$thumbresult);
                   3430:             }
                   3431:         }
1.259     www      3432: #
1.258     www      3433: # Return the URL to it
1.494     albertel 3434:         return '/uploaded/'.$path.$file;
1.263     www      3435:     } else {
1.494     albertel 3436:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3437: 		 ': '.$fetchresult);
1.263     www      3438:         return '/adm/notfound.html';
1.858     raeburn  3439:     }
1.493     albertel 3440: }
                   3441: 
1.637     raeburn  3442: sub extract_embedded_items {
1.961     raeburn  3443:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3444:     my @state = ();
1.1164    raeburn  3445:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3446:     my %javafiles = (
                   3447:                       codebase => '',
                   3448:                       code => '',
                   3449:                       archive => ''
                   3450:                     );
                   3451:     my %mediafiles = (
                   3452:                       src => '',
                   3453:                       movie => '',
                   3454:                      );
1.648     raeburn  3455:     my $p;
                   3456:     if ($content) {
                   3457:         $p = HTML::LCParser->new($content);
                   3458:     } else {
1.961     raeburn  3459:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3460:     }
1.641     albertel 3461:     while (my $t=$p->get_token()) {
1.640     albertel 3462: 	if ($t->[0] eq 'S') {
                   3463: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3464: 	    push(@state, $tagname);
1.648     raeburn  3465:             if (lc($tagname) eq 'allow') {
                   3466:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3467:             }
1.640     albertel 3468: 	    if (lc($tagname) eq 'img') {
                   3469: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3470: 	    }
1.886     albertel 3471: 	    if (lc($tagname) eq 'a') {
1.1172.2.24  raeburn  3472:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
                   3473: 		    &add_filetype($allfiles,$attr->{'href'},'href');
                   3474:                 }
1.886     albertel 3475: 	    }
1.645     raeburn  3476:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3477:                 my $src;
1.645     raeburn  3478:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3479:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3480:                 } else {
1.1164    raeburn  3481:                     if ($attr->{'src'} ne '') {
                   3482:                         $src = $attr->{'src'};
                   3483:                         &add_filetype($allfiles,$src,'src');
                   3484:                     }
                   3485:                 }
                   3486:                 my $text = $p->get_trimmed_text();
                   3487:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3488:                     my @swfargs = split(/,/,$1);
                   3489:                     foreach my $item (@swfargs) {
                   3490:                         $item =~ s/["']//g;
                   3491:                         $item =~ s/^\s+//;
                   3492:                         $item =~ s/\s+$//;
                   3493:                     }
                   3494:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3495:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3496:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3497:                         } else {
                   3498:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3499:                         }
                   3500:                     }
1.645     raeburn  3501:                 }
                   3502:             }
                   3503:             if (lc($tagname) eq 'link') {
                   3504:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3505:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3506:                 }
                   3507:             }
1.640     albertel 3508: 	    if (lc($tagname) eq 'object' ||
                   3509: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3510: 		foreach my $item (keys(%javafiles)) {
                   3511: 		    $javafiles{$item} = '';
                   3512: 		}
1.1164    raeburn  3513:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3514:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3515:                 }
1.640     albertel 3516: 	    }
                   3517: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3518: 		my $name = lc($attr->{'name'});
                   3519: 		foreach my $item (keys(%javafiles)) {
                   3520: 		    if ($name eq $item) {
                   3521: 			$javafiles{$item} = $attr->{'value'};
                   3522: 			last;
                   3523: 		    }
                   3524: 		}
1.1164    raeburn  3525:                 my $pathfrom;
1.640     albertel 3526: 		foreach my $item (keys(%mediafiles)) {
                   3527: 		    if ($name eq $item) {
1.1164    raeburn  3528:                         $pathfrom = $attr->{'value'};
                   3529:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3530: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3531: 			last;
                   3532: 		    }
                   3533: 		}
1.1164    raeburn  3534:                 if ($name eq 'flashvars') {
                   3535:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3536:                 }
                   3537:                 if ($pathfrom ne '') {
                   3538:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3539:                                          $pathfrom);
                   3540:                 }
1.640     albertel 3541: 	    }
                   3542: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3543: 		foreach my $item (keys(%javafiles)) {
                   3544: 		    if ($attr->{$item}) {
                   3545: 			$javafiles{$item} = $attr->{$item};
                   3546: 			last;
                   3547: 		    }
                   3548: 		}
                   3549: 		foreach my $item (keys(%mediafiles)) {
                   3550: 		    if ($attr->{$item}) {
                   3551: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3552: 			last;
                   3553: 		    }
                   3554: 		}
1.1164    raeburn  3555:                 if (lc($tagname) eq 'embed') {
                   3556:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3557:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3558:                                              $attr->{'src'});
                   3559:                     }
                   3560:                 }
1.640     albertel 3561: 	    }
1.1172.2.35  raeburn  3562:             if (lc($tagname) eq 'iframe') {
                   3563:                 my $src = $attr->{'src'} ;
                   3564:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   3565:                     &add_filetype($allfiles,$src,'src');
                   3566:                 } elsif ($src =~ m{^/}) {
                   3567:                     if ($env{'request.course.id'}) {
                   3568:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3569:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3570:                         my $url = &hreflocation('',$fullpath);
                   3571:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   3572:                             my $relpath = $1;
                   3573:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   3574:                                 &add_filetype($allfiles,$1,'src');
                   3575:                             }
                   3576:                         }
                   3577:                     }
                   3578:                 }
                   3579:             }
1.1164    raeburn  3580:             if ($t->[4] =~ m{/>$}) {
1.1172.2.35  raeburn  3581:                 pop(@state);
1.1164    raeburn  3582:             }
1.640     albertel 3583: 	} elsif ($t->[0] eq 'E') {
                   3584: 	    my ($tagname) = ($t->[1]);
                   3585: 	    if ($javafiles{'codebase'} ne '') {
                   3586: 		$javafiles{'codebase'} .= '/';
                   3587: 	    }  
                   3588: 	    if (lc($tagname) eq 'applet' ||
                   3589: 		lc($tagname) eq 'object' ||
                   3590: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3591: 		) {
                   3592: 		foreach my $item (keys(%javafiles)) {
                   3593: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3594: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3595: 			&add_filetype($allfiles,$file,$item);
                   3596: 		    }
                   3597: 		}
                   3598: 	    } 
                   3599: 	    pop @state;
                   3600: 	}
                   3601:     }
1.1164    raeburn  3602:     foreach my $id (sort(keys(%flashvars))) {
                   3603:         if ($shockwave{$id} ne '') {
                   3604:             my @pairs = split(/\&/,$flashvars{$id});
                   3605:             foreach my $pair (@pairs) {
                   3606:                 my ($key,$value) = split(/\=/,$pair);
                   3607:                 if ($key eq 'thumb') {
                   3608:                     &add_filetype($allfiles,$value,$key);
                   3609:                 } elsif ($key eq 'content') {
                   3610:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3611:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3612:                     if ($ext ne '') {
                   3613:                         &add_filetype($allfiles,$path.$value,$ext);
                   3614:                     }
                   3615:                 }
                   3616:             }
                   3617:         }
                   3618:     }
1.637     raeburn  3619:     return 'ok';
                   3620: }
                   3621: 
1.639     albertel 3622: sub add_filetype {
                   3623:     my ($allfiles,$file,$type)=@_;
                   3624:     if (exists($allfiles->{$file})) {
                   3625: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3626: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3627: 	}
                   3628:     } else {
                   3629: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3630:     }
                   3631: }
                   3632: 
1.1164    raeburn  3633: sub embedded_dependency {
                   3634:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3635:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3636:         if (($identifier ne '') &&
                   3637:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3638:             ($pathfrom ne '')) {
                   3639:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3640:             foreach my $dep (@{$related->{$identifier}}) {
                   3641:                 &add_filetype($allfiles,$path.$dep,'object');
                   3642:             }
                   3643:         }
                   3644:     }
                   3645:     return;
                   3646: }
                   3647: 
1.493     albertel 3648: sub removeuploadedurl {
1.984     neumanie 3649:     my ($url)=@_;	
                   3650:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3651:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3652: }
                   3653: 
                   3654: sub removeuserfile {
                   3655:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3656:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3657:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3658:     if ($result eq 'ok') {	
1.798     raeburn  3659:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3660:             my $metafile = $fname.'.meta';
                   3661:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3662: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3663:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3664:             my $sqlresult = 
1.823     albertel 3665:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3666:                                         'portfolio_metadata',$group,
                   3667:                                         'delete');
1.798     raeburn  3668:         }
                   3669:     }
                   3670:     return $result;
1.257     www      3671: }
1.15      www      3672: 
1.530     albertel 3673: sub mkdiruserfile {
                   3674:     my ($docuname,$docudom,$dir)=@_;
                   3675:     my $home=&homeserver($docuname,$docudom);
                   3676:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3677: }
                   3678: 
1.531     albertel 3679: sub renameuserfile {
                   3680:     my ($docuname,$docudom,$old,$new)=@_;
                   3681:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3682:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3683:                         &escape("$old").':'.&escape("$new"),$home);
                   3684:     if ($result eq 'ok') {
                   3685:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3686:             my $oldmeta = $old.'.meta';
                   3687:             my $newmeta = $new.'.meta';
                   3688:             my $metaresult = 
                   3689:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3690: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3691:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3692:             my $sqlresult = 
1.823     albertel 3693:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3694:                                         'portfolio_metadata',$group,
                   3695:                                         'delete');
1.798     raeburn  3696:         }
                   3697:     }
                   3698:     return $result;
1.531     albertel 3699: }
                   3700: 
1.14      www      3701: # ------------------------------------------------------------------------- Log
                   3702: 
                   3703: sub log {
                   3704:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3705:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3706: }
                   3707: 
                   3708: # ------------------------------------------------------------------ Course Log
1.352     www      3709: #
                   3710: # This routine flushes several buffers of non-mission-critical nature
                   3711: #
1.157     www      3712: 
                   3713: sub flushcourselogs {
1.352     www      3714:     &logthis('Flushing log buffers');
                   3715: #
                   3716: # course logs
                   3717: # This is a log of all transactions in a course, which can be used
                   3718: # for data mining purposes
                   3719: #
                   3720: # It also collects the courseid database, which lists last transaction
                   3721: # times and course titles for all courseids
                   3722: #
                   3723:     my %courseidbuffer=();
1.921     raeburn  3724:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3725:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3726: 		          &escape($courselogs{$crsid}),
                   3727: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3728: 	    delete $courselogs{$crsid};
                   3729:         } else {
                   3730:             &logthis('Failed to flush log buffer for '.$crsid);
                   3731:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3732:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3733:                         " exceeded maximum size, deleting.</font>");
                   3734:                delete $courselogs{$crsid};
                   3735:             }
1.352     www      3736:         }
1.920     raeburn  3737:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3738:             'description' => $coursedescrbuf{$crsid},
                   3739:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3740:             'type'        => $coursetypebuf{$crsid},
                   3741:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3742:         };
1.191     harris41 3743:     }
1.352     www      3744: #
                   3745: # Write course id database (reverse lookup) to homeserver of courses 
                   3746: # Is used in pickcourse
                   3747: #
1.840     albertel 3748:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3749:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3750:                                     $courseidbuffer{$crs_home},
                   3751:                                     $crs_home,'timeonly');
1.352     www      3752:     }
                   3753: #
                   3754: # File accesses
                   3755: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3756: #
1.449     matthew  3757:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3758:         if ($entry =~ /___count$/) {
                   3759:             my ($dom,$name);
1.807     albertel 3760:             ($dom,$name,undef)=
1.811     albertel 3761: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3762:             if (! defined($dom) || $dom eq '' || 
                   3763:                 ! defined($name) || $name eq '') {
1.620     albertel 3764:                 my $cid = $env{'request.course.id'};
                   3765:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3766:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3767:             }
1.450     matthew  3768:             my $value = $accesshash{$entry};
                   3769:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   3770:             my %temphash=($url => $value);
1.449     matthew  3771:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   3772:             if ($result eq 'ok') {
                   3773:                 delete $accesshash{$entry};
                   3774:             }
                   3775:         } else {
1.811     albertel 3776:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      3777:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  3778:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3779:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3780:                 delete $accesshash{$entry};
                   3781:             }
1.185     www      3782:         }
1.191     harris41 3783:     }
1.352     www      3784: #
                   3785: # Roles
                   3786: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   3787: #
1.800     albertel 3788:     foreach my $entry (keys(%userrolehash)) {
1.351     www      3789:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      3790: 	    split(/\:/,$entry);
                   3791:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      3792:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      3793:                 $rudom,$runame) eq 'ok') {
                   3794: 	    delete $userrolehash{$entry};
                   3795:         }
                   3796:     }
1.662     raeburn  3797: #
                   3798: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   3799: #
                   3800:     my %domrolebuffer = ();
1.1000    raeburn  3801:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 3802:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  3803:         if ($domrolebuffer{$rudom}) {
                   3804:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   3805:                       '='.&escape($domainrolehash{$entry});
                   3806:         } else {
                   3807:             $domrolebuffer{$rudom}.=&escape($entry).
                   3808:                       '='.&escape($domainrolehash{$entry});
                   3809:         }
                   3810:         delete $domainrolehash{$entry};
                   3811:     }
                   3812:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 3813: 	my %servers = &get_servers($dom,'library');
                   3814: 	foreach my $tryserver (keys(%servers)) {
                   3815: 	    unless (&reply('domroleput:'.$dom.':'.
                   3816: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   3817: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   3818: 	    }
1.662     raeburn  3819:         }
                   3820:     }
1.186     www      3821:     $dumpcount++;
1.157     www      3822: }
                   3823: 
                   3824: sub courselog {
                   3825:     my $what=shift;
1.158     www      3826:     $what=time.':'.$what;
1.620     albertel 3827:     unless ($env{'request.course.id'}) { return ''; }
                   3828:     $coursedombuf{$env{'request.course.id'}}=
                   3829:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3830:     $coursenumbuf{$env{'request.course.id'}}=
                   3831:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   3832:     $coursehombuf{$env{'request.course.id'}}=
                   3833:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   3834:     $coursedescrbuf{$env{'request.course.id'}}=
                   3835:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   3836:     $courseinstcodebuf{$env{'request.course.id'}}=
                   3837:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   3838:     $courseownerbuf{$env{'request.course.id'}}=
                   3839:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  3840:     $coursetypebuf{$env{'request.course.id'}}=
                   3841:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 3842:     if (defined $courselogs{$env{'request.course.id'}}) {
                   3843: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      3844:     } else {
1.620     albertel 3845: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      3846:     }
1.620     albertel 3847:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      3848: 	&flushcourselogs();
                   3849:     }
1.158     www      3850: }
                   3851: 
                   3852: sub courseacclog {
                   3853:     my $fnsymb=shift;
1.620     albertel 3854:     unless ($env{'request.course.id'}) { return ''; }
                   3855:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      3856:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      3857:         $what.=':POST';
1.583     matthew  3858:         # FIXME: Probably ought to escape things....
1.800     albertel 3859: 	foreach my $key (keys(%env)) {
                   3860:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  3861:                 my $formitem = $1;
                   3862:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   3863:                     $what.=':'.$formitem.'='.$env{$key};
                   3864:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   3865:                     $what.=':'.$formitem.'='.$env{$key};
                   3866:                 }
1.158     www      3867:             }
1.191     harris41 3868:         }
1.583     matthew  3869:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   3870:         # FIXME: We should not be depending on a form parameter that someone
                   3871:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 3872:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  3873:             $what.= ':POST';
                   3874:             # FIXME: Probably ought to escape things....
                   3875:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   3876:                                  'crsdiscuss') {
1.620     albertel 3877:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  3878:             }
                   3879:         }
1.158     www      3880:     }
                   3881:     &courselog($what);
1.149     www      3882: }
                   3883: 
1.185     www      3884: sub countacc {
                   3885:     my $url=&declutter(shift);
1.458     matthew  3886:     return if (! defined($url) || $url eq '');
1.620     albertel 3887:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      3888: #
                   3889: # Mark that this url was used in this course
                   3890: #
1.620     albertel 3891:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      3892: #
                   3893: # Increase the access count for this resource in this child process
                   3894: #
1.281     www      3895:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  3896:     $accesshash{$key}++;
1.185     www      3897: }
1.349     www      3898: 
1.361     www      3899: sub linklog {
                   3900:     my ($from,$to)=@_;
                   3901:     $from=&declutter($from);
                   3902:     $to=&declutter($to);
                   3903:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   3904:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   3905: }
1.1160    www      3906: 
                   3907: sub statslog {
                   3908:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   3909:     if ($users<2) { return; }
                   3910:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   3911:             'course'       => $env{'request.course.id'},
                   3912:             'sections'     => '"all"',
                   3913:             'num_students' => $users,
                   3914:             'part'         => $part,
                   3915:             'symb'         => $symb,
                   3916:             'mean_tries'   => $av_attempts,
                   3917:             'deg_of_diff'  => $degdiff});
                   3918:     foreach my $key (keys(%dynstore)) {
                   3919:         $accesshash{$key}=$dynstore{$key};
                   3920:     }
                   3921: }
1.361     www      3922:   
1.349     www      3923: sub userrolelog {
                   3924:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 3925:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      3926:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3927:        $userrolehash
                   3928:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      3929:                     =$tend.':'.$tstart;
1.662     raeburn  3930:     }
1.1169    droeschl 3931:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 3932:        $userrolehash
                   3933:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   3934:                     =$tend.':'.$tstart;
                   3935:     }
1.1169    droeschl 3936:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662     raeburn  3937:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3938:        $domainrolehash
                   3939:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3940:                     = $tend.':'.$tstart;
                   3941:     }
1.351     www      3942: }
                   3943: 
1.957     raeburn  3944: sub courserolelog {
                   3945:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  3946:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3947:         my $cdom = $1;
                   3948:         my $cnum = $2;
                   3949:         my $sec = $3;
                   3950:         my $namespace = 'rolelog';
                   3951:         my %storehash = (
                   3952:                            role    => $trole,
                   3953:                            start   => $tstart,
                   3954:                            end     => $tend,
                   3955:                            selfenroll => $selfenroll,
                   3956:                            context    => $context,
                   3957:                         );
                   3958:         if ($trole eq 'gr') {
                   3959:             $namespace = 'groupslog';
                   3960:             $storehash{'group'} = $sec;
                   3961:         } else {
                   3962:             $storehash{'section'} = $sec;
                   3963:         }
                   3964:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   3965:                    $domain,$cnum,$cdom);
                   3966:         if (($trole ne 'st') || ($sec ne '')) {
                   3967:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  3968:         }
                   3969:     }
                   3970:     return;
                   3971: }
                   3972: 
1.1172.2.9  raeburn  3973: sub domainrolelog {
                   3974:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   3975:     if ($area =~ m{^/($match_domain)/$}) {
                   3976:         my $cdom = $1;
                   3977:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   3978:         my $namespace = 'rolelog';
                   3979:         my %storehash = (
                   3980:                            role    => $trole,
                   3981:                            start   => $tstart,
                   3982:                            end     => $tend,
                   3983:                            context => $context,
                   3984:                         );
                   3985:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   3986:                    $domain,$domconfiguser,$cdom);
                   3987:     }
                   3988:     return;
                   3989: 
                   3990: }
                   3991: 
                   3992: sub coauthorrolelog {
                   3993:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   3994:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   3995:         my $audom = $1;
                   3996:         my $auname = $2;
                   3997:         my $namespace = 'rolelog';
                   3998:         my %storehash = (
                   3999:                            role    => $trole,
                   4000:                            start   => $tstart,
                   4001:                            end     => $tend,
                   4002:                            context => $context,
                   4003:                         );
                   4004:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4005:                    $domain,$auname,$audom);
                   4006:     }
                   4007:     return;
                   4008: }
                   4009: 
1.351     www      4010: sub get_course_adv_roles {
1.948     raeburn  4011:     my ($cid,$codes) = @_;
1.620     albertel 4012:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4013:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4014:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4015:     my %nothide=();
1.800     albertel 4016:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4017:         if ($user !~ /:/) {
                   4018: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4019:         } else {
                   4020:             $nothide{$user}=1;
                   4021:         }
1.470     www      4022:     }
1.1172.2.23  raeburn  4023:     my @possdoms = ($coursehash{'domain'});
                   4024:     if ($coursehash{'checkforpriv'}) {
                   4025:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4026:     }
1.351     www      4027:     my %returnhash=();
                   4028:     my %dumphash=
                   4029:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4030:     my $now=time;
1.997     raeburn  4031:     my %privileged;
1.1000    raeburn  4032:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4033: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4034:         if (($tstart) && ($tstart<0)) { next; }
                   4035:         if (($tend) && ($tend<$now)) { next; }
                   4036:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4037:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4038: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  4039:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4040:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4041: 	if ($role eq 'cr') { next; }
1.948     raeburn  4042:         if ($codes) {
                   4043:             if ($section) { $role .= ':'.$section; }
                   4044:             if ($returnhash{$role}) {
                   4045:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4046:             } else {
                   4047:                 $returnhash{$role}=$username.':'.$domain;
                   4048:             }
1.351     www      4049:         } else {
1.988     raeburn  4050:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4051:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4052:             if ($returnhash{$key}) {
                   4053: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4054:             } else {
                   4055:                 $returnhash{$key}=$username.':'.$domain;
                   4056:             }
1.351     www      4057:         }
1.948     raeburn  4058:     }
1.400     www      4059:     return %returnhash;
                   4060: }
                   4061: 
                   4062: sub get_my_roles {
1.937     raeburn  4063:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4064:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4065:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4066:     my (%dumphash,%nothide);
1.1086    raeburn  4067:     if ($context eq 'userroles') {
1.1166    raeburn  4068:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4069:     } else {
1.1172.2.23  raeburn  4070:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4071:         if ($hidepriv) {
                   4072:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4073:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4074:                 if ($user !~ /:/) {
                   4075:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4076:                 } else {
                   4077:                     $nothide{$user} = 1;
                   4078:                 }
                   4079:             }
                   4080:         }
1.858     raeburn  4081:     }
1.400     www      4082:     my %returnhash=();
                   4083:     my $now=time;
1.999     raeburn  4084:     my %privileged;
1.800     albertel 4085:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4086:         my ($role,$tend,$tstart);
                   4087:         if ($context eq 'userroles') {
1.1149    raeburn  4088:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4089: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4090:         } else {
                   4091:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4092:         }
1.400     www      4093:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4094:         my $status = 'active';
1.939     raeburn  4095:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4096:             $status = 'previous';
                   4097:         } 
                   4098:         if (($tstart) && ($now<$tstart)) {
                   4099:             $status = 'future';
                   4100:         }
                   4101:         if (ref($types) eq 'ARRAY') {
                   4102:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4103:                 next;
                   4104:             } 
                   4105:         } else {
                   4106:             if ($status ne 'active') {
                   4107:                 next;
                   4108:             }
                   4109:         }
1.867     raeburn  4110:         my ($rolecode,$username,$domain,$section,$area);
                   4111:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  4112:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4113:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4114:         } else {
                   4115:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4116:         }
1.832     raeburn  4117:         if (ref($roledoms) eq 'ARRAY') {
                   4118:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4119:                 next;
                   4120:             }
                   4121:         }
                   4122:         if (ref($roles) eq 'ARRAY') {
                   4123:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4124:                 if ($role =~ /^cr\//) {
                   4125:                     if (!grep(/^cr$/,@{$roles})) {
                   4126:                         next;
                   4127:                     }
1.1104    raeburn  4128:                 } elsif ($role =~ /^gr\//) {
                   4129:                     if (!grep(/^gr$/,@{$roles})) {
                   4130:                         next;
                   4131:                     }
1.922     raeburn  4132:                 } else {
                   4133:                     next;
                   4134:                 }
1.832     raeburn  4135:             }
1.867     raeburn  4136:         }
1.937     raeburn  4137:         if ($hidepriv) {
1.1172.2.23  raeburn  4138:             my @privroles = ('dc','su');
1.999     raeburn  4139:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  4140:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4141:             } else {
1.1172.2.23  raeburn  4142:                 my $possdoms = [$domain];
                   4143:                 if (ref($roledoms) eq 'ARRAY') {
                   4144:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  4145:                 }
1.1172.2.23  raeburn  4146:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4147:                     if (!$nothide{$username.':'.$domain}) {
                   4148:                         next;
                   4149:                     }
                   4150:                 }
1.937     raeburn  4151:             }
                   4152:         }
1.933     raeburn  4153:         if ($withsec) {
                   4154:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4155:                 $tstart.':'.$tend;
                   4156:         } else {
                   4157:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4158:         }
1.832     raeburn  4159:     }
1.373     www      4160:     return %returnhash;
1.399     www      4161: }
                   4162: 
                   4163: # ----------------------------------------------------- Frontpage Announcements
                   4164: #
                   4165: #
                   4166: 
                   4167: sub postannounce {
                   4168:     my ($server,$text)=@_;
1.844     albertel 4169:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4170:     unless ($text=~/\w/) { $text=''; }
                   4171:     return &reply('setannounce:'.&escape($text),$server);
                   4172: }
                   4173: 
                   4174: sub getannounce {
1.448     albertel 4175: 
                   4176:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4177: 	my $announcement='';
1.800     albertel 4178: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4179: 	close($fh);
1.399     www      4180: 	if ($announcement=~/\w/) { 
                   4181: 	    return 
                   4182:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4183:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4184: 	} else {
                   4185: 	    return '';
                   4186: 	}
                   4187:     } else {
                   4188: 	return '';
                   4189:     }
1.351     www      4190: }
1.353     www      4191: 
                   4192: # ---------------------------------------------------------- Course ID routines
                   4193: # Deal with domain's nohist_courseid.db files
                   4194: #
                   4195: 
                   4196: sub courseidput {
1.921     raeburn  4197:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4198:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4199:     my $outcome;
                   4200:     if ($caller eq 'timeonly') {
                   4201:         my $cids = '';
                   4202:         foreach my $item (keys(%$storehash)) {
                   4203:             $cids.=&escape($item).'&';
                   4204:         }
                   4205:         $cids=~s/\&$//;
                   4206:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4207:                           $coursehome);       
                   4208:     } else {
                   4209:         my $items = '';
                   4210:         foreach my $item (keys(%$storehash)) {
                   4211:             $items.= &escape($item).'='.
                   4212:                      &freeze_escape($$storehash{$item}).'&';
                   4213:         }
                   4214:         $items=~s/\&$//;
                   4215:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4216:                           $coursehome);
1.918     raeburn  4217:     }
                   4218:     if ($outcome eq 'unknown_cmd') {
                   4219:         my $what;
                   4220:         foreach my $cid (keys(%$storehash)) {
                   4221:             $what .= &escape($cid).'=';
1.921     raeburn  4222:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4223:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4224:             }
                   4225:             $what =~ s/\:$/&/;
                   4226:         }
                   4227:         $what =~ s/\&$//;  
                   4228:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4229:     } else {
                   4230:         return $outcome;
                   4231:     }
1.353     www      4232: }
                   4233: 
                   4234: sub courseiddump {
1.921     raeburn  4235:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4236:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4237:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38  raeburn  4238:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
                   4239:         $hasuniquecode)=@_;
1.918     raeburn  4240:     my $as_hash = 1;
                   4241:     my %returnhash;
                   4242:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4243:     my %libserv = &all_library();
                   4244:     foreach my $tryserver (keys(%libserv)) {
                   4245:         if ( (  $hostidflag == 1 
                   4246: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4247: 	     || (!defined($hostidflag)) ) {
                   4248: 
1.918     raeburn  4249: 	    if (($domfilter eq '') ||
                   4250: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  4251:                 my $rep;
                   4252:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   4253:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   4254:                         join(":", (&host_domain($tryserver), $sincefilter,
                   4255:                                 &escape($descfilter), &escape($instcodefilter),
                   4256:                                 &escape($ownerfilter), &escape($coursefilter),
                   4257:                                 &escape($typefilter), &escape($regexp_ok),
                   4258:                                 $as_hash, &escape($selfenrollonly),
                   4259:                                 &escape($catfilter), $showhidden, $caller,
                   4260:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   4261:                                 &escape($createdbefore), &escape($createdafter),
1.1172.2.38  raeburn  4262:                                 &escape($creationcontext), $domcloner, $hasuniquecode)));
1.1172.2.22  raeburn  4263:                 } else {
                   4264:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4265:                              $sincefilter.':'.&escape($descfilter).':'.
                   4266:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   4267:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   4268:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   4269:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   4270:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   4271:                              &escape($cc_clone).':'.$cloneonly.':'.
                   4272:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.38  raeburn  4273:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode,
1.1172.2.22  raeburn  4274:                              $tryserver);
                   4275:                 }
                   4276: 
1.918     raeburn  4277:                 my @pairs=split(/\&/,$rep);
                   4278:                 foreach my $item (@pairs) {
                   4279:                     my ($key,$value)=split(/\=/,$item,2);
                   4280:                     $key = &unescape($key);
                   4281:                     next if ($key =~ /^error: 2 /);
                   4282:                     my $result = &thaw_unescape($value);
                   4283:                     if (ref($result) eq 'HASH') {
                   4284:                         $returnhash{$key}=$result;
                   4285:                     } else {
1.921     raeburn  4286:                         my @responses = split(/:/,$value);
                   4287:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4288:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4289:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4290:                         }
1.1008    raeburn  4291:                     }
1.353     www      4292:                 }
                   4293:             }
                   4294:         }
                   4295:     }
                   4296:     return %returnhash;
                   4297: }
                   4298: 
1.1055    raeburn  4299: sub courselastaccess {
                   4300:     my ($cdom,$cnum,$hostidref) = @_;
                   4301:     my %returnhash;
                   4302:     if ($cdom && $cnum) {
                   4303:         my $chome = &homeserver($cnum,$cdom);
                   4304:         if ($chome ne 'no_host') {
                   4305:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4306:             &extract_lastaccess(\%returnhash,$rep);
                   4307:         }
                   4308:     } else {
                   4309:         if (!$cdom) { $cdom=''; }
                   4310:         my %libserv = &all_library();
                   4311:         foreach my $tryserver (keys(%libserv)) {
                   4312:             if (ref($hostidref) eq 'ARRAY') {
                   4313:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4314:             } 
                   4315:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4316:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4317:                 &extract_lastaccess(\%returnhash,$rep);
                   4318:             }
                   4319:         }
                   4320:     }
                   4321:     return %returnhash;
                   4322: }
                   4323: 
                   4324: sub extract_lastaccess {
                   4325:     my ($returnhash,$rep) = @_;
                   4326:     if (ref($returnhash) eq 'HASH') {
                   4327:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4328:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4329:                  $rep eq '') {
                   4330:             my @pairs=split(/\&/,$rep);
                   4331:             foreach my $item (@pairs) {
                   4332:                 my ($key,$value)=split(/\=/,$item,2);
                   4333:                 $key = &unescape($key);
                   4334:                 next if ($key =~ /^error: 2 /);
                   4335:                 $returnhash->{$key} = &thaw_unescape($value);
                   4336:             }
                   4337:         }
                   4338:     }
                   4339:     return;
                   4340: }
                   4341: 
1.658     raeburn  4342: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4343: 
                   4344: sub dcmailput {
1.685     raeburn  4345:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4346:     my $status = &Apache::lonnet::critical(
1.740     www      4347:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4348:        &escape($message),$server);
1.662     raeburn  4349:     return $status;
                   4350: }
                   4351: 
1.658     raeburn  4352: sub dcmaildump {
                   4353:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4354:     my %returnhash=();
1.846     albertel 4355: 
                   4356:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4357:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4358:                                                          &escape($enddate).':';
                   4359: 	my @esc_senders=map { &escape($_)} @$senders;
                   4360: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4361: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4362:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4363:             if (($key) && ($value)) {
                   4364:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4365:             }
                   4366:         }
                   4367:     }
                   4368:     return %returnhash;
                   4369: }
1.662     raeburn  4370: # ---------------------------------------------------------- Domain roles
                   4371: 
                   4372: sub get_domain_roles {
                   4373:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4374:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4375:         $startdate = '.';
                   4376:     }
1.1018    raeburn  4377:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4378:         $enddate = '.';
                   4379:     }
1.922     raeburn  4380:     my $rolelist;
                   4381:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  4382:         $rolelist = join('&',@{$roles});
1.922     raeburn  4383:     }
1.662     raeburn  4384:     my %personnel = ();
1.841     albertel 4385: 
                   4386:     my %servers = &get_servers($dom,'library');
                   4387:     foreach my $tryserver (keys(%servers)) {
                   4388: 	%{$personnel{$tryserver}}=();
                   4389: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4390: 					    &escape($startdate).':'.
                   4391: 					    &escape($enddate).':'.
                   4392: 					    &escape($rolelist), $tryserver))) {
                   4393: 	    my ($key,$value) = split(/\=/,$line,2);
                   4394: 	    if (($key) && ($value)) {
                   4395: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4396: 	    }
                   4397: 	}
1.662     raeburn  4398:     }
                   4399:     return %personnel;
                   4400: }
1.658     raeburn  4401: 
1.1057    www      4402: # ----------------------------------------------------------- Interval timing 
1.149     www      4403: 
1.1153    www      4404: {
                   4405: # Caches needed for speedup of navmaps
                   4406: # We don't want to cache this for very long at all (5 seconds at most)
                   4407: # 
                   4408: # The user for whom we cache
                   4409: my $cachedkey='';
                   4410: # The cached times for this user
                   4411: my %cachedtimes=();
                   4412: # When this was last done
                   4413: my $cachedtime=();
                   4414: 
                   4415: sub load_all_first_access {
1.1154    raeburn  4416:     my ($uname,$udom)=@_;
1.1156    www      4417:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2  raeburn  4418:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  4419:         return;
                   4420:     }
                   4421:     $cachedtime=time;
                   4422:     $cachedkey=$uname.':'.$udom;
                   4423:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4424: }
                   4425: 
1.504     albertel 4426: sub get_first_access {
1.1162    raeburn  4427:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 4428:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4429:     if ($argsymb) { $symb=$argsymb; }
                   4430:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4431:     if ($argmap) { $map = $argmap; }
1.926     albertel 4432:     if ($type eq 'course') {
                   4433: 	$res='course';
                   4434:     } elsif ($type eq 'map') {
1.588     albertel 4435: 	$res=&symbread($map);
                   4436:     } else {
                   4437: 	$res=$symb;
                   4438:     }
1.1153    www      4439:     &load_all_first_access($uname,$udom);
                   4440:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4441: }
                   4442: 
                   4443: sub set_first_access {
1.1162    raeburn  4444:     my ($type,$interval)=@_;
1.790     albertel 4445:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4446:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4447:     if ($type eq 'course') {
                   4448: 	$res='course';
                   4449:     } elsif ($type eq 'map') {
1.588     albertel 4450: 	$res=&symbread($map);
                   4451:     } else {
                   4452: 	$res=$symb;
                   4453:     }
1.1153    www      4454:     $cachedkey='';
1.1162    raeburn  4455:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4456:     if (!$firstaccess) {
1.1162    raeburn  4457:         my $start = time;
                   4458: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4459:                           $udom,$uname);
                   4460:         if ($putres eq 'ok') {
                   4461:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4462:                  $udom,$uname); 
                   4463:             &appenv(
                   4464:                      {
                   4465:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4466:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4467:                      }
                   4468:                   );
                   4469:         }
                   4470:         return $putres;
1.505     albertel 4471:     }
                   4472:     return 'already_set';
1.504     albertel 4473: }
1.1153    www      4474: }
1.1172.2.32  raeburn  4475: 
                   4476: sub checkout {
                   4477:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   4478:     my $now=time;
                   4479:     my $lonhost=$perlvar{'lonHostID'};
                   4480:     my $infostr=&escape(
                   4481:                  'CHECKOUTTOKEN&'.
                   4482:                  $tuname.'&'.
                   4483:                  $tudom.'&'.
                   4484:                  $tcrsid.'&'.
                   4485:                  $symb.'&'.
                   4486:                  $now.'&'.$ENV{'REMOTE_ADDR'});
                   4487:     my $token=&reply('tmpput:'.$infostr,$lonhost);
                   4488:     if ($token=~/^error\:/) {
                   4489:         &logthis("<font color=\"blue\">WARNING: ".
                   4490:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   4491:                  "</font>");
                   4492:         return '';
                   4493:     }
                   4494: 
                   4495:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   4496:     $token=~tr/a-z/A-Z/;
                   4497: 
                   4498:     my %infohash=('resource.0.outtoken' => $token,
                   4499:                   'resource.0.checkouttime' => $now,
                   4500:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
                   4501: 
                   4502:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   4503:        return '';
                   4504:     } else {
                   4505:         &logthis("<font color=\"blue\">WARNING: ".
                   4506:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   4507:                  "</font>");
                   4508:     }
                   4509: 
                   4510:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   4511:                          &escape('Checkout '.$infostr.' - '.
                   4512:                                                  $token)) ne 'ok') {
                   4513:         return '';
                   4514:     } else {
                   4515:         &logthis("<font color=\"blue\">WARNING: ".
                   4516:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   4517:                  "</font>");
                   4518:     }
                   4519:     return $token;
                   4520: }
                   4521: 
                   4522: # ------------------------------------------------------------ Check in an item
                   4523: 
                   4524: sub checkin {
                   4525:     my $token=shift;
                   4526:     my $now=time;
                   4527:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   4528:     $lonhost=~tr/A-Z/a-z/;
                   4529:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
                   4530:     $dtoken=~s/\W/\_/g;
                   4531:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                   4532:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   4533: 
                   4534:     unless (($tuname) && ($tudom)) {
                   4535:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   4536:         return '';
                   4537:     }
                   4538: 
                   4539:     unless (&allowed('mgr',$tcrsid)) {
                   4540:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   4541:                  $env{'user.name'}.' - '.$env{'user.domain'});
                   4542:         return '';
                   4543:     }
                   4544: 
                   4545:     my %infohash=('resource.0.intoken' => $token,
                   4546:                   'resource.0.checkintime' => $now,
                   4547:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
                   4548: 
                   4549:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   4550:        return '';
                   4551:     }
                   4552: 
                   4553:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   4554:                          &escape('Checkin - '.$token)) ne 'ok') {
                   4555:         return '';
                   4556:     }
                   4557: 
                   4558:     return ($symb,$tuname,$tudom,$tcrsid);
                   4559: }
                   4560: 
1.110     www      4561: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4562: 
                   4563: sub expirespread {
                   4564:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4565:     my $cid=$env{'request.course.id'}; 
1.110     www      4566:     if ($cid) {
                   4567:        my $now=time;
                   4568:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4569:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4570:                             $env{'course.'.$cid.'.num'}.
1.110     www      4571: 	        	    ':nohist_expirationdates:'.
                   4572:                             &escape($key).'='.$now,
1.620     albertel 4573:                             $env{'course.'.$cid.'.home'})
1.110     www      4574:     }
                   4575:     return 'ok';
1.14      www      4576: }
                   4577: 
1.109     www      4578: # ----------------------------------------------------- Devalidate Spreadsheets
                   4579: 
                   4580: sub devalidate {
1.325     www      4581:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4582:     my $cid=$env{'request.course.id'}; 
1.109     www      4583:     if ($cid) {
1.391     matthew  4584:         # delete the stored spreadsheets for
                   4585:         # - the student level sheet of this user in course's homespace
                   4586:         # - the assessment level sheet for this resource 
                   4587:         #   for this user in user's homespace
1.553     albertel 4588: 	# - current conditional state info
1.325     www      4589: 	my $key=$uname.':'.$udom.':';
1.109     www      4590:         my $status=
1.299     matthew  4591: 	    &del('nohist_calculatedsheets',
1.391     matthew  4592: 		 [$key.'studentcalc:'],
1.620     albertel 4593: 		 $env{'course.'.$cid.'.domain'},
                   4594: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4595: 		.' '.
                   4596: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4597: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4598:         unless ($status eq 'ok ok') {
                   4599:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4600:                     $uname.' at '.$udom.' for '.
1.109     www      4601: 		    $symb.': '.$status);
1.133     albertel 4602:         }
1.553     albertel 4603: 	&delenv('user.state.'.$cid);
1.109     www      4604:     }
                   4605: }
                   4606: 
1.265     albertel 4607: sub get_scalar {
                   4608:     my ($string,$end) = @_;
                   4609:     my $value;
                   4610:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4611: 	$value = $1;
                   4612:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4613: 	$value = $1;
                   4614:     }
                   4615:     return &unescape($value);
                   4616: }
                   4617: 
                   4618: sub array2str {
                   4619:   my (@array) = @_;
                   4620:   my $result=&arrayref2str(\@array);
                   4621:   $result=~s/^__ARRAY_REF__//;
                   4622:   $result=~s/__END_ARRAY_REF__$//;
                   4623:   return $result;
                   4624: }
                   4625: 
1.204     albertel 4626: sub arrayref2str {
                   4627:   my ($arrayref) = @_;
1.265     albertel 4628:   my $result='__ARRAY_REF__';
1.204     albertel 4629:   foreach my $elem (@$arrayref) {
1.265     albertel 4630:     if(ref($elem) eq 'ARRAY') {
                   4631:       $result.=&arrayref2str($elem).'&';
                   4632:     } elsif(ref($elem) eq 'HASH') {
                   4633:       $result.=&hashref2str($elem).'&';
                   4634:     } elsif(ref($elem)) {
                   4635:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4636:     } else {
                   4637:       $result.=&escape($elem).'&';
                   4638:     }
                   4639:   }
                   4640:   $result=~s/\&$//;
1.265     albertel 4641:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4642:   return $result;
                   4643: }
                   4644: 
1.168     albertel 4645: sub hash2str {
1.204     albertel 4646:   my (%hash) = @_;
                   4647:   my $result=&hashref2str(\%hash);
1.265     albertel 4648:   $result=~s/^__HASH_REF__//;
                   4649:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4650:   return $result;
                   4651: }
                   4652: 
                   4653: sub hashref2str {
                   4654:   my ($hashref)=@_;
1.265     albertel 4655:   my $result='__HASH_REF__';
1.800     albertel 4656:   foreach my $key (sort(keys(%$hashref))) {
                   4657:     if (ref($key) eq 'ARRAY') {
                   4658:       $result.=&arrayref2str($key).'=';
                   4659:     } elsif (ref($key) eq 'HASH') {
                   4660:       $result.=&hashref2str($key).'=';
                   4661:     } elsif (ref($key)) {
1.265     albertel 4662:       $result.='=';
1.800     albertel 4663:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 4664:     } else {
1.1132    raeburn  4665: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 4666:     }
                   4667: 
1.800     albertel 4668:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   4669:       $result.=&arrayref2str($hashref->{$key}).'&';
                   4670:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   4671:       $result.=&hashref2str($hashref->{$key}).'&';
                   4672:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4673:        $result.='&';
1.800     albertel 4674:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4675:     } else {
1.800     albertel 4676:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4677:     }
                   4678:   }
1.168     albertel 4679:   $result=~s/\&$//;
1.265     albertel 4680:   $result .= '__END_HASH_REF__';
1.168     albertel 4681:   return $result;
                   4682: }
                   4683: 
                   4684: sub str2hash {
1.265     albertel 4685:     my ($string)=@_;
                   4686:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4687:     return %$hash;
                   4688: }
                   4689: 
                   4690: sub str2hashref {
1.168     albertel 4691:   my ($string) = @_;
1.265     albertel 4692: 
                   4693:   my %hash;
                   4694: 
                   4695:   if($string !~ /^__HASH_REF__/) {
                   4696:       if (! ($string eq '' || !defined($string))) {
                   4697: 	  $hash{'error'}='Not hash reference';
                   4698:       }
                   4699:       return (\%hash, $string);
                   4700:   }
                   4701: 
                   4702:   $string =~ s/^__HASH_REF__//;
                   4703: 
                   4704:   while($string !~ /^__END_HASH_REF__/) {
                   4705:       #key
                   4706:       my $key='';
                   4707:       if($string =~ /^__HASH_REF__/) {
                   4708:           ($key, $string)=&str2hashref($string);
                   4709:           if(defined($key->{'error'})) {
                   4710:               $hash{'error'}='Bad data';
                   4711:               return (\%hash, $string);
                   4712:           }
                   4713:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4714:           ($key, $string)=&str2arrayref($string);
                   4715:           if($key->[0] eq 'Array reference error') {
                   4716:               $hash{'error'}='Bad data';
                   4717:               return (\%hash, $string);
                   4718:           }
                   4719:       } else {
                   4720:           $string =~ s/^(.*?)=//;
1.267     albertel 4721: 	  $key=&unescape($1);
1.265     albertel 4722:       }
                   4723:       $string =~ s/^=//;
                   4724: 
                   4725:       #value
                   4726:       my $value='';
                   4727:       if($string =~ /^__HASH_REF__/) {
                   4728:           ($value, $string)=&str2hashref($string);
                   4729:           if(defined($value->{'error'})) {
                   4730:               $hash{'error'}='Bad data';
                   4731:               return (\%hash, $string);
                   4732:           }
                   4733:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4734:           ($value, $string)=&str2arrayref($string);
                   4735:           if($value->[0] eq 'Array reference error') {
                   4736:               $hash{'error'}='Bad data';
                   4737:               return (\%hash, $string);
                   4738:           }
                   4739:       } else {
                   4740: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4741:       }
                   4742:       $string =~ s/^&//;
                   4743: 
                   4744:       $hash{$key}=$value;
1.204     albertel 4745:   }
1.265     albertel 4746: 
                   4747:   $string =~ s/^__END_HASH_REF__//;
                   4748: 
                   4749:   return (\%hash, $string);
1.204     albertel 4750: }
                   4751: 
                   4752: sub str2array {
1.265     albertel 4753:     my ($string)=@_;
                   4754:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4755:     return @$array;
                   4756: }
                   4757: 
                   4758: sub str2arrayref {
1.204     albertel 4759:   my ($string) = @_;
1.265     albertel 4760:   my @array;
                   4761: 
                   4762:   if($string !~ /^__ARRAY_REF__/) {
                   4763:       if (! ($string eq '' || !defined($string))) {
                   4764: 	  $array[0]='Array reference error';
                   4765:       }
                   4766:       return (\@array, $string);
                   4767:   }
                   4768: 
                   4769:   $string =~ s/^__ARRAY_REF__//;
                   4770: 
                   4771:   while($string !~ /^__END_ARRAY_REF__/) {
                   4772:       my $value='';
                   4773:       if($string =~ /^__HASH_REF__/) {
                   4774:           ($value, $string)=&str2hashref($string);
                   4775:           if(defined($value->{'error'})) {
                   4776:               $array[0] ='Array reference error';
                   4777:               return (\@array, $string);
                   4778:           }
                   4779:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4780:           ($value, $string)=&str2arrayref($string);
                   4781:           if($value->[0] eq 'Array reference error') {
                   4782:               $array[0] ='Array reference error';
                   4783:               return (\@array, $string);
                   4784:           }
                   4785:       } else {
                   4786: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   4787:       }
                   4788:       $string =~ s/^&//;
                   4789: 
                   4790:       push(@array, $value);
1.191     harris41 4791:   }
1.265     albertel 4792: 
                   4793:   $string =~ s/^__END_ARRAY_REF__//;
                   4794: 
                   4795:   return (\@array, $string);
1.168     albertel 4796: }
                   4797: 
1.167     albertel 4798: # -------------------------------------------------------------------Temp Store
                   4799: 
1.168     albertel 4800: sub tmpreset {
                   4801:   my ($symb,$namespace,$domain,$stuname) = @_;
                   4802:   if (!$symb) {
                   4803:     $symb=&symbread();
1.620     albertel 4804:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4805:   }
                   4806:   $symb=escape($symb);
                   4807: 
1.620     albertel 4808:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 4809:   $namespace=~s/\//\_/g;
                   4810:   $namespace=~s/\W//g;
                   4811: 
1.620     albertel 4812:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4813:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4814:   if ($domain eq 'public' && $stuname eq 'public') {
                   4815:       $stuname=$ENV{'REMOTE_ADDR'};
                   4816:   }
1.1117    foxr     4817:   my $path=LONCAPA::tempdir();
1.168     albertel 4818:   my %hash;
                   4819:   if (tie(%hash,'GDBM_File',
                   4820: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4821: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  4822:     foreach my $key (keys(%hash)) {
1.180     albertel 4823:       if ($key=~ /:$symb/) {
1.168     albertel 4824: 	delete($hash{$key});
                   4825:       }
                   4826:     }
                   4827:   }
                   4828: }
                   4829: 
1.167     albertel 4830: sub tmpstore {
1.168     albertel 4831:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4832: 
                   4833:   if (!$symb) {
                   4834:     $symb=&symbread();
1.620     albertel 4835:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4836:   }
                   4837:   $symb=escape($symb);
                   4838: 
                   4839:   if (!$namespace) {
                   4840:     # I don't think we would ever want to store this for a course.
                   4841:     # it seems this will only be used if we don't have a course.
1.620     albertel 4842:     #$namespace=$env{'request.course.id'};
1.168     albertel 4843:     #if (!$namespace) {
1.620     albertel 4844:       $namespace=$env{'request.state'};
1.168     albertel 4845:     #}
                   4846:   }
                   4847:   $namespace=~s/\//\_/g;
                   4848:   $namespace=~s/\W//g;
1.620     albertel 4849:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4850:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4851:   if ($domain eq 'public' && $stuname eq 'public') {
                   4852:       $stuname=$ENV{'REMOTE_ADDR'};
                   4853:   }
1.168     albertel 4854:   my $now=time;
                   4855:   my %hash;
1.1117    foxr     4856:   my $path=LONCAPA::tempdir();
1.168     albertel 4857:   if (tie(%hash,'GDBM_File',
                   4858: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4859: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 4860:     $hash{"version:$symb"}++;
                   4861:     my $version=$hash{"version:$symb"};
                   4862:     my $allkeys=''; 
                   4863:     foreach my $key (keys(%$storehash)) {
                   4864:       $allkeys.=$key.':';
1.591     albertel 4865:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 4866:     }
                   4867:     $hash{"$version:$symb:timestamp"}=$now;
                   4868:     $allkeys.='timestamp';
                   4869:     $hash{"$version:keys:$symb"}=$allkeys;
                   4870:     if (untie(%hash)) {
                   4871:       return 'ok';
                   4872:     } else {
                   4873:       return "error:$!";
                   4874:     }
                   4875:   } else {
                   4876:     return "error:$!";
                   4877:   }
                   4878: }
1.167     albertel 4879: 
1.168     albertel 4880: # -----------------------------------------------------------------Temp Restore
1.167     albertel 4881: 
1.168     albertel 4882: sub tmprestore {
                   4883:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 4884: 
1.168     albertel 4885:   if (!$symb) {
                   4886:     $symb=&symbread();
1.620     albertel 4887:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4888:   }
                   4889:   $symb=escape($symb);
                   4890: 
1.620     albertel 4891:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 4892: 
1.620     albertel 4893:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4894:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4895:   if ($domain eq 'public' && $stuname eq 'public') {
                   4896:       $stuname=$ENV{'REMOTE_ADDR'};
                   4897:   }
1.168     albertel 4898:   my %returnhash;
                   4899:   $namespace=~s/\//\_/g;
                   4900:   $namespace=~s/\W//g;
                   4901:   my %hash;
1.1117    foxr     4902:   my $path=LONCAPA::tempdir();
1.168     albertel 4903:   if (tie(%hash,'GDBM_File',
                   4904: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4905: 	  &GDBM_READER(),0640)) {
1.168     albertel 4906:     my $version=$hash{"version:$symb"};
                   4907:     $returnhash{'version'}=$version;
                   4908:     my $scope;
                   4909:     for ($scope=1;$scope<=$version;$scope++) {
                   4910:       my $vkeys=$hash{"$scope:keys:$symb"};
                   4911:       my @keys=split(/:/,$vkeys);
                   4912:       my $key;
                   4913:       $returnhash{"$scope:keys"}=$vkeys;
                   4914:       foreach $key (@keys) {
1.591     albertel 4915: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   4916: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 4917:       }
                   4918:     }
1.168     albertel 4919:     if (!(untie(%hash))) {
                   4920:       return "error:$!";
                   4921:     }
                   4922:   } else {
                   4923:     return "error:$!";
                   4924:   }
                   4925:   return %returnhash;
1.167     albertel 4926: }
                   4927: 
1.9       www      4928: # ----------------------------------------------------------------------- Store
                   4929: 
                   4930: sub store {
1.124     www      4931:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4932:     my $home='';
                   4933: 
1.168     albertel 4934:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4935: 
1.213     www      4936:     $symb=&symbclean($symb);
1.122     albertel 4937:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4938: 
1.620     albertel 4939:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4940:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4941: 
                   4942:     &devalidate($symb,$stuname,$domain);
1.109     www      4943: 
                   4944:     $symb=escape($symb);
1.187     www      4945:     if (!$namespace) { 
1.620     albertel 4946:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4947:           return ''; 
                   4948:        } 
                   4949:     }
1.620     albertel 4950:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4951: 
                   4952:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4953:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   4954: 
1.12      www      4955:     my $namevalue='';
1.800     albertel 4956:     foreach my $key (keys(%$storehash)) {
                   4957:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4958:     }
1.12      www      4959:     $namevalue=~s/\&$//;
1.187     www      4960:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      4961:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      4962: }
                   4963: 
1.47      www      4964: # -------------------------------------------------------------- Critical Store
                   4965: 
                   4966: sub cstore {
1.124     www      4967:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4968:     my $home='';
                   4969: 
1.168     albertel 4970:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4971: 
1.213     www      4972:     $symb=&symbclean($symb);
1.122     albertel 4973:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4974: 
1.620     albertel 4975:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4976:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4977: 
                   4978:     &devalidate($symb,$stuname,$domain);
1.109     www      4979: 
                   4980:     $symb=escape($symb);
1.187     www      4981:     if (!$namespace) { 
1.620     albertel 4982:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4983:           return ''; 
                   4984:        } 
                   4985:     }
1.620     albertel 4986:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4987: 
                   4988:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4989:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 4990: 
1.47      www      4991:     my $namevalue='';
1.800     albertel 4992:     foreach my $key (keys(%$storehash)) {
                   4993:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4994:     }
1.47      www      4995:     $namevalue=~s/\&$//;
1.187     www      4996:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      4997:     return critical
                   4998:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      4999: }
                   5000: 
1.9       www      5001: # --------------------------------------------------------------------- Restore
                   5002: 
                   5003: sub restore {
1.124     www      5004:     my ($symb,$namespace,$domain,$stuname) = @_;
                   5005:     my $home='';
                   5006: 
1.168     albertel 5007:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5008: 
1.122     albertel 5009:     if (!$symb) {
1.1172.2.26  raeburn  5010:         return if ($namespace eq 'courserequests');
                   5011:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 5012:     } else {
1.1172.2.26  raeburn  5013:         unless ($namespace eq 'courserequests') {
                   5014:             $symb=&escape(&symbclean($symb));
                   5015:         }
1.122     albertel 5016:     }
1.188     www      5017:     if (!$namespace) { 
1.620     albertel 5018:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      5019:           return ''; 
                   5020:        } 
                   5021:     }
1.620     albertel 5022:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5023:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   5024:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 5025:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   5026: 
1.12      www      5027:     my %returnhash=();
1.800     albertel 5028:     foreach my $line (split(/\&/,$answer)) {
                   5029: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 5030:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 5031:     }
1.75      www      5032:     my $version;
                   5033:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 5034:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   5035:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 5036:        }
1.75      www      5037:     }
1.13      www      5038:     return %returnhash;
1.34      www      5039: }
                   5040: 
                   5041: # ---------------------------------------------------------- Course Description
1.1118    foxr     5042: #
                   5043: #  
1.34      www      5044: 
                   5045: sub coursedescription {
1.731     albertel 5046:     my ($courseid,$args)=@_;
1.34      www      5047:     $courseid=~s/^\///;
1.49      www      5048:     $courseid=~s/\_/\//g;
1.34      www      5049:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 5050:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 5051:     my $normalid=$cdomain.'_'.$cnum;
                   5052:     # need to always cache even if we get errors otherwise we keep 
                   5053:     # trying and trying and trying to get the course description.
                   5054:     my %envhash=();
                   5055:     my %returnhash=();
1.731     albertel 5056:     
                   5057:     my $expiretime=600;
                   5058:     if ($env{'request.course.id'} eq $normalid) {
                   5059: 	$expiretime=120;
                   5060:     }
                   5061: 
                   5062:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   5063:     if (!$args->{'freshen_cache'}
                   5064: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   5065: 	foreach my $key (keys(%env)) {
                   5066: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   5067: 	    my ($setting) = $1;
                   5068: 	    $returnhash{$setting} = $env{$key};
                   5069: 	}
                   5070: 	return %returnhash;
                   5071:     }
                   5072: 
1.1118    foxr     5073:     # get the data again
                   5074: 
1.731     albertel 5075:     if (!$args->{'one_time'}) {
                   5076: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   5077:     }
1.811     albertel 5078: 
1.34      www      5079:     if ($chome ne 'no_host') {
1.302     albertel 5080:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 5081:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     5082: 	   my $username = $env{'user.name'}; # Defult username
                   5083: 	   if(defined $args->{'user'}) {
                   5084: 	       $username = $args->{'user'};
                   5085: 	   }
1.129     albertel 5086:            $returnhash{'home'}= $chome;
                   5087: 	   $returnhash{'domain'} = $cdomain;
                   5088: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  5089:            if (!defined($returnhash{'type'})) {
                   5090:                $returnhash{'type'} = 'Course';
                   5091:            }
1.130     albertel 5092:            while (my ($name,$value) = each %returnhash) {
1.53      www      5093:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 5094:            }
1.270     www      5095:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     5096:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     5097: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      5098:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   5099:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   5100:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      5101:        }
                   5102:     }
1.731     albertel 5103:     if (!$args->{'one_time'}) {
1.949     raeburn  5104: 	&appenv(\%envhash);
1.731     albertel 5105:     }
1.302     albertel 5106:     return %returnhash;
1.461     www      5107: }
                   5108: 
1.1080    raeburn  5109: sub update_released_required {
                   5110:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   5111:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   5112:         $cid = $env{'request.course.id'};
                   5113:         $cdom = $env{'course.'.$cid.'.domain'};
                   5114:         $cnum = $env{'course.'.$cid.'.num'};
                   5115:         $chome = $env{'course.'.$cid.'.home'};
                   5116:     }
                   5117:     if ($needsrelease) {
                   5118:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   5119:         my $needsupdate;
                   5120:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   5121:             $needsupdate = 1;
                   5122:         } else {
                   5123:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   5124:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   5125:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   5126:                 $needsupdate = 1;
                   5127:             }
                   5128:         }
                   5129:         if ($needsupdate) {
                   5130:             my %needshash = (
                   5131:                              'internal.releaserequired' => $needsrelease,
                   5132:                             );
                   5133:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   5134:             if ($putresult eq 'ok') {
                   5135:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   5136:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   5137:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   5138:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   5139:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   5140:                 }
                   5141:             }
                   5142:         }
                   5143:     }
                   5144:     return;
                   5145: }
                   5146: 
1.461     www      5147: # -------------------------------------------------See if a user is privileged
                   5148: 
                   5149: sub privileged {
1.1172.2.23  raeburn  5150:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5151:     my $now = time;
1.1172.2.23  raeburn  5152:     my $roles;
                   5153:     if (ref($possroles) eq 'ARRAY') {
                   5154:         $roles = $possroles;
                   5155:     } else {
                   5156:         $roles = ['dc','su'];
                   5157:     }
                   5158:     if (ref($possdomains) eq 'ARRAY') {
                   5159:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   5160:         foreach my $dom (@{$possdomains}) {
                   5161:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   5162:                 (ref($privileged{$dom}) eq 'HASH')) {
                   5163:                 foreach my $role (@{$roles}) {
                   5164:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5165:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5166:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5167:                             return 1 unless (($end && $end < $now) ||
                   5168:                                              ($start && $start > $now));
                   5169:                         }
                   5170:                     }
                   5171:                 }
                   5172:             }
                   5173:         }
                   5174:     } else {
                   5175:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   5176:         my $now = time;
1.1170    droeschl 5177: 
1.1172.2.23  raeburn  5178:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
1.1170    droeschl 5179:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  5180:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   5181:                 return 1 unless ($tend && $tend < $now)
                   5182:                         or ($tstart && $tstart > $now);
1.1170    droeschl 5183:             }
1.1172.2.23  raeburn  5184:         }
                   5185:     }
1.461     www      5186:     return 0;
1.9       www      5187: }
1.1       albertel 5188: 
1.1172.2.23  raeburn  5189: sub privileged_by_domain {
                   5190:     my ($domains,$roles) = @_;
                   5191:     my %privileged = ();
                   5192:     my $cachetime = 60*60*24;
                   5193:     my $now = time;
                   5194:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   5195:         return %privileged;
                   5196:     }
                   5197:     foreach my $dom (@{$domains}) {
                   5198:         next if (ref($privileged{$dom}) eq 'HASH');
                   5199:         my $needroles;
                   5200:         foreach my $role (@{$roles}) {
                   5201:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   5202:             if (defined($cached)) {
                   5203:                 if (ref($result) eq 'HASH') {
                   5204:                     $privileged{$dom}{$role} = $result;
                   5205:                 }
                   5206:             } else {
                   5207:                 $needroles = 1;
                   5208:             }
                   5209:         }
                   5210:         if ($needroles) {
                   5211:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   5212:             $privileged{$dom} = {};
                   5213:             foreach my $server (keys(%dompersonnel)) {
                   5214:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   5215:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   5216:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   5217:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   5218:                         next if ($end && $end < $now);
                   5219:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   5220:                             $dompersonnel{$server}{$item};
                   5221:                     }
                   5222:                 }
                   5223:             }
                   5224:             if (ref($privileged{$dom}) eq 'HASH') {
                   5225:                 foreach my $role (@{$roles}) {
                   5226:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5227:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   5228:                     } else {
                   5229:                         my %hash = ();
                   5230:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   5231:                     }
                   5232:                 }
                   5233:             }
                   5234:         }
                   5235:     }
                   5236:     return %privileged;
                   5237: }
                   5238: 
1.103     harris41 5239: # -------------------------------------------------------- Get user privileges
1.11      www      5240: 
                   5241: sub rolesinit {
1.1169    droeschl 5242:     my ($domain, $username) = @_;
                   5243:     my %userroles = ('user.login.time' => time);
                   5244:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   5245: 
                   5246:     # firstaccess and timerinterval are related to timed maps/resources. 
                   5247:     # also, blocking can be triggered by an activating timer
                   5248:     # it's saved in the user's %env.
                   5249:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   5250:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   5251:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   5252:         %timerintchk, %timerintenv);
                   5253: 
1.1162    raeburn  5254:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 5255:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  5256:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   5257:     }
1.1169    droeschl 5258: 
1.1162    raeburn  5259:     foreach my $key (keys(%timerinterval)) {
                   5260:         my ($cid,$rest) = split(/\0/,$key);
                   5261:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   5262:     }
1.1169    droeschl 5263: 
1.11      www      5264:     my %allroles=();
1.1162    raeburn  5265:     my %allgroups=();
1.11      www      5266: 
1.1169    droeschl 5267:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
                   5268:         my $role = $rolesdump{$area};
                   5269:         $area =~ s/\_\w\w$//;
                   5270: 
                   5271:         my ($trole, $tend, $tstart, $group_privs);
                   5272: 
                   5273:         if ($role =~ /^cr/) {
                   5274:         # Custom role, defined by a user 
                   5275:         # e.g., user.role.cr/msu/smith/mynewrole
                   5276:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5277:                 $trole = $1;
                   5278:                 ($tend, $tstart) = split('_', $2);
                   5279:             } else {
                   5280:                 $trole = $role;
                   5281:             }
                   5282:         } elsif ($role =~ m|^gr/|) {
                   5283:         # Role of member in a group, defined within a course/community
                   5284:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5285:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5286:             next if $tstart eq '-1';
                   5287:             ($trole, $group_privs) = split(/\//, $trole);
                   5288:             $group_privs = &unescape($group_privs);
                   5289:         } else {
                   5290:         # Just a normal role, defined in roles.tab
                   5291:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5292:         }
                   5293: 
                   5294:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5295:                  $username);
                   5296:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5297: 
                   5298:         # role expired or not available yet?
                   5299:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5300:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5301: 
                   5302:         next if $area eq '' or $trole eq '';
                   5303: 
                   5304:         my $spec = "$trole.$area";
                   5305:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5306: 
                   5307:         if ($trole =~ /^cr\//) {
                   5308:         # Custom role, defined by a user
                   5309:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5310:         } elsif ($trole eq 'gr') {
                   5311:         # Role of a member in a group, defined within a course/community
                   5312:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5313:             next;
                   5314:         } else {
                   5315:         # Normal role, defined in roles.tab
                   5316:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5317:         }
                   5318: 
                   5319:         my $cid = $tdomain.'_'.$trest;
                   5320:         unless ($firstaccchk{$cid}) {
                   5321:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5322:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5323:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5324:                         $coursetimerstarts{$cid}{$item}; 
                   5325:                 }
                   5326:             }
                   5327:             $firstaccchk{$cid} = 1;
                   5328:         }
                   5329:         unless ($timerintchk{$cid}) {
                   5330:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5331:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5332:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5333:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5334:                 }
1.12      www      5335:             }
1.1169    droeschl 5336:             $timerintchk{$cid} = 1;
1.191     harris41 5337:         }
1.11      www      5338:     }
1.1169    droeschl 5339: 
                   5340:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
                   5341:         \%allroles, \%allgroups);
                   5342:     $env{'user.adv'} = $userroles{'user.adv'};
                   5343: 
1.1162    raeburn  5344:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5345: }
                   5346: 
1.567     raeburn  5347: sub set_arearole {
1.1172.2.19  raeburn  5348:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   5349:     unless ($nolog) {
1.567     raeburn  5350: # log the associated role with the area
1.1172.2.19  raeburn  5351:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   5352:     }
1.743     albertel 5353:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5354: }
                   5355: 
                   5356: sub custom_roleprivs {
                   5357:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5358:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40  raeburn  5359:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 5360:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5361:         my ($rdummy,$roledef)=
                   5362:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5363:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5364:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5365:             if (defined($syspriv)) {
1.1043    raeburn  5366:                 if ($trest =~ /^$match_community$/) {
                   5367:                     $syspriv =~ s/bre\&S//; 
                   5368:                 }
1.567     raeburn  5369:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5370:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5371:             }
                   5372:             if ($tdomain ne '') {
                   5373:                 if (defined($dompriv)) {
                   5374:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5375:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5376:                 }
                   5377:                 if (($trest ne '') && (defined($coursepriv))) {
                   5378:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5379:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5380:                 }
                   5381:             }
                   5382:         }
                   5383:     }
                   5384: }
                   5385: 
1.678     raeburn  5386: sub group_roleprivs {
                   5387:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   5388:     my $access = 1;
                   5389:     my $now = time;
                   5390:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   5391:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   5392:     if ($access) {
1.811     albertel 5393:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  5394:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   5395:     }
                   5396: }
1.567     raeburn  5397: 
                   5398: sub standard_roleprivs {
                   5399:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   5400:     if (defined($pr{$trole.':s'})) {
                   5401:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   5402:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   5403:     }
                   5404:     if ($tdomain ne '') {
                   5405:         if (defined($pr{$trole.':d'})) {
                   5406:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5407:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5408:         }
                   5409:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   5410:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   5411:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   5412:         }
                   5413:     }
                   5414: }
                   5415: 
                   5416: sub set_userprivs {
1.1064    raeburn  5417:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  5418:     my $author=0;
                   5419:     my $adv=0;
1.678     raeburn  5420:     my %grouproles = ();
                   5421:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  5422:         my @groupkeys; 
1.1000    raeburn  5423:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  5424:             push(@groupkeys,$role);
                   5425:         }
                   5426:         if (ref($groups_roles) eq 'HASH') {
                   5427:             foreach my $key (keys(%{$groups_roles})) {
                   5428:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   5429:                     push(@groupkeys,$key);
                   5430:                 }
                   5431:             }
                   5432:         }
                   5433:         if (@groupkeys > 0) {
                   5434:             foreach my $role (@groupkeys) {
                   5435:                 my ($trole,$area,$sec,$extendedarea);
                   5436:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   5437:                     $trole = $1;
                   5438:                     $area = $2;
                   5439:                     $sec = $3;
                   5440:                     $extendedarea = $area.$sec;
                   5441:                     if (exists($$allgroups{$area})) {
                   5442:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   5443:                             my $spec = $trole.'.'.$extendedarea;
                   5444:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  5445:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  5446:                         }
1.678     raeburn  5447:                     }
                   5448:                 }
                   5449:             }
                   5450:         }
                   5451:     }
1.800     albertel 5452:     foreach my $group (keys(%grouproles)) {
                   5453:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  5454:     }
1.800     albertel 5455:     foreach my $role (keys(%{$allroles})) {
                   5456:         my %thesepriv;
1.941     raeburn  5457:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 5458:         foreach my $item (split(/:/,$$allroles{$role})) {
                   5459:             if ($item ne '') {
                   5460:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  5461:                 if ($restrictions eq '') {
                   5462:                     $thesepriv{$privilege}='F';
                   5463:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   5464:                     $thesepriv{$privilege}.=$restrictions;
                   5465:                 }
                   5466:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   5467:             }
                   5468:         }
                   5469:         my $thesestr='';
1.1104    raeburn  5470:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 5471: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   5472: 	}
                   5473:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  5474:     }
                   5475:     return ($author,$adv);
                   5476: }
                   5477: 
1.994     raeburn  5478: sub role_status {
1.1104    raeburn  5479:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  5480:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40  raeburn  5481:         my ($one,$two) = split(m{\./},$rolekey,2);
                   5482:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  5483:         unless (!defined($$role) || $$role eq '') {
1.1172.2.40  raeburn  5484:             $$where = '/'.$two;
1.994     raeburn  5485:             $$trolecode=$$role.'.'.$$where;
                   5486:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   5487:             $$tstatus='is';
1.1104    raeburn  5488:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  5489:                 $$tstatus='future';
1.1034    raeburn  5490:                 if ($$tstart<$now) {
                   5491:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  5492:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  5493:                             my (%allroles,%allgroups,$group_privs,
                   5494:                                 %groups_roles,@rolecodes);
1.1002    raeburn  5495:                             my %userroles = (
                   5496:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   5497:                             );
1.1064    raeburn  5498:                             @rolecodes = ('cm'); 
1.1002    raeburn  5499:                             my $spec=$$role.'.'.$$where;
                   5500:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   5501:                             if ($$role =~ /^cr\//) {
                   5502:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  5503:                                 push(@rolecodes,'cr');
1.1002    raeburn  5504:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  5505:                                 push(@rolecodes,$$role);
1.1002    raeburn  5506:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   5507:                                                     $env{'user.name'});
1.1064    raeburn  5508:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  5509:                                 (undef,my $group_privs) = split(/\//,$trole);
                   5510:                                 $group_privs = &unescape($group_privs);
                   5511:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  5512:                                 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  5513:                                 &get_groups_roles($tdomain,$trest,
                   5514:                                                   \%course_roles,\@rolecodes,
                   5515:                                                   \%groups_roles);
1.1002    raeburn  5516:                             } else {
1.1064    raeburn  5517:                                 push(@rolecodes,$$role);
1.1002    raeburn  5518:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   5519:                             }
1.1064    raeburn  5520:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   5521:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  5522:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   5523:                         }
                   5524:                     }
1.1034    raeburn  5525:                     $$tstatus = 'is';
1.1002    raeburn  5526:                 }
1.994     raeburn  5527:             }
                   5528:             if ($$tend) {
1.1104    raeburn  5529:                 if ($$tend<$update) {
1.994     raeburn  5530:                     $$tstatus='expired';
                   5531:                 } elsif ($$tend<$now) {
                   5532:                     $$tstatus='will_not';
                   5533:                 }
                   5534:             }
                   5535:         }
                   5536:     }
                   5537: }
                   5538: 
1.1104    raeburn  5539: sub get_groups_roles {
                   5540:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   5541:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   5542:                   (ref($rolecodes) eq 'ARRAY') && 
                   5543:                   (ref($groups_roles) eq 'HASH')); 
                   5544:     if (keys(%{$cdom_courseroles}) > 0) {
                   5545:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   5546:         if ($cdom ne '' && $cnum ne '') {
                   5547:             foreach my $key (keys(%{$cdom_courseroles})) {
                   5548:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   5549:                     my $crsrole = $1;
                   5550:                     my $crssec = $2;
                   5551:                     if ($crsrole =~ /^cr/) {
                   5552:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   5553:                             push(@{$rolecodes},'cr');
                   5554:                         }
                   5555:                     } else {
                   5556:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   5557:                             push(@{$rolecodes},$crsrole);
                   5558:                         }
                   5559:                     }
                   5560:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   5561:                     if ($crssec ne '') {
                   5562:                         $rolekey .= "/$crssec";
                   5563:                     }
                   5564:                     $rolekey .= './';
                   5565:                     $groups_roles->{$rolekey} = $rolecodes;
                   5566:                 }
                   5567:             }
                   5568:         }
                   5569:     }
                   5570:     return;
                   5571: }
                   5572: 
                   5573: sub delete_env_groupprivs {
                   5574:     my ($where,$courseroles,$possroles) = @_;
                   5575:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   5576:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   5577:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   5578:         %{$courseroles->{$udom}} =
                   5579:             &get_my_roles('','','userroles',['active'],
                   5580:                           $possroles,[$udom],1);
                   5581:     }
                   5582:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   5583:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   5584:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   5585:             my $area = '/'.$cdom.'/'.$cnum;
                   5586:             my $privkey = "user.priv.$crsrole.$area";
                   5587:             if ($crssec ne '') {
                   5588:                 $privkey .= '/'.$crssec;
                   5589:             }
                   5590:             $privkey .= ".$area/$group";
                   5591:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   5592:         }
                   5593:     }
                   5594:     return;
                   5595: }
                   5596: 
1.994     raeburn  5597: sub check_adhoc_privs {
1.1104    raeburn  5598:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  5599:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.9  raeburn  5600:     my $setprivs;
1.994     raeburn  5601:     if ($env{$cckey}) {
                   5602:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  5603:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  5604:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  5605:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9  raeburn  5606:             $setprivs = 1;
1.994     raeburn  5607:         }
                   5608:     } else {
1.1088    raeburn  5609:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9  raeburn  5610:         $setprivs = 1;
1.994     raeburn  5611:     }
1.1172.2.9  raeburn  5612:     return $setprivs;
1.994     raeburn  5613: }
                   5614: 
                   5615: sub set_adhoc_privileges {
                   5616: # role can be cc or ca
1.1088    raeburn  5617:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  5618:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   5619:     my $spec = $role.'.'.$area;
                   5620:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  5621:                                   $env{'user.name'},1);
1.994     raeburn  5622:     my %ccrole = ();
                   5623:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   5624:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   5625:     &appenv(\%userroles,[$role,'cm']);
                   5626:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  5627:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   5628:         &appenv( {'request.role'        => $spec,
                   5629:                   'request.role.domain' => $dcdom,
                   5630:                   'request.course.sec'  => ''
                   5631:                  }
                   5632:                );
                   5633:         my $tadv=0;
                   5634:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   5635:         &appenv({'request.role.adv'    => $tadv});
                   5636:     }
1.994     raeburn  5637: }
                   5638: 
1.12      www      5639: # --------------------------------------------------------------- get interface
                   5640: 
                   5641: sub get {
1.131     albertel 5642:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5643:    my $items='';
1.800     albertel 5644:    foreach my $item (@$storearr) {
                   5645:        $items.=&escape($item).'&';
1.191     harris41 5646:    }
1.12      www      5647:    $items=~s/\&$//;
1.620     albertel 5648:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5649:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 5650:    my $uhome=&homeserver($uname,$udomain);
                   5651: 
1.133     albertel 5652:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5653:    my @pairs=split(/\&/,$rep);
1.273     albertel 5654:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   5655:      return @pairs;
                   5656:    }
1.15      www      5657:    my %returnhash=();
1.42      www      5658:    my $i=0;
1.800     albertel 5659:    foreach my $item (@$storearr) {
                   5660:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5661:       $i++;
1.191     harris41 5662:    }
1.15      www      5663:    return %returnhash;
1.27      www      5664: }
                   5665: 
                   5666: # --------------------------------------------------------------- del interface
                   5667: 
                   5668: sub del {
1.133     albertel 5669:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      5670:    my $items='';
1.800     albertel 5671:    foreach my $item (@$storearr) {
                   5672:        $items.=&escape($item).'&';
1.191     harris41 5673:    }
1.984     neumanie 5674: 
1.27      www      5675:    $items=~s/\&$//;
1.620     albertel 5676:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5677:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5678:    my $uhome=&homeserver($uname,$udomain);
                   5679:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5680: }
                   5681: 
                   5682: # -------------------------------------------------------------- dump interface
                   5683: 
1.1172.2.22  raeburn  5684: sub unserialize {
                   5685:     my ($rep, $escapedkeys) = @_;
                   5686: 
                   5687:     return {} if $rep =~ /^error/;
                   5688: 
                   5689:     my %returnhash=();
                   5690:     foreach my $item (split(/\&/,$rep)) {
                   5691:         my ($key, $value) = split(/=/, $item, 2);
                   5692:         $key = unescape($key) unless $escapedkeys;
                   5693:         next if $key =~ /^error: 2 /;
                   5694:         $returnhash{$key} = &thaw_unescape($value);
                   5695:     }
                   5696:     return \%returnhash;
                   5697: }
                   5698: 
                   5699: # see Lond::dump_with_regexp
                   5700: # if $escapedkeys hash keys won't get unescaped.
1.15      www      5701: sub dump {
1.1172.2.22  raeburn  5702:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 5703:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5704:     if (!$uname) { $uname=$env{'user.name'}; }
                   5705:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 5706: 
1.1172.2.22  raeburn  5707:     my $reply;
                   5708:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   5709:         # user is hosted on this machine
                   5710:         $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  5711:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  5712:         return %{&unserialize($reply, $escapedkeys)};
                   5713:     }
1.755     albertel 5714:     if ($regexp) {
                   5715: 	$regexp=&escape($regexp);
                   5716:     } else {
                   5717: 	$regexp='.';
                   5718:     }
1.1166    raeburn  5719:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 5720:     my @pairs=split(/\&/,$rep);
                   5721:     my %returnhash=();
1.1098    foxr     5722:     if (!($rep =~ /^error/ )) {
                   5723: 	foreach my $item (@pairs) {
                   5724: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  5725:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     5726: 	    next if ($key =~ /^error: 2 /);
                   5727: 	    $returnhash{$key}=&thaw_unescape($value);
                   5728: 	}
1.755     albertel 5729:     }
                   5730:     return %returnhash;
1.407     www      5731: }
                   5732: 
1.1098    foxr     5733: 
1.717     albertel 5734: # --------------------------------------------------------- dumpstore interface
                   5735: 
                   5736: sub dumpstore {
                   5737:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  5738:    # same as dump but keys must be escaped. They may contain colon separated
                   5739:    # lists of values that may themself contain colons (e.g. symbs).
                   5740:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 5741: }
                   5742: 
1.407     www      5743: # -------------------------------------------------------------- keys interface
                   5744: 
                   5745: sub getkeys {
                   5746:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 5747:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5748:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      5749:    my $uhome=&homeserver($uname,$udomain);
                   5750:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   5751:    my @keyarray=();
1.800     albertel 5752:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  5753:       next if ($key =~ /^error: 2 /);
1.800     albertel 5754:       push(@keyarray,&unescape($key));
1.407     www      5755:    }
                   5756:    return @keyarray;
1.318     matthew  5757: }
                   5758: 
1.319     matthew  5759: # --------------------------------------------------------------- currentdump
                   5760: sub currentdump {
1.328     matthew  5761:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 5762:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   5763:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   5764:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  5765:    my $uhome = &homeserver($sname,$sdom);
                   5766:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  5767:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  5768:    #
1.318     matthew  5769:    my %returnhash=();
1.319     matthew  5770:    #
                   5771:    if ($rep eq "unknown_cmd") { 
                   5772:        # an old lond will not know currentdump
                   5773:        # Do a dump and make it look like a currentdump
1.822     albertel 5774:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  5775:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   5776:        my %hash = @tmp;
                   5777:        @tmp=();
1.424     matthew  5778:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  5779:    } else {
                   5780:        my @pairs=split(/\&/,$rep);
1.800     albertel 5781:        foreach my $pair (@pairs) {
                   5782:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  5783:            my ($symb,$param) = split(/:/,$key);
                   5784:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 5785:                                                         &thaw_unescape($value);
1.319     matthew  5786:        }
1.191     harris41 5787:    }
1.12      www      5788:    return %returnhash;
1.424     matthew  5789: }
                   5790: 
                   5791: sub convert_dump_to_currentdump{
                   5792:     my %hash = %{shift()};
                   5793:     my %returnhash;
                   5794:     # Code ripped from lond, essentially.  The only difference
                   5795:     # here is the unescaping done by lonnet::dump().  Conceivably
                   5796:     # we might run in to problems with parameter names =~ /^v\./
                   5797:     while (my ($key,$value) = each(%hash)) {
                   5798:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 5799: 	$symb  = &unescape($symb);
                   5800: 	$param = &unescape($param);
1.424     matthew  5801:         next if ($v eq 'version' || $symb eq 'keys');
                   5802:         next if (exists($returnhash{$symb}) &&
                   5803:                  exists($returnhash{$symb}->{$param}) &&
                   5804:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   5805:         $returnhash{$symb}->{$param}=$value;
                   5806:         $returnhash{$symb}->{'v.'.$param}=$v;
                   5807:     }
                   5808:     #
                   5809:     # Remove all of the keys in the hashes which keep track of
                   5810:     # the version of the parameter.
                   5811:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   5812:         # use a foreach because we are going to delete from the hash.
                   5813:         foreach my $key (keys(%$param_hash)) {
                   5814:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   5815:         }
                   5816:     }
                   5817:     return \%returnhash;
1.12      www      5818: }
                   5819: 
1.627     albertel 5820: # ------------------------------------------------------ critical inc interface
                   5821: 
                   5822: sub cinc {
                   5823:     return &inc(@_,'critical');
                   5824: }
                   5825: 
1.449     matthew  5826: # --------------------------------------------------------------- inc interface
                   5827: 
                   5828: sub inc {
1.627     albertel 5829:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 5830:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5831:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  5832:     my $uhome=&homeserver($uname,$udomain);
                   5833:     my $items='';
                   5834:     if (! ref($store)) {
                   5835:         # got a single value, so use that instead
                   5836:         $items = &escape($store).'=&';
                   5837:     } elsif (ref($store) eq 'SCALAR') {
                   5838:         $items = &escape($$store).'=&';        
                   5839:     } elsif (ref($store) eq 'ARRAY') {
                   5840:         $items = join('=&',map {&escape($_);} @{$store});
                   5841:     } elsif (ref($store) eq 'HASH') {
                   5842:         while (my($key,$value) = each(%{$store})) {
                   5843:             $items.= &escape($key).'='.&escape($value).'&';
                   5844:         }
                   5845:     }
                   5846:     $items=~s/\&$//;
1.627     albertel 5847:     if ($critical) {
                   5848: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5849:     } else {
                   5850: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5851:     }
1.449     matthew  5852: }
                   5853: 
1.12      www      5854: # --------------------------------------------------------------- put interface
                   5855: 
                   5856: sub put {
1.134     albertel 5857:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5858:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5859:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5860:    my $uhome=&homeserver($uname,$udomain);
1.12      www      5861:    my $items='';
1.800     albertel 5862:    foreach my $item (keys(%$storehash)) {
                   5863:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5864:    }
1.12      www      5865:    $items=~s/\&$//;
1.134     albertel 5866:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      5867: }
                   5868: 
1.631     albertel 5869: # ------------------------------------------------------------ newput interface
                   5870: 
                   5871: sub newput {
                   5872:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   5873:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5874:    if (!$uname) { $uname=$env{'user.name'}; }
                   5875:    my $uhome=&homeserver($uname,$udomain);
                   5876:    my $items='';
                   5877:    foreach my $key (keys(%$storehash)) {
                   5878:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   5879:    }
                   5880:    $items=~s/\&$//;
                   5881:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   5882: }
                   5883: 
                   5884: # ---------------------------------------------------------  putstore interface
                   5885: 
1.524     raeburn  5886: sub putstore {
1.715     albertel 5887:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 5888:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5889:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  5890:    my $uhome=&homeserver($uname,$udomain);
                   5891:    my $items='';
1.715     albertel 5892:    foreach my $key (keys(%$storehash)) {
                   5893:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  5894:    }
1.715     albertel 5895:    $items=~s/\&$//;
1.716     albertel 5896:    my $esc_symb=&escape($symb);
                   5897:    my $esc_v=&escape($version);
1.715     albertel 5898:    my $reply =
1.716     albertel 5899:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 5900: 	      $uhome);
                   5901:    if ($reply eq 'unknown_cmd') {
1.716     albertel 5902:        # gfall back to way things use to be done
1.715     albertel 5903:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   5904: 			    $uname);
1.524     raeburn  5905:    }
1.715     albertel 5906:    return $reply;
                   5907: }
                   5908: 
                   5909: sub old_putstore {
1.716     albertel 5910:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   5911:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5912:     if (!$uname) { $uname=$env{'user.name'}; }
                   5913:     my $uhome=&homeserver($uname,$udomain);
                   5914:     my %newstorehash;
1.800     albertel 5915:     foreach my $item (keys(%$storehash)) {
                   5916: 	my $key = $version.':'.&escape($symb).':'.$item;
                   5917: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 5918:     }
                   5919:     my $items='';
                   5920:     my %allitems = ();
1.800     albertel 5921:     foreach my $item (keys(%newstorehash)) {
                   5922: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 5923: 	    my $key = $1.':keys:'.$2;
                   5924: 	    $allitems{$key} .= $3.':';
                   5925: 	}
1.800     albertel 5926: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 5927:     }
1.800     albertel 5928:     foreach my $item (keys(%allitems)) {
                   5929: 	$allitems{$item} =~ s/\:$//;
                   5930: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 5931:     }
                   5932:     $items=~s/\&$//;
                   5933:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  5934: }
                   5935: 
1.47      www      5936: # ------------------------------------------------------ critical put interface
                   5937: 
                   5938: sub cput {
1.134     albertel 5939:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5940:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5941:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5942:    my $uhome=&homeserver($uname,$udomain);
1.47      www      5943:    my $items='';
1.800     albertel 5944:    foreach my $item (keys(%$storehash)) {
                   5945:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5946:    }
1.47      www      5947:    $items=~s/\&$//;
1.134     albertel 5948:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5949: }
                   5950: 
                   5951: # -------------------------------------------------------------- eget interface
                   5952: 
                   5953: sub eget {
1.133     albertel 5954:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5955:    my $items='';
1.800     albertel 5956:    foreach my $item (@$storearr) {
                   5957:        $items.=&escape($item).'&';
1.191     harris41 5958:    }
1.12      www      5959:    $items=~s/\&$//;
1.620     albertel 5960:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5961:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5962:    my $uhome=&homeserver($uname,$udomain);
                   5963:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5964:    my @pairs=split(/\&/,$rep);
                   5965:    my %returnhash=();
1.42      www      5966:    my $i=0;
1.800     albertel 5967:    foreach my $item (@$storearr) {
                   5968:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5969:       $i++;
1.191     harris41 5970:    }
1.12      www      5971:    return %returnhash;
                   5972: }
                   5973: 
1.667     albertel 5974: # ------------------------------------------------------------ tmpput interface
                   5975: sub tmpput {
1.802     raeburn  5976:     my ($storehash,$server,$context)=@_;
1.667     albertel 5977:     my $items='';
1.800     albertel 5978:     foreach my $item (keys(%$storehash)) {
                   5979: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 5980:     }
                   5981:     $items=~s/\&$//;
1.802     raeburn  5982:     if (defined($context)) {
                   5983:         $items .= ':'.&escape($context);
                   5984:     }
1.667     albertel 5985:     return &reply("tmpput:$items",$server);
                   5986: }
                   5987: 
                   5988: # ------------------------------------------------------------ tmpget interface
                   5989: sub tmpget {
1.688     albertel 5990:     my ($token,$server)=@_;
                   5991:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5992:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 5993:     my %returnhash;
                   5994:     foreach my $item (split(/\&/,$rep)) {
                   5995: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  5996:         next if ($key =~ /^error: 2 /);
1.667     albertel 5997: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   5998:     }
                   5999:     return %returnhash;
                   6000: }
                   6001: 
1.1113    raeburn  6002: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 6003: sub tmpdel {
                   6004:     my ($token,$server)=@_;
                   6005:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6006:     return &reply("tmpdel:$token",$server);
                   6007: }
                   6008: 
1.1172.2.13  raeburn  6009: # ------------------------------------------------------------ get_timebased_id
                   6010: 
                   6011: sub get_timebased_id {
                   6012:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   6013:         $maxtries) = @_;
                   6014:     my ($newid,$error,$dellock);
                   6015:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   6016:         return ('','ok','invalid call to get suffix');
                   6017:     }
                   6018: 
                   6019: # set defaults for any optional args for which values were not supplied
                   6020:     if ($who eq '') {
                   6021:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   6022:     }
                   6023:     if (!$locktries) {
                   6024:         $locktries = 3;
                   6025:     }
                   6026:     if (!$maxtries) {
                   6027:         $maxtries = 10;
                   6028:     }
                   6029: 
                   6030:     if (($cdom eq '') || ($cnum eq '')) {
                   6031:         if ($env{'request.course.id'}) {
                   6032:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6033:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6034:         }
                   6035:         if (($cdom eq '') || ($cnum eq '')) {
                   6036:             return ('','ok','call to get suffix not in course context');
                   6037:         }
                   6038:     }
                   6039: 
                   6040: # construct locking item
                   6041:     my $lockhash = {
                   6042:                       $prefix."\0".'locked_'.$keyid => $who,
                   6043:                    };
                   6044:     my $tries = 0;
                   6045: 
                   6046: # attempt to get lock on nohist_$namespace file
                   6047:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6048:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   6049:         $tries ++;
                   6050:         sleep 1;
                   6051:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6052:     }
                   6053: 
                   6054: # attempt to get unique identifier, based on current timestamp
                   6055:     if ($gotlock eq 'ok') {
                   6056:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   6057:         my $id = time;
                   6058:         $newid = $id;
                   6059:         my $idtries = 0;
                   6060:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   6061:             if ($idtype eq 'concat') {
                   6062:                 $newid = $id.$idtries;
                   6063:             } else {
                   6064:                 $newid ++;
                   6065:             }
                   6066:             $idtries ++;
                   6067:         }
                   6068:         if (!exists($inuse{$prefix."\0".$newid})) {
                   6069:             my %new_item =  (
                   6070:                               $prefix."\0".$newid => $who,
                   6071:                             );
                   6072:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   6073:                                                  $cdom,$cnum);
                   6074:             if ($putresult ne 'ok') {
                   6075:                 undef($newid);
                   6076:                 $error = 'error saving new item: '.$putresult;
                   6077:             }
                   6078:         } else {
                   6079:              $error = ('error: no unique suffix available for the new item ');
                   6080:         }
                   6081: #  remove lock
                   6082:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   6083:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   6084:     } else {
                   6085:         $error = "error: could not obtain lockfile\n";
                   6086:         $dellock = 'ok';
                   6087:     }
                   6088:     return ($newid,$dellock,$error);
                   6089: }
                   6090: 
1.765     albertel 6091: # -------------------------------------------------- portfolio access checking
                   6092: 
                   6093: sub portfolio_access {
1.766     albertel 6094:     my ($requrl) = @_;
1.765     albertel 6095:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   6096:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  6097:     if ($result) {
                   6098:         my %setters;
                   6099:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6100:             my ($startblock,$endblock) =
                   6101:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   6102:             if ($startblock && $endblock) {
                   6103:                 return 'B';
                   6104:             }
                   6105:         } else {
                   6106:             my ($startblock,$endblock) =
                   6107:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   6108:             if ($startblock && $endblock) {
                   6109:                 return 'B';
                   6110:             }
                   6111:         }
                   6112:     }
1.765     albertel 6113:     if ($result eq 'ok') {
1.766     albertel 6114:        return 'F';
1.765     albertel 6115:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 6116:        return 'A';
1.765     albertel 6117:     }
1.766     albertel 6118:     return '';
1.765     albertel 6119: }
                   6120: 
                   6121: sub get_portfolio_access {
1.767     albertel 6122:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   6123: 
                   6124:     if (!ref($access_hash)) {
                   6125: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   6126: 	my %access_controls = &get_access_controls($current_perms,$group,
                   6127: 						   $file_name);
                   6128: 	$access_hash = $access_controls{$file_name};
                   6129:     }
                   6130: 
1.765     albertel 6131:     my ($public,$guest,@domains,@users,@courses,@groups);
                   6132:     my $now = time;
                   6133:     if (ref($access_hash) eq 'HASH') {
                   6134:         foreach my $key (keys(%{$access_hash})) {
                   6135:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6136:             if ($start > $now) {
                   6137:                 next;
                   6138:             }
                   6139:             if ($end && $end<$now) {
                   6140:                 next;
                   6141:             }
                   6142:             if ($scope eq 'public') {
                   6143:                 $public = $key;
                   6144:                 last;
                   6145:             } elsif ($scope eq 'guest') {
                   6146:                 $guest = $key;
                   6147:             } elsif ($scope eq 'domains') {
                   6148:                 push(@domains,$key);
                   6149:             } elsif ($scope eq 'users') {
                   6150:                 push(@users,$key);
                   6151:             } elsif ($scope eq 'course') {
                   6152:                 push(@courses,$key);
                   6153:             } elsif ($scope eq 'group') {
                   6154:                 push(@groups,$key);
                   6155:             }
                   6156:         }
                   6157:         if ($public) {
                   6158:             return 'ok';
                   6159:         }
                   6160:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6161:             if ($guest) {
                   6162:                 return $guest;
                   6163:             }
                   6164:         } else {
                   6165:             if (@domains > 0) {
                   6166:                 foreach my $domkey (@domains) {
                   6167:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   6168:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   6169:                             return 'ok';
                   6170:                         }
                   6171:                     }
                   6172:                 }
                   6173:             }
                   6174:             if (@users > 0) {
                   6175:                 foreach my $userkey (@users) {
1.865     raeburn  6176:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   6177:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   6178:                             if (ref($item) eq 'HASH') {
                   6179:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   6180:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   6181:                                     return 'ok';
                   6182:                                 }
                   6183:                             }
                   6184:                         }
                   6185:                     } 
1.765     albertel 6186:                 }
                   6187:             }
                   6188:             my %roleshash;
                   6189:             my @courses_and_groups = @courses;
                   6190:             push(@courses_and_groups,@groups); 
                   6191:             if (@courses_and_groups > 0) {
                   6192:                 my (%allgroups,%allroles); 
                   6193:                 my ($start,$end,$role,$sec,$group);
                   6194:                 foreach my $envkey (%env) {
1.1060    raeburn  6195:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6196:                         my $cid = $2.'_'.$3; 
                   6197:                         if ($1 eq 'gr') {
                   6198:                             $group = $4;
                   6199:                             $allgroups{$cid}{$group} = $env{$envkey};
                   6200:                         } else {
                   6201:                             if ($4 eq '') {
                   6202:                                 $sec = 'none';
                   6203:                             } else {
                   6204:                                 $sec = $4;
                   6205:                             }
                   6206:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6207:                         }
1.811     albertel 6208:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6209:                         my $cid = $2.'_'.$3;
                   6210:                         if ($4 eq '') {
                   6211:                             $sec = 'none';
                   6212:                         } else {
                   6213:                             $sec = $4;
                   6214:                         }
                   6215:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6216:                     }
                   6217:                 }
                   6218:                 if (keys(%allroles) == 0) {
                   6219:                     return;
                   6220:                 }
                   6221:                 foreach my $key (@courses_and_groups) {
                   6222:                     my %content = %{$$access_hash{$key}};
                   6223:                     my $cnum = $content{'number'};
                   6224:                     my $cdom = $content{'domain'};
                   6225:                     my $cid = $cdom.'_'.$cnum;
                   6226:                     if (!exists($allroles{$cid})) {
                   6227:                         next;
                   6228:                     }    
                   6229:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   6230:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   6231:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   6232:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   6233:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   6234:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   6235:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   6236:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   6237:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   6238:                                         if (grep/^all$/,@sections) {
                   6239:                                             return 'ok';
                   6240:                                         } else {
                   6241:                                             if (grep/^$sec$/,@sections) {
                   6242:                                                 return 'ok';
                   6243:                                             }
                   6244:                                         }
                   6245:                                     }
                   6246:                                 }
                   6247:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   6248:                                     if (grep/^none$/,@groups) {
                   6249:                                         return 'ok';
                   6250:                                     }
                   6251:                                 } else {
                   6252:                                     if (grep/^all$/,@groups) {
                   6253:                                         return 'ok';
                   6254:                                     } 
                   6255:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   6256:                                         if (grep/^$group$/,@groups) {
                   6257:                                             return 'ok';
                   6258:                                         }
                   6259:                                     }
                   6260:                                 } 
                   6261:                             }
                   6262:                         }
                   6263:                     }
                   6264:                 }
                   6265:             }
                   6266:             if ($guest) {
                   6267:                 return $guest;
                   6268:             }
                   6269:         }
                   6270:     }
                   6271:     return;
                   6272: }
                   6273: 
                   6274: sub course_group_datechecker {
                   6275:     my ($dates,$now,$status) = @_;
                   6276:     my ($start,$end) = split(/\./,$dates);
                   6277:     if (!$start && !$end) {
                   6278:         return 'ok';
                   6279:     }
                   6280:     if (grep/^active$/,@{$status}) {
                   6281:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   6282:             return 'ok';
                   6283:         }
                   6284:     }
                   6285:     if (grep/^previous$/,@{$status}) {
                   6286:         if ($end > $now ) {
                   6287:             return 'ok';
                   6288:         }
                   6289:     }
                   6290:     if (grep/^future$/,@{$status}) {
                   6291:         if ($start > $now) {
                   6292:             return 'ok';
                   6293:         }
                   6294:     }
                   6295:     return; 
                   6296: }
                   6297: 
                   6298: sub parse_portfolio_url {
                   6299:     my ($url) = @_;
                   6300: 
                   6301:     my ($type,$udom,$unum,$group,$file_name);
                   6302:     
1.823     albertel 6303:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 6304: 	$type = 1;
                   6305:         $udom = $1;
                   6306:         $unum = $2;
                   6307:         $file_name = $3;
1.823     albertel 6308:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 6309: 	$type = 2;
                   6310:         $udom = $1;
                   6311:         $unum = $2;
                   6312:         $group = $3;
                   6313:         $file_name = $3.'/'.$4;
                   6314:     }
                   6315:     if (wantarray) {
                   6316: 	return ($type,$udom,$unum,$file_name,$group);
                   6317:     }
                   6318:     return $type;
                   6319: }
                   6320: 
                   6321: sub is_portfolio_url {
                   6322:     my ($url) = @_;
                   6323:     return scalar(&parse_portfolio_url($url));
                   6324: }
                   6325: 
1.798     raeburn  6326: sub is_portfolio_file {
                   6327:     my ($file) = @_;
1.820     raeburn  6328:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  6329:         return 1;
                   6330:     }
                   6331:     return;
                   6332: }
                   6333: 
1.976     raeburn  6334: sub usertools_access {
1.1084    raeburn  6335:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  6336:     my ($access,%tools);
                   6337:     if ($context eq '') {
                   6338:         $context = 'tools';
                   6339:     }
                   6340:     if ($context eq 'requestcourses') {
                   6341:         %tools = (
                   6342:                       official   => 1,
                   6343:                       unofficial => 1,
1.1006    raeburn  6344:                       community  => 1,
1.1172.2.37  raeburn  6345:                       textbook   => 1,
1.985     raeburn  6346:                  );
1.1172.2.9  raeburn  6347:     } elsif ($context eq 'requestauthor') {
                   6348:         %tools = (
                   6349:                       requestauthor => 1,
                   6350:                  );
1.985     raeburn  6351:     } else {
                   6352:         %tools = (
                   6353:                       aboutme   => 1,
                   6354:                       blog      => 1,
1.1172.2.6  raeburn  6355:                       webdav    => 1,
1.985     raeburn  6356:                       portfolio => 1,
                   6357:                  );
                   6358:     }
1.976     raeburn  6359:     return if (!defined($tools{$tool}));
                   6360: 
1.1172.2.35  raeburn  6361:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  6362:         $udom = $env{'user.domain'};
                   6363:         $uname = $env{'user.name'};
                   6364:     }
                   6365: 
1.978     raeburn  6366:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6367:         if ($action ne 'reload') {
1.985     raeburn  6368:             if ($context eq 'requestcourses') {
                   6369:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  6370:             } elsif ($context eq 'requestauthor') {
                   6371:                 return $env{'environment.canrequest.author'};
1.985     raeburn  6372:             } else {
                   6373:                 return $env{'environment.availabletools.'.$tool};
                   6374:             }
                   6375:         }
1.976     raeburn  6376:     }
                   6377: 
1.1172.2.9  raeburn  6378:     my ($toolstatus,$inststatus,$envkey);
                   6379:     if ($context eq 'requestauthor') {
                   6380:         $envkey = $context;
                   6381:     } else {
                   6382:         $envkey = $context.'.'.$tool;
                   6383:     }
1.976     raeburn  6384: 
1.985     raeburn  6385:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   6386:          ($action ne 'reload')) {
1.1172.2.9  raeburn  6387:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  6388:         $inststatus = $env{'environment.inststatus'};
                   6389:     } else {
1.1084    raeburn  6390:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  6391:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  6392:             $inststatus = $userenvref->{'inststatus'};
                   6393:         } else {
1.1172.2.9  raeburn  6394:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   6395:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  6396:             $inststatus = $userenv{'inststatus'};
                   6397:         }
1.976     raeburn  6398:     }
                   6399: 
                   6400:     if ($toolstatus ne '') {
                   6401:         if ($toolstatus) {
                   6402:             $access = 1;
                   6403:         } else {
                   6404:             $access = 0;
                   6405:         }
                   6406:         return $access;
                   6407:     }
                   6408: 
1.1084    raeburn  6409:     my ($is_adv,%domdef);
                   6410:     if (ref($is_advref) eq 'HASH') {
                   6411:         $is_adv = $is_advref->{'is_adv'};
                   6412:     } else {
                   6413:         $is_adv = &is_advanced_user($udom,$uname);
                   6414:     }
                   6415:     if (ref($domdefref) eq 'HASH') {
                   6416:         %domdef = %{$domdefref};
                   6417:     } else {
                   6418:         %domdef = &get_domain_defaults($udom);
                   6419:     }
1.976     raeburn  6420:     if (ref($domdef{$tool}) eq 'HASH') {
                   6421:         if ($is_adv) {
                   6422:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   6423:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   6424:                     $access = 1;
                   6425:                 } else {
                   6426:                     $access = 0;
                   6427:                 }
                   6428:                 return $access;
                   6429:             }
                   6430:         }
                   6431:         if ($inststatus ne '') {
                   6432:             my ($hasaccess,$hasnoaccess);
                   6433:             foreach my $affiliation (split(/:/,$inststatus)) {
                   6434:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   6435:                     if ($domdef{$tool}{$affiliation}) {
                   6436:                         $hasaccess = 1;
                   6437:                     } else {
                   6438:                         $hasnoaccess = 1;
                   6439:                     }
                   6440:                 }
                   6441:             }
                   6442:             if ($hasaccess || $hasnoaccess) {
                   6443:                 if ($hasaccess) {
                   6444:                     $access = 1;
                   6445:                 } elsif ($hasnoaccess) {
                   6446:                     $access = 0; 
                   6447:                 }
                   6448:                 return $access;
                   6449:             }
                   6450:         } else {
                   6451:             if ($domdef{$tool}{'default'} ne '') {
                   6452:                 if ($domdef{$tool}{'default'}) {
                   6453:                     $access = 1;
                   6454:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   6455:                     $access = 0;
                   6456:                 }
                   6457:                 return $access;
                   6458:             }
                   6459:         }
                   6460:     } else {
1.1172.2.6  raeburn  6461:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  6462:             $access = 1;
                   6463:         } else {
                   6464:             $access = 0;
                   6465:         }
1.976     raeburn  6466:         return $access;
                   6467:     }
                   6468: }
                   6469: 
1.1050    raeburn  6470: sub is_course_owner {
                   6471:     my ($cdom,$cnum,$udom,$uname) = @_;
                   6472:     if (($udom eq '') || ($uname eq '')) {
                   6473:         $udom = $env{'user.domain'};
                   6474:         $uname = $env{'user.name'};
                   6475:     }
                   6476:     unless (($udom eq '') || ($uname eq '')) {
                   6477:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   6478:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   6479:                 return 1;
                   6480:             } else {
                   6481:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   6482:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   6483:                     return 1;
                   6484:                 }
                   6485:             }
                   6486:         }
                   6487:     }
                   6488:     return;
                   6489: }
                   6490: 
1.976     raeburn  6491: sub is_advanced_user {
                   6492:     my ($udom,$uname) = @_;
1.1085    raeburn  6493:     if ($udom ne '' && $uname ne '') {
                   6494:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  6495:             if (wantarray) {
                   6496:                 return ($env{'user.adv'},$env{'user.author'});
                   6497:             } else {
                   6498:                 return $env{'user.adv'};
                   6499:             }
1.1085    raeburn  6500:         }
                   6501:     }
1.976     raeburn  6502:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   6503:     my %allroles;
1.1128    raeburn  6504:     my ($is_adv,$is_author);
1.976     raeburn  6505:     foreach my $role (keys(%roleshash)) {
                   6506:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   6507:         my $area = '/'.$tdomain.'/'.$trest;
                   6508:         if ($sec ne '') {
                   6509:             $area .= '/'.$sec;
                   6510:         }
                   6511:         if (($area ne '') && ($trole ne '')) {
                   6512:             my $spec=$trole.'.'.$area;
                   6513:             if ($trole =~ /^cr\//) {
                   6514:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6515:             } elsif ($trole ne 'gr') {
                   6516:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6517:             }
1.1128    raeburn  6518:             if ($trole eq 'au') {
                   6519:                 $is_author = 1;
                   6520:             }
1.976     raeburn  6521:         }
                   6522:     }
                   6523:     foreach my $role (keys(%allroles)) {
                   6524:         last if ($is_adv);
                   6525:         foreach my $item (split(/:/,$allroles{$role})) {
                   6526:             if ($item ne '') {
                   6527:                 my ($privilege,$restrictions)=split(/&/,$item);
                   6528:                 if ($privilege eq 'adv') {
                   6529:                     $is_adv = 1;
                   6530:                     last;
                   6531:                 }
                   6532:             }
                   6533:         }
                   6534:     }
1.1128    raeburn  6535:     if (wantarray) {
                   6536:         return ($is_adv,$is_author);
                   6537:     }
1.976     raeburn  6538:     return $is_adv;
                   6539: }
1.798     raeburn  6540: 
1.1035    raeburn  6541: sub check_can_request {
1.1036    raeburn  6542:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  6543:     my $canreq = 0;
                   6544:     my ($types,$typename) = &Apache::loncommon::course_types();
                   6545:     my @options = ('approval','validate','autolimit');
                   6546:     my $optregex = join('|',@options);
                   6547:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   6548:         foreach my $type (@{$types}) {
                   6549:             if (&usertools_access($env{'user.name'},
                   6550:                                   $env{'user.domain'},
                   6551:                                   $type,undef,'requestcourses')) {
                   6552:                 $canreq ++;
1.1036    raeburn  6553:                 if (ref($request_domains) eq 'HASH') {
                   6554:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   6555:                 }
1.1035    raeburn  6556:                 if ($dom eq $env{'user.domain'}) {
                   6557:                     $can_request->{$type} = 1;
                   6558:                 }
                   6559:             }
                   6560:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   6561:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   6562:                 if (@curr > 0) {
1.1036    raeburn  6563:                     foreach my $item (@curr) {
                   6564:                         if (ref($request_domains) eq 'HASH') {
                   6565:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   6566:                             if ($otherdom ne '') {
                   6567:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   6568:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   6569:                                         push(@{$request_domains->{$type}},$otherdom);
                   6570:                                     }
                   6571:                                 } else {
                   6572:                                     push(@{$request_domains->{$type}},$otherdom);
                   6573:                                 }
                   6574:                             }
                   6575:                         }
                   6576:                     }
                   6577:                     unless($dom eq $env{'user.domain'}) {
                   6578:                         $canreq ++;
1.1035    raeburn  6579:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   6580:                             $can_request->{$type} = 1;
                   6581:                         }
                   6582:                     }
                   6583:                 }
                   6584:             }
                   6585:         }
                   6586:     }
                   6587:     return $canreq;
                   6588: }
                   6589: 
1.341     www      6590: # ---------------------------------------------- Custom access rule evaluation
                   6591: 
                   6592: sub customaccess {
                   6593:     my ($priv,$uri)=@_;
1.807     albertel 6594:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      6595:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 6596:     $udom = &LONCAPA::clean_domain($udom);
                   6597:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      6598:     my $access=0;
1.800     albertel 6599:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 6600: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   6601: 	if ($type eq 'user') {
                   6602: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 6603: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 6604: 		if ($tdom) {
                   6605: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   6606: 		}
1.896     albertel 6607: 		if ($tuname) {
                   6608: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 6609: 		}
                   6610: 		$access=($effect eq 'allow');
                   6611: 		last;
                   6612: 	    }
                   6613: 	} else {
                   6614: 	    if ($role) {
                   6615: 		if ($role ne $urole) { next; }
                   6616: 	    }
                   6617: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   6618: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   6619: 		if ($tdom) {
                   6620: 		    if ($tdom ne $udom) { next; }
                   6621: 		}
                   6622: 		if ($tcrs) {
                   6623: 		    if ($tcrs ne $ucrs) { next; }
                   6624: 		}
                   6625: 		if ($tsec) {
                   6626: 		    if ($tsec ne $usec) { next; }
                   6627: 		}
                   6628: 		$access=($effect eq 'allow');
                   6629: 		last;
                   6630: 	    }
                   6631: 	    if ($realm eq '' && $role eq '') {
                   6632: 		$access=($effect eq 'allow');
                   6633: 	    }
1.402     bowersj2 6634: 	}
1.341     www      6635:     }
                   6636:     return $access;
                   6637: }
                   6638: 
1.103     harris41 6639: # ------------------------------------------------- Check for a user privilege
1.12      www      6640: 
                   6641: sub allowed {
1.810     raeburn  6642:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 6643:     my $ver_orguri=$uri;
1.439     www      6644:     $uri=&deversion($uri);
1.152     www      6645:     my $orguri=$uri;
1.52      www      6646:     $uri=&declutter($uri);
1.809     raeburn  6647: 
1.810     raeburn  6648:     if ($priv eq 'evb') {
                   6649: # Evade communication block restrictions for specified role in a course
                   6650:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   6651:             return $1;
                   6652:         } else {
                   6653:             return;
                   6654:         }
                   6655:     }
                   6656: 
1.620     albertel 6657:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      6658: # Free bre access to adm and meta resources
1.775     albertel 6659:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 6660: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   6661: 	&& ($priv eq 'bre')) {
1.14      www      6662: 	return 'F';
1.159     www      6663:     }
                   6664: 
1.545     banghart 6665: # Free bre access to user's own portfolio contents
1.714     raeburn  6666:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  6667:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  6668: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  6669:         my %setters;
                   6670:         my ($startblock,$endblock) = 
                   6671:             &Apache::loncommon::blockcheck(\%setters,'port');
                   6672:         if ($startblock && $endblock) {
                   6673:             return 'B';
                   6674:         } else {
                   6675:             return 'F';
                   6676:         }
1.545     banghart 6677:     }
                   6678: 
1.762     raeburn  6679: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  6680:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   6681:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   6682:         if (exists($env{'request.course.id'})) {
                   6683:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6684:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6685:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   6686:                 my $courseprivid=$env{'request.course.id'};
                   6687:                 $courseprivid=~s/\_/\//;
                   6688:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   6689:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   6690:                     return $1; 
1.762     raeburn  6691:                 } else {
                   6692:                     if ($env{'request.course.sec'}) {
                   6693:                         $courseprivid.='/'.$env{'request.course.sec'};
                   6694:                     }
                   6695:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   6696:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   6697:                         return $2;
                   6698:                     }
1.714     raeburn  6699:                 }
                   6700:             }
                   6701:         }
                   6702:     }
                   6703: 
1.159     www      6704: # Free bre to public access
                   6705: 
                   6706:     if ($priv eq 'bre') {
1.238     www      6707:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 6708: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      6709:            return 'F'; 
                   6710:         }
1.238     www      6711:         if ($copyright eq 'priv') {
                   6712:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6713: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      6714: 		return '';
                   6715:             }
                   6716:         }
                   6717:         if ($copyright eq 'domain') {
                   6718:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6719: 	    unless (($env{'user.domain'} eq $1) ||
                   6720:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      6721: 		return '';
                   6722:             }
1.262     matthew  6723:         }
1.620     albertel 6724:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  6725:             # Library role, so allow browsing of resources in this domain.
                   6726:             return 'F';
1.238     www      6727:         }
1.341     www      6728:         if ($copyright eq 'custom') {
                   6729: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   6730:         }
1.14      www      6731:     }
1.264     matthew  6732:     # Domain coordinator is trying to create a course
1.620     albertel 6733:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  6734:         # uri is the requested domain in this case.
                   6735:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  6736:         # a role of dc for the domain in question.
1.620     albertel 6737:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  6738:     }
1.29      www      6739: 
1.52      www      6740:     my $thisallowed='';
                   6741:     my $statecond=0;
                   6742:     my $courseprivid='';
                   6743: 
1.1039    raeburn  6744:     my $ownaccess;
1.1043    raeburn  6745:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  6746:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   6747:         if ($uri eq '') {
                   6748:             $ownaccess = 1;
                   6749:         } else {
                   6750:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   6751:                 my $udom = $env{'user.domain'};
                   6752:                 my $uname = $env{'user.name'};
                   6753:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   6754:                     $ownaccess = 1;
1.1040    raeburn  6755:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  6756:                     unless ($uri =~ m{\.\./}) {
                   6757:                         $ownaccess = 1;
                   6758:                     }
                   6759:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   6760:                     my $now = time;
                   6761:                     if ($uri =~ m{^([^/]+)/?$}) {
                   6762:                         my $adom = $1;
                   6763:                         foreach my $key (keys(%env)) {
1.1042    raeburn  6764:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  6765:                                 my ($start,$end) = split('.',$env{$key});
                   6766:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6767:                                     $ownaccess = 1;
                   6768:                                     last;
                   6769:                                 }
                   6770:                             }
                   6771:                         }
                   6772:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   6773:                         my $adom = $1;
                   6774:                         my $aname = $2;
1.1042    raeburn  6775:                         foreach my $role ('ca','aa') { 
                   6776:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   6777:                                 my ($start,$end) =
                   6778:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   6779:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6780:                                     $ownaccess = 1;
                   6781:                                     last;
                   6782:                                 }
1.1039    raeburn  6783:                             }
                   6784:                         }
                   6785:                     }
                   6786:                 }
                   6787:             }
                   6788:         }
                   6789:     }
                   6790: 
1.52      www      6791: # Course
                   6792: 
1.620     albertel 6793:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6794:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6795:             $thisallowed.=$1;
                   6796:         }
1.52      www      6797:     }
1.29      www      6798: 
1.52      www      6799: # Domain
                   6800: 
1.620     albertel 6801:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 6802:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6803:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6804:             $thisallowed.=$1;
                   6805:         }
1.12      www      6806:     }
1.52      www      6807: 
1.1141    raeburn  6808: # User who is not author or co-author might still be able to edit
                   6809: # resource of an author in the domain (e.g., if Domain Coordinator).
                   6810:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   6811:         (&allowed('mdc',$env{'request.course.id'}))) {
                   6812:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   6813:             $thisallowed.=$1;
                   6814:         }
                   6815:     }
                   6816: 
1.52      www      6817: # Course: uri itself is a course
1.66      www      6818:     my $courseuri=$uri;
                   6819:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      6820:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      6821: 
1.620     albertel 6822:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 6823:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6824:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6825:             $thisallowed.=$1;
                   6826:         }
1.12      www      6827:     }
1.29      www      6828: 
1.665     albertel 6829: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 6830: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 6831:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 6832: 	$thisallowed='';
1.671     raeburn  6833:         my ($match)=&is_on_map($uri);
                   6834:         if ($match) {
                   6835:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   6836:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6837:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6838:                 if (@blockers > 0) {
                   6839:                     $thisallowed = 'B';
                   6840:                 } else {
                   6841:                     $thisallowed.=$1;
                   6842:                 }
1.671     raeburn  6843:             }
                   6844:         } else {
1.705     albertel 6845:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  6846:             if ($refuri) {
                   6847:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  6848:                     $thisallowed='F';
1.671     raeburn  6849:                 } else {
                   6850:                     $refuri=&declutter($refuri);
                   6851:                     my ($match) = &is_on_map($refuri);
                   6852:                     if ($match) {
1.1162    raeburn  6853:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6854:                         if (@blockers > 0) {
                   6855:                             $thisallowed = 'B';
                   6856:                         } else {
                   6857:                             $thisallowed='F';
                   6858:                         }
1.671     raeburn  6859:                     }
1.669     raeburn  6860:                 }
1.671     raeburn  6861:             }
                   6862:         }
1.314     www      6863:     }
1.492     albertel 6864: 
1.766     albertel 6865:     if ($priv eq 'bre'
                   6866: 	&& $thisallowed ne 'F' 
                   6867: 	&& $thisallowed ne '2'
                   6868: 	&& &is_portfolio_url($uri)) {
                   6869: 	$thisallowed = &portfolio_access($uri);
                   6870:     }
                   6871:     
1.52      www      6872: # Full access at system, domain or course-wide level? Exit.
1.29      www      6873:     if ($thisallowed=~/F/) {
                   6874: 	return 'F';
                   6875:     }
                   6876: 
1.52      www      6877: # If this is generating or modifying users, exit with special codes
1.29      www      6878: 
1.643     www      6879:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   6880: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 6881: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      6882: # no author name given, so this just checks on the general right to make a co-author in this domain
                   6883: 	    unless ($auname) { return $thisallowed; }
                   6884: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 6885: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   6886: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   6887: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   6888: 	}
1.52      www      6889: 	return $thisallowed;
                   6890:     }
                   6891: #
1.103     harris41 6892: # Gathered so far: system, domain and course wide privileges
1.52      www      6893: #
                   6894: # Course: See if uri or referer is an individual resource that is part of 
                   6895: # the course
                   6896: 
1.620     albertel 6897:     if ($env{'request.course.id'}) {
1.232     www      6898: 
1.620     albertel 6899:        $courseprivid=$env{'request.course.id'};
                   6900:        if ($env{'request.course.sec'}) {
                   6901:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      6902:        }
                   6903:        $courseprivid=~s/\_/\//;
                   6904:        my $checkreferer=1;
1.232     www      6905:        my ($match,$cond)=&is_on_map($uri);
                   6906:        if ($match) {
                   6907:            $statecond=$cond;
1.620     albertel 6908:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6909:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6910:                my $value = $1;
                   6911:                if ($priv eq 'bre') {
                   6912:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6913:                    if (@blockers > 0) {
                   6914:                        $thisallowed = 'B';
                   6915:                    } else {
                   6916:                        $thisallowed.=$value;
                   6917:                    }
                   6918:                } else {
                   6919:                    $thisallowed.=$value;
                   6920:                }
1.52      www      6921:                $checkreferer=0;
                   6922:            }
1.29      www      6923:        }
1.83      www      6924:        
1.148     www      6925:        if ($checkreferer) {
1.620     albertel 6926: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      6927:             unless ($refuri) {
1.800     albertel 6928:                 foreach my $key (keys(%env)) {
                   6929: 		    if ($key=~/^httpref\..*\*/) {
                   6930: 			my $pattern=$key;
1.156     www      6931:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      6932:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   6933:                         $pattern=~s/\//\\\//g;
1.152     www      6934:                         if ($orguri=~/$pattern/) {
1.800     albertel 6935: 			    $refuri=$env{$key};
1.148     www      6936:                         }
                   6937:                     }
1.191     harris41 6938:                 }
1.148     www      6939:             }
1.232     www      6940: 
1.148     www      6941:          if ($refuri) { 
1.152     www      6942: 	  $refuri=&declutter($refuri);
1.232     www      6943:           my ($match,$cond)=&is_on_map($refuri);
                   6944:             if ($match) {
                   6945:               my $refstatecond=$cond;
1.620     albertel 6946:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6947:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6948:                   my $value = $1;
                   6949:                   if ($priv eq 'bre') {
                   6950:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6951:                       if (@blockers > 0) {
                   6952:                           $thisallowed = 'B';
                   6953:                       } else {
                   6954:                           $thisallowed.=$value;
                   6955:                       }
                   6956:                   } else {
                   6957:                       $thisallowed.=$value;
                   6958:                   }
1.53      www      6959:                   $uri=$refuri;
                   6960:                   $statecond=$refstatecond;
1.52      www      6961:               }
                   6962:           }
1.148     www      6963:         }
1.29      www      6964:        }
1.52      www      6965:    }
1.29      www      6966: 
1.52      www      6967: #
1.103     harris41 6968: # Gathered now: all privileges that could apply, and condition number
1.52      www      6969: # 
                   6970: #
                   6971: # Full or no access?
                   6972: #
1.29      www      6973: 
1.52      www      6974:     if ($thisallowed=~/F/) {
                   6975: 	return 'F';
                   6976:     }
1.29      www      6977: 
1.52      www      6978:     unless ($thisallowed) {
                   6979:         return '';
                   6980:     }
1.29      www      6981: 
1.52      www      6982: # Restrictions exist, deal with them
                   6983: #
                   6984: #   C:according to course preferences
                   6985: #   R:according to resource settings
                   6986: #   L:unless locked
                   6987: #   X:according to user session state
                   6988: #
                   6989: 
                   6990: # Possibly locked functionality, check all courses
1.54      www      6991: # Locks might take effect only after 10 minutes cache expiration for other
                   6992: # courses, and 2 minutes for current course
1.52      www      6993: 
                   6994:     my $envkey;
                   6995:     if ($thisallowed=~/L/) {
1.1000    raeburn  6996:         foreach $envkey (keys(%env)) {
1.54      www      6997:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   6998:                my $courseid=$2;
                   6999:                my $roleid=$1.'.'.$2;
1.92      www      7000:                $courseid=~s/^\///;
1.54      www      7001:                my $expiretime=600;
1.620     albertel 7002:                if ($env{'request.role'} eq $roleid) {
1.54      www      7003: 		  $expiretime=120;
                   7004:                }
                   7005: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   7006:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 7007:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 7008: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      7009:                }
1.620     albertel 7010:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7011:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   7012: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   7013:                        &log($env{'user.domain'},$env{'user.name'},
                   7014:                             $env{'user.home'},
1.57      www      7015:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      7016:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7017:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7018: 		       return '';
                   7019:                    }
                   7020:                }
1.620     albertel 7021:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7022:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   7023: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   7024:                        &log($env{'user.domain'},$env{'user.name'},
                   7025:                             $env{'user.home'},
1.57      www      7026:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      7027:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7028:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7029: 		       return '';
                   7030:                    }
                   7031:                }
                   7032: 	   }
1.29      www      7033:        }
1.52      www      7034:     }
                   7035:    
                   7036: #
                   7037: # Rest of the restrictions depend on selected course
                   7038: #
                   7039: 
1.620     albertel 7040:     unless ($env{'request.course.id'}) {
1.766     albertel 7041: 	if ($thisallowed eq 'A') {
                   7042: 	    return 'A';
1.814     raeburn  7043:         } elsif ($thisallowed eq 'B') {
                   7044:             return 'B';
1.766     albertel 7045: 	} else {
                   7046: 	    return '1';
                   7047: 	}
1.52      www      7048:     }
1.29      www      7049: 
1.52      www      7050: #
                   7051: # Now user is definitely in a course
                   7052: #
1.53      www      7053: 
                   7054: 
                   7055: # Course preferences
                   7056: 
                   7057:    if ($thisallowed=~/C/) {
1.620     albertel 7058:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   7059:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   7060:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 7061: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  7062: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7063: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7064: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   7065: 			$env{'request.course.id'});
                   7066: 	   }
1.237     www      7067:            return '';
                   7068:        }
                   7069: 
1.620     albertel 7070:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 7071: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  7072: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7073: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   7074: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   7075: 			$env{'request.course.id'});
                   7076: 	   }
1.54      www      7077:            return '';
                   7078:        }
1.53      www      7079:    }
                   7080: 
                   7081: # Resource preferences
                   7082: 
                   7083:    if ($thisallowed=~/R/) {
1.620     albertel 7084:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 7085:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  7086: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7087: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7088: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   7089: 	   }
                   7090: 	   return '';
1.54      www      7091:        }
1.53      www      7092:    }
1.30      www      7093: 
1.246     www      7094: # Restricted by state or randomout?
1.30      www      7095: 
1.52      www      7096:    if ($thisallowed=~/X/) {
1.620     albertel 7097:       if ($env{'acc.randomout'}) {
1.579     albertel 7098: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 7099:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      7100:             return ''; 
                   7101:          }
1.247     www      7102:       }
                   7103:       if (&condval($statecond)) {
1.52      www      7104: 	 return '2';
                   7105:       } else {
                   7106:          return '';
                   7107:       }
                   7108:    }
1.30      www      7109: 
1.766     albertel 7110:     if ($thisallowed eq 'A') {
                   7111: 	return 'A';
1.814     raeburn  7112:     } elsif ($thisallowed eq 'B') {
                   7113:         return 'B';
1.766     albertel 7114:     }
1.52      www      7115:    return 'F';
1.232     www      7116: }
1.1162    raeburn  7117: 
1.1172.2.13  raeburn  7118: # ------------------------------------------- Check construction space access
                   7119: 
                   7120: sub constructaccess {
                   7121:     my ($url,$setpriv)=@_;
                   7122: 
                   7123: # We do not allow editing of previous versions of files
                   7124:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   7125: 
                   7126: # Get username and domain from URL
                   7127:     my ($ownername,$ownerdomain,$ownerhome);
                   7128: 
                   7129:     ($ownerdomain,$ownername) =
                   7130:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
                   7131: 
                   7132: # The URL does not really point to any authorspace, forget it
                   7133:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   7134: 
                   7135: # Now we need to see if the user has access to the authorspace of
                   7136: # $ownername at $ownerdomain
                   7137: 
                   7138:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   7139: # Real author for this?
                   7140:        $ownerhome = $env{'user.home'};
                   7141:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   7142:           return ($ownername,$ownerdomain,$ownerhome);
                   7143:        }
                   7144:     } else {
                   7145: # Co-author for this?
                   7146:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   7147:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   7148:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   7149:             return ($ownername,$ownerdomain,$ownerhome);
                   7150:         }
                   7151:     }
                   7152: 
                   7153: # We don't have any access right now. If we are not possibly going to do anything about this,
                   7154: # we might as well leave
                   7155:    unless ($setpriv) { return ''; }
                   7156: 
                   7157: # Backdoor access?
                   7158:     my $allowed=&allowed('eco',$ownerdomain);
                   7159: # Nope
                   7160:     unless ($allowed) { return ''; }
                   7161: # Looks like we may have access, but could be locked by the owner of the construction space
                   7162:     if ($allowed eq 'U') {
                   7163:         my %blocked=&get('environment',['domcoord.author'],
                   7164:                          $ownerdomain,$ownername);
                   7165: # Is blocked by owner
                   7166:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   7167:     }
                   7168:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   7169: # Grant temporary access
                   7170:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  7171:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  7172:         if (!$update) { $update = $then; }
                   7173:         my $refresh=$env{'user.refresh.time'};
                   7174:         if (!$refresh) { $refresh = $update; }
                   7175:         my $now = time;
                   7176:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   7177:                            $now,'ca','constructaccess');
                   7178:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   7179:         return($ownername,$ownerdomain,$ownerhome);
                   7180:     }
                   7181: # No business here
                   7182:     return '';
                   7183: }
                   7184: 
1.1162    raeburn  7185: sub get_comm_blocks {
                   7186:     my ($cdom,$cnum) = @_;
                   7187:     if ($cdom eq '' || $cnum eq '') {
                   7188:         return unless ($env{'request.course.id'});
                   7189:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7190:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7191:     }
                   7192:     my %commblocks;
                   7193:     my $hashid=$cdom.'_'.$cnum;
                   7194:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   7195:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   7196:         %commblocks = %{$blocksref};
                   7197:     } else {
                   7198:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   7199:         my $cachetime = 600;
                   7200:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   7201:     }
                   7202:     return %commblocks;
                   7203: }
                   7204: 
                   7205: sub has_comm_blocking {
                   7206:     my ($priv,$symb,$uri,$blocks) = @_;
                   7207:     return unless ($env{'request.course.id'});
                   7208:     return unless ($priv eq 'bre');
                   7209:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   7210:     my %commblocks;
                   7211:     if (ref($blocks) eq 'HASH') {
                   7212:         %commblocks = %{$blocks};
                   7213:     } else {
                   7214:         %commblocks = &get_comm_blocks();
                   7215:     }
                   7216:     return unless (keys(%commblocks) > 0);
                   7217:     if (!$symb) { $symb=&symbread($uri,1); }
                   7218:     my ($map,$resid,undef)=&decode_symb($symb);
                   7219:     my %tocheck = (
                   7220:                     maps      => $map,
                   7221:                     resources => $symb,
                   7222:                   );
                   7223:     my @blockers;
                   7224:     my $now = time;
1.1163    raeburn  7225:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1162    raeburn  7226:     foreach my $block (keys(%commblocks)) {
                   7227:         if ($block =~ /^(\d+)____(\d+)$/) {
                   7228:             my ($start,$end) = ($1,$2);
                   7229:             if ($start <= $now && $end >= $now) {
                   7230:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7231:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7232:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   7233:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
                   7234:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   7235:                                     push(@blockers,$block);
                   7236:                                 }
                   7237:                             }
                   7238:                         }
                   7239:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   7240:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
                   7241:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
                   7242:                                     push(@blockers,$block);
                   7243:                                 }
                   7244:                             }
                   7245:                         }
                   7246:                     }
                   7247:                 }
                   7248:             }
                   7249:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   7250:             my $item = $1;
1.1163    raeburn  7251:             my @to_test;
1.1162    raeburn  7252:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7253:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7254:                     my $check_interval;
                   7255:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
                   7256:                         my @interval;
                   7257:                         my $type = 'map';
                   7258:                         if ($item eq 'course') {
                   7259:                             $type = 'course';
                   7260:                             @interval=&EXT("resource.0.interval");
                   7261:                         } else {
                   7262:                             if ($item =~ /___\d+___/) {
                   7263:                                 $type = 'resource';
                   7264:                                 @interval=&EXT("resource.0.interval",$item);
1.1163    raeburn  7265:                                 if (ref($navmap)) {                        
                   7266:                                     my $res = $navmap->getBySymb($item); 
                   7267:                                     push(@to_test,$res);
                   7268:                                 }
1.1162    raeburn  7269:                             } else {
                   7270:                                 my $mapsymb = &symbread($item,1);
                   7271:                                 if ($mapsymb) {
                   7272:                                     if (ref($navmap)) {
                   7273:                                         my $mapres = $navmap->getBySymb($mapsymb);
1.1163    raeburn  7274:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
                   7275:                                         foreach my $res (@to_test) {
1.1162    raeburn  7276:                                             my $symb = $res->symb();
                   7277:                                             next if ($symb eq $mapsymb);
                   7278:                                             if ($symb ne '') {
                   7279:                                                 @interval=&EXT("resource.0.interval",$symb);
                   7280:                                                 last;
                   7281:                                             }
                   7282:                                         }
                   7283:                                     }
                   7284:                                 }
                   7285:                             }
                   7286:                         }
                   7287:                         if ($interval[0] =~ /\d+/) {
                   7288:                             my $first_access;
                   7289:                             if ($type eq 'resource') {
                   7290:                                 $first_access=&get_first_access($interval[1],$item);
                   7291:                             } elsif ($type eq 'map') {
                   7292:                                 $first_access=&get_first_access($interval[1],undef,$item);
                   7293:                             } else {
                   7294:                                 $first_access=&get_first_access($interval[1]);
                   7295:                             }
                   7296:                             if ($first_access) {
                   7297:                                 my $timesup = $first_access+$interval[0];
                   7298:                                 if ($timesup > $now) {
1.1163    raeburn  7299:                                     foreach my $res (@to_test) {
                   7300:                                         if ($res->is_problem()) {
                   7301:                                             if ($res->completable()) {
                   7302:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   7303:                                                     push(@blockers,$block);
                   7304:                                                 }
                   7305:                                                 last;
                   7306:                                             }
                   7307:                                         }
1.1162    raeburn  7308:                                     }
                   7309:                                 }
                   7310:                             }
                   7311:                         }
                   7312:                     }
                   7313:                 }
                   7314:             }
                   7315:         }
                   7316:     }
                   7317:     return @blockers;
                   7318: }
                   7319: 
                   7320: sub check_docs_block {
                   7321:     my ($docsblock,$tocheck) =@_;
                   7322:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
                   7323:         return;
                   7324:     }
                   7325:     if (ref($docsblock->{'maps'}) eq 'HASH') {
                   7326:         if ($tocheck->{'maps'}) {
                   7327:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
                   7328:                 return 1;
                   7329:             }
                   7330:         }
                   7331:     }
                   7332:     if (ref($docsblock->{'resources'}) eq 'HASH') {
                   7333:         if ($tocheck->{'resources'}) {
                   7334:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
                   7335:                 return 1;
                   7336:             }
                   7337:         }
                   7338:     }
                   7339:     return;
                   7340: }
                   7341: 
1.1133    foxr     7342: #
                   7343: #   Removes the versino from a URI and
                   7344: #   splits it in to its filename and path to the filename.
                   7345: #   Seems like File::Basename could have done this more clearly.
                   7346: #   Parameters:
                   7347: #      $uri   - input URI
                   7348: #   Returns:
                   7349: #     Two element list consisting of 
                   7350: #     $pathname  - the URI up to and excluding the trailing /
                   7351: #     $filename  - The part of the URI following the last /
                   7352: #  NOTE:
                   7353: #    Another realization of this is simply:
                   7354: #    use File::Basename;
                   7355: #    ...
                   7356: #    $uri = shift;
                   7357: #    $filename = basename($uri);
                   7358: #    $path     = dirname($uri);
                   7359: #    return ($filename, $path);
                   7360: #
                   7361: #     The implementation below is probably faster however.
                   7362: #
1.710     albertel 7363: sub split_uri_for_cond {
                   7364:     my $uri=&deversion(&declutter(shift));
                   7365:     my @uriparts=split(/\//,$uri);
                   7366:     my $filename=pop(@uriparts);
                   7367:     my $pathname=join('/',@uriparts);
                   7368:     return ($pathname,$filename);
                   7369: }
1.232     www      7370: # --------------------------------------------------- Is a resource on the map?
                   7371: 
                   7372: sub is_on_map {
1.710     albertel 7373:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 7374:     #Trying to find the conditional for the file
1.620     albertel 7375:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 7376: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      7377:     if ($match) {
1.289     bowersj2 7378: 	return (1,$1);
                   7379:     } else {
1.434     www      7380: 	return (0,0);
1.289     bowersj2 7381:     }
1.12      www      7382: }
                   7383: 
1.427     www      7384: # --------------------------------------------------------- Get symb from alias
                   7385: 
                   7386: sub get_symb_from_alias {
                   7387:     my $symb=shift;
                   7388:     my ($map,$resid,$url)=&decode_symb($symb);
                   7389: # Already is a symb
                   7390:     if ($url) { return $symb; }
                   7391: # Must be an alias
                   7392:     my $aliassymb='';
                   7393:     my %bighash;
1.620     albertel 7394:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      7395:                             &GDBM_READER(),0640)) {
                   7396:         my $rid=$bighash{'mapalias_'.$symb};
                   7397: 	if ($rid) {
                   7398: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 7399: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   7400: 				    $resid,$bighash{'src_'.$rid});
1.427     www      7401: 	}
                   7402:         untie %bighash;
                   7403:     }
                   7404:     return $aliassymb;
                   7405: }
                   7406: 
1.12      www      7407: # ----------------------------------------------------------------- Define Role
                   7408: 
                   7409: sub definerole {
                   7410:   if (allowed('mcr','/')) {
                   7411:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 7412:     foreach my $role (split(':',$sysrole)) {
                   7413: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7414:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   7415:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   7416: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7417:                return "refused:s:$crole&$cqual"; 
                   7418:             }
                   7419:         }
1.191     harris41 7420:     }
1.800     albertel 7421:     foreach my $role (split(':',$domrole)) {
                   7422: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7423:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   7424:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   7425: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      7426:                return "refused:d:$crole&$cqual"; 
                   7427:             }
                   7428:         }
1.191     harris41 7429:     }
1.800     albertel 7430:     foreach my $role (split(':',$courole)) {
                   7431: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7432:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   7433:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   7434: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7435:                return "refused:c:$crole&$cqual"; 
                   7436:             }
                   7437:         }
1.191     harris41 7438:     }
1.620     albertel 7439:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   7440:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7441: 	        "rolesdef_$rolename=".
                   7442:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 7443:     return reply($command,$env{'user.home'});
1.12      www      7444:   } else {
                   7445:     return 'refused';
                   7446:   }
1.105     harris41 7447: }
                   7448: 
                   7449: # ---------------- Make a metadata query against the network of library servers
                   7450: 
                   7451: sub metadata_query {
1.1172.2.33  raeburn  7452:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 7453:     my %rhash;
1.845     albertel 7454:     my %libserv = &all_library();
1.244     matthew  7455:     my @server_list = (defined($server_array) ? @$server_array
                   7456:                                               : keys(%libserv) );
                   7457:     for my $server (@server_list) {
1.1172.2.33  raeburn  7458:         my $domains = '';
                   7459:         if (ref($domains_hash) eq 'HASH') {
                   7460:             $domains = $domains_hash->{$server};    
                   7461:         }
1.118     harris41 7462: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  7463: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 7464: 	    $rhash{$server}=$reply;
                   7465: 	}
                   7466: 	else {
                   7467: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  7468: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 7469: 			     $server);
                   7470: 	    $rhash{$server}=$reply;
                   7471: 	}
1.112     harris41 7472:     }
1.118     harris41 7473:     return \%rhash;
1.240     www      7474: }
                   7475: 
                   7476: # ----------------------------------------- Send log queries and wait for reply
                   7477: 
                   7478: sub log_query {
                   7479:     my ($uname,$udom,$query,%filters)=@_;
                   7480:     my $uhome=&homeserver($uname,$udom);
                   7481:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 7482:     my $uhost=&hostname($uhome);
1.800     albertel 7483:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      7484:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   7485:                        $uhome);
1.479     albertel 7486:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      7487:     return get_query_reply($queryid);
                   7488: }
                   7489: 
1.818     raeburn  7490: # -------------------------- Update MySQL table for portfolio file
                   7491: 
                   7492: sub update_portfolio_table {
1.821     raeburn  7493:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  7494:     if ($group ne '') {
                   7495:         $file_name =~s /^\Q$group\E//;
                   7496:     }
1.818     raeburn  7497:     my $homeserver = &homeserver($uname,$udom);
                   7498:     my $queryid=
1.821     raeburn  7499:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   7500:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  7501:     my $reply = &get_query_reply($queryid);
                   7502:     return $reply;
                   7503: }
                   7504: 
1.899     raeburn  7505: # -------------------------- Update MySQL allusers table
                   7506: 
                   7507: sub update_allusers_table {
                   7508:     my ($uname,$udom,$names) = @_;
                   7509:     my $homeserver = &homeserver($uname,$udom);
                   7510:     my $queryid=
                   7511:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   7512:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   7513:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   7514:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   7515:                'generation='.&escape($names->{'generation'}).'%%'.
                   7516:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   7517:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  7518:     return;
1.899     raeburn  7519: }
                   7520: 
1.508     raeburn  7521: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  7522: 
                   7523: sub fetch_enrollment_query {
1.511     raeburn  7524:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  7525:     my $homeserver;
1.547     raeburn  7526:     my $maxtries = 1;
1.508     raeburn  7527:     if ($context eq 'automated') {
                   7528:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  7529:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  7530:     } else {
                   7531:         $homeserver = &homeserver($cnum,$dom);
                   7532:     }
1.838     albertel 7533:     my $host=&hostname($homeserver);
1.506     raeburn  7534:     my $cmd = '';
1.1000    raeburn  7535:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 7536:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  7537:     }
                   7538:     $cmd =~ s/%%$//;
                   7539:     $cmd = &escape($cmd);
                   7540:     my $query = 'fetchenrollment';
1.620     albertel 7541:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  7542:     unless ($queryid=~/^\Q$host\E\_/) { 
                   7543:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   7544:         return 'error: '.$queryid;
                   7545:     }
1.506     raeburn  7546:     my $reply = &get_query_reply($queryid);
1.547     raeburn  7547:     my $tries = 1;
                   7548:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7549:         $reply = &get_query_reply($queryid);
                   7550:         $tries ++;
                   7551:     }
1.526     raeburn  7552:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 7553:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  7554:     } else {
1.901     albertel 7555:         my @responses = split(/:/,$reply);
1.515     raeburn  7556:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 7557:             foreach my $line (@responses) {
                   7558:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  7559:                 $$replyref{$key} = $value;
                   7560:             }
                   7561:         } else {
1.1117    foxr     7562:             my $pathname = LONCAPA::tempdir();
1.800     albertel 7563:             foreach my $line (@responses) {
                   7564:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  7565:                 $$replyref{$key} = $value;
                   7566:                 if ($value > 0) {
1.800     albertel 7567:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   7568:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  7569:                         my $destname = $pathname.'/'.$filename;
                   7570:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  7571:                         if ($xml_classlist =~ /^error/) {
                   7572:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   7573:                         } else {
1.506     raeburn  7574:                             if ( open(FILE,">$destname") ) {
                   7575:                                 print FILE &unescape($xml_classlist);
                   7576:                                 close(FILE);
1.526     raeburn  7577:                             } else {
                   7578:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  7579:                             }
                   7580:                         }
                   7581:                     }
                   7582:                 }
                   7583:             }
                   7584:         }
                   7585:         return 'ok';
                   7586:     }
                   7587:     return 'error';
                   7588: }
                   7589: 
1.242     www      7590: sub get_query_reply {
                   7591:     my $queryid=shift;
1.1117    foxr     7592:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      7593:     my $reply='';
                   7594:     for (1..100) {
                   7595: 	sleep 2;
                   7596:         if (-e $replyfile.'.end') {
1.448     albertel 7597: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 7598: 		$reply = join('',<$fh>);
                   7599: 		close($fh);
1.240     www      7600: 	   } else { return 'error: reply_file_error'; }
1.242     www      7601:            return &unescape($reply);
                   7602: 	}
1.240     www      7603:     }
1.242     www      7604:     return 'timeout:'.$queryid;
1.240     www      7605: }
                   7606: 
                   7607: sub courselog_query {
1.241     www      7608: #
                   7609: # possible filters:
                   7610: # url: url or symb
                   7611: # username
                   7612: # domain
                   7613: # action: view, submit, grade
                   7614: # start: timestamp
                   7615: # end: timestamp
                   7616: #
1.240     www      7617:     my (%filters)=@_;
1.620     albertel 7618:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      7619:     if ($filters{'url'}) {
                   7620: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   7621:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   7622:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   7623:     }
1.620     albertel 7624:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7625:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      7626:     return &log_query($cname,$cdom,'courselog',%filters);
                   7627: }
                   7628: 
                   7629: sub userlog_query {
1.858     raeburn  7630: #
                   7631: # possible filters:
                   7632: # action: log check role
                   7633: # start: timestamp
                   7634: # end: timestamp
                   7635: #
1.240     www      7636:     my ($uname,$udom,%filters)=@_;
                   7637:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      7638: }
                   7639: 
1.506     raeburn  7640: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   7641: 
                   7642: sub auto_run {
1.508     raeburn  7643:     my ($cnum,$cdom) = @_;
1.876     raeburn  7644:     my $response = 0;
                   7645:     my $settings;
                   7646:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   7647:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   7648:         $settings = $domconfig{'autoenroll'};
                   7649:         if ($settings->{'run'} eq '1') {
                   7650:             $response = 1;
                   7651:         }
                   7652:     } else {
1.934     raeburn  7653:         my $homeserver;
                   7654:         if (&is_course($cdom,$cnum)) {
                   7655:             $homeserver = &homeserver($cnum,$cdom);
                   7656:         } else {
                   7657:             $homeserver = &domain($cdom,'primary');
                   7658:         }
                   7659:         if ($homeserver ne 'no_host') {
                   7660:             $response = &reply('autorun:'.$cdom,$homeserver);
                   7661:         }
1.876     raeburn  7662:     }
1.506     raeburn  7663:     return $response;
                   7664: }
1.776     albertel 7665: 
1.506     raeburn  7666: sub auto_get_sections {
1.508     raeburn  7667:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  7668:     my $homeserver;
                   7669:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   7670:         $homeserver = &homeserver($cnum,$cdom);
                   7671:     }
                   7672:     if (!defined($homeserver)) { 
                   7673:         if ($cdom =~ /^$match_domain$/) {
                   7674:             $homeserver = &domain($cdom,'primary');
                   7675:         }
                   7676:     }
                   7677:     my @secs;
                   7678:     if (defined($homeserver)) {
                   7679:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   7680:         unless ($response eq 'refused') {
                   7681:             @secs = split(/:/,$response);
                   7682:         }
1.506     raeburn  7683:     }
                   7684:     return @secs;
                   7685: }
1.776     albertel 7686: 
1.506     raeburn  7687: sub auto_new_course {
1.1099    raeburn  7688:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  7689:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  7690:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  7691:     return $response;
                   7692: }
1.776     albertel 7693: 
1.506     raeburn  7694: sub auto_validate_courseID {
1.508     raeburn  7695:     my ($cnum,$cdom,$inst_course_id) = @_;
                   7696:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  7697:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  7698:     return $response;
                   7699: }
1.776     albertel 7700: 
1.1007    raeburn  7701: sub auto_validate_instcode {
1.1020    raeburn  7702:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  7703:     my ($homeserver,$response);
                   7704:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7705:         $homeserver = &homeserver($cnum,$cdom);
                   7706:     }
                   7707:     if (!defined($homeserver)) {
                   7708:         if ($cdom =~ /^$match_domain$/) {
                   7709:             $homeserver = &domain($cdom,'primary');
                   7710:         }
                   7711:     }
1.1065    raeburn  7712:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   7713:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  7714:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   7715:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  7716: }
                   7717: 
1.506     raeburn  7718: sub auto_create_password {
1.873     raeburn  7719:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   7720:     my ($homeserver,$response);
1.506     raeburn  7721:     my $create_passwd = 0;
                   7722:     my $authchk = '';
1.873     raeburn  7723:     if ($udom =~ /^$match_domain$/) {
                   7724:         $homeserver = &domain($udom,'primary');
                   7725:     }
                   7726:     if ($homeserver eq '') {
                   7727:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7728:             $homeserver = &homeserver($cnum,$cdom);
                   7729:         }
                   7730:     }
                   7731:     if ($homeserver eq '') {
                   7732:         $authchk = 'nodomain';
1.506     raeburn  7733:     } else {
1.873     raeburn  7734:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   7735:         if ($response eq 'refused') {
                   7736:             $authchk = 'refused';
                   7737:         } else {
1.901     albertel 7738:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  7739:         }
1.506     raeburn  7740:     }
                   7741:     return ($authparam,$create_passwd,$authchk);
                   7742: }
                   7743: 
1.706     raeburn  7744: sub auto_photo_permission {
                   7745:     my ($cnum,$cdom,$students) = @_;
                   7746:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 7747:     my ($outcome,$perm_reqd,$conditions) = 
                   7748: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 7749:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7750: 	return (undef,undef);
                   7751:     }
1.706     raeburn  7752:     return ($outcome,$perm_reqd,$conditions);
                   7753: }
                   7754: 
                   7755: sub auto_checkphotos {
                   7756:     my ($uname,$udom,$pid) = @_;
                   7757:     my $homeserver = &homeserver($uname,$udom);
                   7758:     my ($result,$resulttype);
                   7759:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 7760: 				   &escape($uname).':'.&escape($pid),
                   7761: 				   $homeserver));
1.709     albertel 7762:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7763: 	return (undef,undef);
                   7764:     }
1.706     raeburn  7765:     if ($outcome) {
                   7766:         ($result,$resulttype) = split(/:/,$outcome);
                   7767:     } 
                   7768:     return ($result,$resulttype);
                   7769: }
                   7770: 
                   7771: sub auto_photochoice {
                   7772:     my ($cnum,$cdom) = @_;
                   7773:     my $homeserver = &homeserver($cnum,$cdom);
                   7774:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 7775: 						       &escape($cdom),
                   7776: 						       $homeserver)));
1.709     albertel 7777:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7778: 	return (undef,undef);
                   7779:     }
1.706     raeburn  7780:     return ($update,$comment);
                   7781: }
                   7782: 
                   7783: sub auto_photoupdate {
                   7784:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   7785:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 7786:     my $host=&hostname($homeserver);
1.706     raeburn  7787:     my $cmd = '';
                   7788:     my $maxtries = 1;
1.800     albertel 7789:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   7790:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  7791:     }
                   7792:     $cmd =~ s/%%$//;
                   7793:     $cmd = &escape($cmd);
                   7794:     my $query = 'institutionalphotos';
                   7795:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   7796:     unless ($queryid=~/^\Q$host\E\_/) {
                   7797:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   7798:         return 'error: '.$queryid;
                   7799:     }
                   7800:     my $reply = &get_query_reply($queryid);
                   7801:     my $tries = 1;
                   7802:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7803:         $reply = &get_query_reply($queryid);
                   7804:         $tries ++;
                   7805:     }
                   7806:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   7807:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   7808:     } else {
                   7809:         my @responses = split(/:/,$reply);
                   7810:         my $outcome = shift(@responses); 
                   7811:         foreach my $item (@responses) {
                   7812:             my ($key,$value) = split(/=/,$item);
                   7813:             $$photo{$key} = $value;
                   7814:         }
                   7815:         return $outcome;
                   7816:     }
                   7817:     return 'error';
                   7818: }
                   7819: 
1.521     raeburn  7820: sub auto_instcode_format {
1.793     albertel 7821:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   7822: 	$cat_order) = @_;
1.521     raeburn  7823:     my $courses = '';
1.772     raeburn  7824:     my @homeservers;
1.521     raeburn  7825:     if ($caller eq 'global') {
1.841     albertel 7826: 	my %servers = &get_servers($codedom,'library');
                   7827: 	foreach my $tryserver (keys(%servers)) {
                   7828: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7829: 		push(@homeservers,$tryserver);
                   7830: 	    }
1.584     raeburn  7831:         }
1.1022    raeburn  7832:     } elsif ($caller eq 'requests') {
                   7833:         if ($codedom =~ /^$match_domain$/) {
                   7834:             my $chome = &domain($codedom,'primary');
                   7835:             unless ($chome eq 'no_host') {
                   7836:                 push(@homeservers,$chome);
                   7837:             }
                   7838:         }
1.521     raeburn  7839:     } else {
1.772     raeburn  7840:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  7841:     }
1.793     albertel 7842:     foreach my $code (keys(%{$instcodes})) {
                   7843:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  7844:     }
                   7845:     chop($courses);
1.772     raeburn  7846:     my $ok_response = 0;
                   7847:     my $response;
                   7848:     while (@homeservers > 0 && $ok_response == 0) {
                   7849:         my $server = shift(@homeservers); 
                   7850:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   7851:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   7852:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 7853: 		split(/:/,$response);
1.772     raeburn  7854:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   7855:             push(@{$codetitles},&str2array($codetitles_str));
                   7856:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   7857:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   7858:             $ok_response = 1;
                   7859:         }
                   7860:     }
                   7861:     if ($ok_response) {
1.521     raeburn  7862:         return 'ok';
1.772     raeburn  7863:     } else {
                   7864:         return $response;
1.521     raeburn  7865:     }
                   7866: }
                   7867: 
1.792     raeburn  7868: sub auto_instcode_defaults {
                   7869:     my ($domain,$returnhash,$code_order) = @_;
                   7870:     my @homeservers;
1.841     albertel 7871: 
                   7872:     my %servers = &get_servers($domain,'library');
                   7873:     foreach my $tryserver (keys(%servers)) {
                   7874: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7875: 	    push(@homeservers,$tryserver);
                   7876: 	}
1.792     raeburn  7877:     }
1.841     albertel 7878: 
1.792     raeburn  7879:     my $response;
1.841     albertel 7880:     foreach my $server (@homeservers) {
1.792     raeburn  7881:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 7882:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   7883: 	
                   7884: 	foreach my $pair (split(/\&/,$response)) {
                   7885: 	    my ($name,$value)=split(/\=/,$pair);
                   7886: 	    if ($name eq 'code_order') {
                   7887: 		@{$code_order} = split(/\&/,&unescape($value));
                   7888: 	    } else {
                   7889: 		$returnhash->{&unescape($name)}=&unescape($value);
                   7890: 	    }
                   7891: 	}
                   7892: 	return 'ok';
1.792     raeburn  7893:     }
1.841     albertel 7894: 
                   7895:     return $response;
1.1003    raeburn  7896: }
                   7897: 
                   7898: sub auto_possible_instcodes {
1.1007    raeburn  7899:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   7900:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   7901:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   7902:         return;
                   7903:     }
1.1003    raeburn  7904:     my (@homeservers,$uhome);
                   7905:     if (defined(&domain($domain,'primary'))) {
                   7906:         $uhome=&domain($domain,'primary');
                   7907:         push(@homeservers,&domain($domain,'primary'));
                   7908:     } else {
                   7909:         my %servers = &get_servers($domain,'library');
                   7910:         foreach my $tryserver (keys(%servers)) {
                   7911:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7912:                 push(@homeservers,$tryserver);
                   7913:             }
                   7914:         }
                   7915:     }
                   7916:     my $response;
                   7917:     foreach my $server (@homeservers) {
                   7918:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   7919:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  7920:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   7921:             split(':',$response);
                   7922:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   7923:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  7924:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  7925:             my ($name,$value)=split('=',$item);
                   7926:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7927:         }
                   7928:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  7929:             my ($name,$value)=split('=',$item);
                   7930:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7931:         }
                   7932:         return 'ok';
                   7933:     }
                   7934:     return $response;
                   7935: }
1.792     raeburn  7936: 
1.1010    raeburn  7937: sub auto_courserequest_checks {
                   7938:     my ($dom) = @_;
1.1020    raeburn  7939:     my ($homeserver,%validations);
                   7940:     if ($dom =~ /^$match_domain$/) {
                   7941:         $homeserver = &domain($dom,'primary');
                   7942:     }
                   7943:     unless ($homeserver eq 'no_host') {
                   7944:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   7945:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   7946:             my @items = split(/&/,$response);
                   7947:             foreach my $item (@items) {
                   7948:                 my ($key,$value) = split('=',$item);
                   7949:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   7950:             }
                   7951:         }
                   7952:     }
1.1010    raeburn  7953:     return %validations; 
                   7954: }
                   7955: 
1.1020    raeburn  7956: sub auto_courserequest_validation {
1.1172.2.43  raeburn  7957:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  7958:     my ($homeserver,$response);
                   7959:     if ($dom =~ /^$match_domain$/) {
                   7960:         $homeserver = &domain($dom,'primary');
                   7961:     }
1.1172.2.43  raeburn  7962:     unless ($homeserver eq 'no_host') {
                   7963:         my $customdata;
                   7964:         if (ref($custominfo) eq 'HASH') {
                   7965:             $customdata = &freeze_escape($custominfo);
                   7966:         }
1.1020    raeburn  7967:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  7968:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43  raeburn  7969:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   7970:                                     $customdata,$homeserver));
1.1020    raeburn  7971:     }
                   7972:     return $response;
                   7973: }
                   7974: 
1.777     albertel 7975: sub auto_validate_class_sec {
1.918     raeburn  7976:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  7977:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  7978:     my $ownerlist;
                   7979:     if (ref($owners) eq 'ARRAY') {
                   7980:         $ownerlist = join(',',@{$owners});
                   7981:     } else {
                   7982:         $ownerlist = $owners;
                   7983:     }
1.773     raeburn  7984:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  7985:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  7986:     return $response;
                   7987: }
                   7988: 
1.1172.2.38  raeburn  7989: sub auto_crsreq_update {
                   7990:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45  raeburn  7991:         $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38  raeburn  7992:     my ($homeserver,%crsreqresponse);
                   7993:     if ($cdom =~ /^$match_domain$/) {
                   7994:         $homeserver = &domain($cdom,'primary');
                   7995:     }
                   7996:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   7997:         my $info;
                   7998:         if (ref($inbound) eq 'HASH') {
                   7999:             $info = &freeze_escape($inbound);
                   8000:         }
                   8001:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   8002:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   8003:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45  raeburn  8004:                             &escape($title).':'.&escape($code).':'.
                   8005:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38  raeburn  8006:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8007:             my @items = split(/&/,$response);
                   8008:             foreach my $item (@items) {
                   8009:                 my ($key,$value) = split('=',$item);
                   8010:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   8011:             }
                   8012:         }
                   8013:     }
                   8014:     return \%crsreqresponse;
                   8015: }
                   8016: 
1.679     raeburn  8017: # ------------------------------------------------------- Course Group routines
                   8018: 
                   8019: sub get_coursegroups {
1.809     raeburn  8020:     my ($cdom,$cnum,$group,$namespace) = @_;
                   8021:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  8022: }
                   8023: 
1.679     raeburn  8024: sub modify_coursegroup {
                   8025:     my ($cdom,$cnum,$groupsettings) = @_;
                   8026:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   8027: }
                   8028: 
1.809     raeburn  8029: sub toggle_coursegroup_status {
                   8030:     my ($cdom,$cnum,$group,$action) = @_;
                   8031:     my ($from_namespace,$to_namespace);
                   8032:     if ($action eq 'delete') {
                   8033:         $from_namespace = 'coursegroups';
                   8034:         $to_namespace = 'deleted_groups';
                   8035:     } else {
                   8036:         $from_namespace = 'deleted_groups';
                   8037:         $to_namespace = 'coursegroups';
                   8038:     }
                   8039:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  8040:     if (my $tmp = &error(%curr_group)) {
                   8041:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   8042:         return ('read error',$tmp);
                   8043:     } else {
                   8044:         my %savedsettings = %curr_group; 
1.809     raeburn  8045:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  8046:         my $deloutcome;
                   8047:         if ($result eq 'ok') {
1.809     raeburn  8048:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  8049:         } else {
                   8050:             return ('write error',$result);
                   8051:         }
                   8052:         if ($deloutcome eq 'ok') {
                   8053:             return 'ok';
                   8054:         } else {
                   8055:             return ('delete error',$deloutcome);
                   8056:         }
                   8057:     }
                   8058: }
                   8059: 
1.679     raeburn  8060: sub modify_group_roles {
1.957     raeburn  8061:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  8062:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   8063:     my $role = 'gr/'.&escape($userprivs);
                   8064:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  8065:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  8066:     if ($result eq 'ok') {
                   8067:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   8068:     }
1.679     raeburn  8069:     return $result;
                   8070: }
                   8071: 
                   8072: sub modify_coursegroup_membership {
                   8073:     my ($cdom,$cnum,$membership) = @_;
                   8074:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   8075:     return $result;
                   8076: }
                   8077: 
1.682     raeburn  8078: sub get_active_groups {
                   8079:     my ($udom,$uname,$cdom,$cnum) = @_;
                   8080:     my $now = time;
                   8081:     my %groups = ();
                   8082:     foreach my $key (keys(%env)) {
1.811     albertel 8083:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  8084:             my ($start,$end) = split(/\./,$env{$key});
                   8085:             if (($end!=0) && ($end<$now)) { next; }
                   8086:             if (($start!=0) && ($start>$now)) { next; }
                   8087:             if ($1 eq $cdom && $2 eq $cnum) {
                   8088:                 $groups{$3} = $env{$key} ;
                   8089:             }
                   8090:         }
                   8091:     }
                   8092:     return %groups;
                   8093: }
                   8094: 
1.683     raeburn  8095: sub get_group_membership {
                   8096:     my ($cdom,$cnum,$group) = @_;
                   8097:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   8098: }
                   8099: 
                   8100: sub get_users_groups {
                   8101:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  8102:     my @usersgroups;
1.683     raeburn  8103:     my $cachetime=1800;
                   8104: 
                   8105:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  8106:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   8107:     if (defined($cached)) {
1.734     albertel 8108:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  8109:     } else {  
                   8110:         $grouplist = '';
1.816     raeburn  8111:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  8112:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  8113:         my $access_end = $env{'course.'.$courseid.
                   8114:                               '.default_enrollment_end_date'};
                   8115:         my $now = time;
                   8116:         foreach my $key (keys(%roleshash)) {
                   8117:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   8118:                 my $group = $1;
                   8119:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   8120:                     my $start = $2;
                   8121:                     my $end = $1;
                   8122:                     if ($start == -1) { next; } # deleted from group
                   8123:                     if (($start!=0) && ($start>$now)) { next; }
                   8124:                     if (($end!=0) && ($end<$now)) {
                   8125:                         if ($access_end && $access_end < $now) {
                   8126:                             if ($access_end - $end < 86400) {
                   8127:                                 push(@usersgroups,$group);
1.733     raeburn  8128:                             }
                   8129:                         }
1.817     raeburn  8130:                         next;
1.733     raeburn  8131:                     }
1.817     raeburn  8132:                     push(@usersgroups,$group);
1.683     raeburn  8133:                 }
                   8134:             }
                   8135:         }
1.817     raeburn  8136:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   8137:         $grouplist = join(':',@usersgroups);
                   8138:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  8139:     }
1.733     raeburn  8140:     return @usersgroups;
1.683     raeburn  8141: }
                   8142: 
                   8143: sub devalidate_getgroups_cache {
                   8144:     my ($udom,$uname,$cdom,$cnum)=@_;
                   8145:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 8146: 
1.683     raeburn  8147:     my $hashid="$udom:$uname:$courseid";
                   8148:     &devalidate_cache_new('getgroups',$hashid);
                   8149: }
                   8150: 
1.12      www      8151: # ------------------------------------------------------------------ Plain Text
                   8152: 
                   8153: sub plaintext {
1.988     raeburn  8154:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  8155:     if ($short =~ m{^cr/}) {
1.758     albertel 8156: 	return (split('/',$short))[-1];
                   8157:     }
1.742     raeburn  8158:     if (!defined($cid)) {
                   8159:         $cid = $env{'request.course.id'};
                   8160:     }
                   8161:     my %rolenames = (
1.1008    raeburn  8162:                       Course    => 'std',
                   8163:                       Community => 'alt1',
1.742     raeburn  8164:                     );
1.1037    raeburn  8165:     if ($cid ne '') {
                   8166:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   8167:             unless ($forcedefault) {
                   8168:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   8169:                 &Apache::lonlocal::mt_escape(\$roletext);
                   8170:                 return &Apache::lonlocal::mt($roletext);
                   8171:             }
                   8172:         }
                   8173:     }
                   8174:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   8175:         (defined($rolenames{$type})) && 
                   8176:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  8177:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  8178:     } elsif ($cid ne '') {
                   8179:         my $crstype = $env{'course.'.$cid.'.type'};
                   8180:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   8181:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   8182:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   8183:         }
1.742     raeburn  8184:     }
1.1037    raeburn  8185:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      8186: }
                   8187: 
                   8188: # ----------------------------------------------------------------- Assign Role
                   8189: 
                   8190: sub assignrole {
1.957     raeburn  8191:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   8192:         $context)=@_;
1.21      www      8193:     my $mrole;
                   8194:     if ($role =~ /^cr\//) {
1.393     www      8195:         my $cwosec=$url;
1.811     albertel 8196:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      8197: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  8198:            my $refused = 1;
                   8199:            if ($context eq 'requestcourses') {
                   8200:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   8201:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   8202:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   8203:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8204:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8205:                            if ($crsenv{'internal.courseowner'} eq
                   8206:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   8207:                                $refused = '';
                   8208:                            }
                   8209:                        }
                   8210:                    }
                   8211:                }
                   8212:            }
                   8213:            if ($refused) {
                   8214:                &logthis('Refused custom assignrole: '.
                   8215:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   8216:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   8217:                return 'refused';
                   8218:            }
1.104     www      8219:         }
1.21      www      8220:         $mrole='cr';
1.678     raeburn  8221:     } elsif ($role =~ /^gr\//) {
                   8222:         my $cwogrp=$url;
1.811     albertel 8223:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  8224:         unless (&allowed('mdg',$cwogrp)) {
                   8225:             &logthis('Refused group assignrole: '.
                   8226:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   8227:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   8228:             return 'refused';
                   8229:         }
                   8230:         $mrole='gr';
1.21      www      8231:     } else {
1.82      www      8232:         my $cwosec=$url;
1.811     albertel 8233:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  8234:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   8235:             my $refused;
                   8236:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   8237:                 if (!(&allowed('c'.$role,$url))) {
                   8238:                     $refused = 1;
                   8239:                 }
                   8240:             } else {
                   8241:                 $refused = 1;
                   8242:             }
1.947     raeburn  8243:             if ($refused) {
1.1045    raeburn  8244:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8245:                 if (!$selfenroll && $context eq 'course') {
                   8246:                     my %crsenv;
                   8247:                     if ($role eq 'cc' || $role eq 'co') {
                   8248:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8249:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   8250:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   8251:                                 if ($crsenv{'internal.courseowner'} eq 
                   8252:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8253:                                     $refused = '';
                   8254:                                 }
                   8255:                             }
                   8256:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   8257:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   8258:                                 if ($crsenv{'internal.courseowner'} eq 
                   8259:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8260:                                     $refused = '';
                   8261:                                 }
                   8262:                             }
                   8263:                         }
                   8264:                     }
                   8265:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  8266:                     $refused = '';
1.1017    raeburn  8267:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  8268:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  8269:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  8270:                         my $wrongcc;
                   8271:                         if ($cnum =~ /^$match_community$/) {
                   8272:                             $wrongcc = 1 if ($role eq 'cc');
                   8273:                         } else {
                   8274:                             $wrongcc = 1 if ($role eq 'co');
                   8275:                         }
                   8276:                         unless ($wrongcc) {
                   8277:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8278:                             if ($crsenv{'internal.courseowner'} eq 
                   8279:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   8280:                                 $refused = '';
                   8281:                             }
1.1017    raeburn  8282:                         }
                   8283:                     }
1.1172.2.9  raeburn  8284:                 } elsif ($context eq 'requestauthor') {
                   8285:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   8286:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   8287:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   8288:                             $refused = '';
                   8289:                         } else {
                   8290:                             my %domdefaults = &get_domain_defaults($udom);
                   8291:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   8292:                                 my $checkbystatus;
                   8293:                                 if ($env{'user.adv'}) {
                   8294:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   8295:                                     if ($disposition eq 'automatic') {
                   8296:                                         $refused = '';
                   8297:                                     } elsif ($disposition eq '') {
                   8298:                                         $checkbystatus = 1;
                   8299:                                     }
                   8300:                                 } else {
                   8301:                                     $checkbystatus = 1;
                   8302:                                 }
                   8303:                                 if ($checkbystatus) {
                   8304:                                     if ($env{'environment.inststatus'}) {
                   8305:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   8306:                                         foreach my $type (@inststatuses) {
                   8307:                                             if (($type ne '') &&
                   8308:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   8309:                                                 $refused = '';
                   8310:                                             }
                   8311:                                         }
                   8312:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   8313:                                         $refused = '';
                   8314:                                     }
                   8315:                                 }
                   8316:                             }
                   8317:                         }
                   8318:                     }
1.1017    raeburn  8319:                 }
                   8320:                 if ($refused) {
1.947     raeburn  8321:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   8322:                              ' '.$role.' '.$end.' '.$start.' by '.
                   8323: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   8324:                     return 'refused';
                   8325:                 }
1.932     raeburn  8326:             }
1.1131    raeburn  8327:         } elsif ($role eq 'au') {
                   8328:             if ($url ne '/'.$udom.'/') {
                   8329:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   8330:                          ' to assign author role for '.$uname.':'.$udom.
                   8331:                          ' in domain: '.$url.' refused (wrong domain).');
                   8332:                 return 'refused';
                   8333:             }
1.104     www      8334:         }
1.21      www      8335:         $mrole=$role;
                   8336:     }
1.620     albertel 8337:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      8338:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      8339:     if ($end) { $command.='_'.$end; }
1.21      www      8340:     if ($start) {
                   8341: 	if ($end) { 
1.81      www      8342:            $command.='_'.$start; 
1.21      www      8343:         } else {
1.81      www      8344:            $command.='_0_'.$start;
1.21      www      8345:         }
                   8346:     }
1.739     raeburn  8347:     my $origstart = $start;
                   8348:     my $origend = $end;
1.957     raeburn  8349:     my $delflag;
1.357     www      8350: # actually delete
                   8351:     if ($deleteflag) {
1.373     www      8352: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      8353: # modify command to delete the role
1.620     albertel 8354:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      8355:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 8356: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      8357: # set start and finish to negative values for userrolelog
                   8358:            $start=-1;
                   8359:            $end=-1;
1.957     raeburn  8360:            $delflag = 1;
1.357     www      8361:         }
                   8362:     }
                   8363: # send command
1.349     www      8364:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      8365: # log new user role if status is ok
1.349     www      8366:     if ($answer eq 'ok') {
1.663     raeburn  8367: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  8368:         if (($role eq 'cc') || ($role eq 'in') ||
                   8369:             ($role eq 'ep') || ($role eq 'ad') ||
                   8370:             ($role eq 'ta') || ($role eq 'st') ||
                   8371:             ($role=~/^cr/) || ($role eq 'gr') ||
                   8372:             ($role eq 'co')) {
1.1172.2.13  raeburn  8373: # for course roles, perform group memberships changes triggered by role change.
                   8374:             unless ($role =~ /^gr/) {
                   8375:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   8376:                                                  $origstart,$selfenroll,$context);
                   8377:             }
1.1172.2.9  raeburn  8378:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8379:                            $selfenroll,$context);
                   8380:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
                   8381:                  ($role eq 'au') || ($role eq 'dc')) {
                   8382:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8383:                            $context);
                   8384:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   8385:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8386:                              $context);
                   8387:         }
1.1053    raeburn  8388:         if ($role eq 'cc') {
                   8389:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   8390:         }
1.349     www      8391:     }
                   8392:     return $answer;
1.169     harris41 8393: }
                   8394: 
1.1053    raeburn  8395: sub autoupdate_coowners {
                   8396:     my ($url,$end,$start,$uname,$udom) = @_;
                   8397:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   8398:     if (($cdom ne '') && ($cnum ne '')) {
                   8399:         my $now = time;
                   8400:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   8401:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   8402:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   8403:             my $instcode = $coursehash{'internal.coursecode'};
                   8404:             if ($instcode ne '') {
1.1056    raeburn  8405:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   8406:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  8407:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  8408:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   8409:                         if ($result eq 'valid') {
                   8410:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  8411:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8412:                                     push(@newcoowners,$coowner);
                   8413:                                 }
                   8414:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   8415:                                     push(@newcoowners,$uname.':'.$udom);
                   8416:                                 }
                   8417:                                 @newcoowners = sort(@newcoowners);
                   8418:                             } else {
                   8419:                                 push(@newcoowners,$uname.':'.$udom);
                   8420:                             }
                   8421:                         } else {
                   8422:                             if ($coursehash{'internal.co-owners'}) {
                   8423:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8424:                                     unless ($coowner eq $uname.':'.$udom) {
                   8425:                                         push(@newcoowners,$coowner);
                   8426:                                     }
                   8427:                                 }
                   8428:                                 unless (@newcoowners > 0) {
                   8429:                                     $delcoowners = 1;
                   8430:                                     $coowners = '';
                   8431:                                 }
                   8432:                             }
                   8433:                         }
                   8434:                         if (@newcoowners || $delcoowners) {
                   8435:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   8436:                                             $delcoowners,@newcoowners);
                   8437:                         }
                   8438:                     }
                   8439:                 }
                   8440:             }
                   8441:         }
                   8442:     }
                   8443: }
                   8444: 
                   8445: sub store_coowners {
                   8446:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   8447:     my $cid = $cdom.'_'.$cnum;
                   8448:     my ($coowners,$delresult,$putresult);
                   8449:     if (@newcoowners) {
                   8450:         $coowners = join(',',@newcoowners);
                   8451:         my %coownershash = (
                   8452:                             'internal.co-owners' => $coowners,
                   8453:                            );
                   8454:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   8455:         if ($putresult eq 'ok') {
                   8456:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   8457:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   8458:             }
                   8459:         }
                   8460:     }
                   8461:     if ($delcoowners) {
                   8462:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   8463:         if ($delresult eq 'ok') {
                   8464:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   8465:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   8466:             }
                   8467:         }
                   8468:     }
                   8469:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   8470:         my %crsinfo =
                   8471:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   8472:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   8473:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   8474:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   8475:         }
                   8476:     }
                   8477: }
                   8478: 
1.169     harris41 8479: # -------------------------------------------------- Modify user authentication
1.197     www      8480: # Overrides without validation
                   8481: 
1.169     harris41 8482: sub modifyuserauth {
                   8483:     my ($udom,$uname,$umode,$upass)=@_;
                   8484:     my $uhome=&homeserver($uname,$udom);
1.197     www      8485:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   8486:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 8487:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8488:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 8489:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   8490: 		     &escape($upass),$uhome);
1.620     albertel 8491:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      8492:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   8493:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   8494:     &log($udom,,$uname,$uhome,
1.620     albertel 8495:         'Authentication changed by '.$env{'user.domain'}.', '.
                   8496:                                      $env{'user.name'}.', '.$umode.
1.197     www      8497:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 8498:     unless ($reply eq 'ok') {
1.197     www      8499:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 8500: 	return 'error: '.$reply;
                   8501:     }   
1.170     harris41 8502:     return 'ok';
1.80      www      8503: }
                   8504: 
1.81      www      8505: # --------------------------------------------------------------- Modify a user
1.80      www      8506: 
1.81      www      8507: sub modifyuser {
1.206     matthew  8508:     my ($udom,    $uname, $uid,
                   8509:         $umode,   $upass, $first,
                   8510:         $middle,  $last,  $gene,
1.1058    raeburn  8511:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 8512:     $udom= &LONCAPA::clean_domain($udom);
                   8513:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  8514:     my $showcandelete = 'none';
                   8515:     if (ref($candelete) eq 'ARRAY') {
                   8516:         if (@{$candelete} > 0) {
                   8517:             $showcandelete = join(', ',@{$candelete});
                   8518:         }
                   8519:     }
1.81      www      8520:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      8521:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  8522: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  8523:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   8524:                                      ' desiredhome not specified'). 
1.620     albertel 8525:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8526:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 8527:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  8528:     my $newuser;
                   8529:     if ($uhome eq 'no_host') {
                   8530:         $newuser = 1;
                   8531:     }
1.80      www      8532: # ----------------------------------------------------------------- Create User
1.406     albertel 8533:     if (($uhome eq 'no_host') && 
                   8534: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      8535:         my $unhome='';
1.844     albertel 8536:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  8537:             $unhome = $desiredhome;
1.620     albertel 8538: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   8539: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  8540:         } else { # load balancing routine for determining $unhome
1.81      www      8541:             my $loadm=10000000;
1.841     albertel 8542: 	    my %servers = &get_servers($udom,'library');
                   8543: 	    foreach my $tryserver (keys(%servers)) {
                   8544: 		my $answer=reply('load',$tryserver);
                   8545: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   8546: 		    $loadm=$answer;
                   8547: 		    $unhome=$tryserver;
                   8548: 		}
1.80      www      8549: 	    }
                   8550:         }
                   8551:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  8552: 	    return 'error: unable to find a home server for '.$uname.
                   8553:                    ' in domain '.$udom;
1.80      www      8554:         }
                   8555:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   8556:                          &escape($upass),$unhome);
                   8557: 	unless ($reply eq 'ok') {
                   8558:             return 'error: '.$reply;
                   8559:         }   
1.230     stredwic 8560:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      8561:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  8562: 	    return 'error: unable verify users home machine.';
1.80      www      8563:         }
1.209     matthew  8564:     }   # End of creation of new user
1.80      www      8565: # ---------------------------------------------------------------------- Add ID
                   8566:     if ($uid) {
                   8567:        $uid=~tr/A-Z/a-z/;
                   8568:        my %uidhash=&idrget($udom,$uname);
1.196     www      8569:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   8570:          && (!$forceid)) {
1.80      www      8571: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  8572: 	      return 'error: user id "'.$uid.'" does not match '.
                   8573:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      8574:           }
                   8575:        } else {
                   8576: 	  &idput($udom,($uname => $uid));
                   8577:        }
                   8578:     }
                   8579: # -------------------------------------------------------------- Add names, etc
1.313     matthew  8580:     my @tmp=&get('environment',
1.899     raeburn  8581: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  8582:                     'permanentemail','inststatus'],
1.134     albertel 8583: 		   $udom,$uname);
1.1075    raeburn  8584:     my (%names,%oldnames);
1.313     matthew  8585:     if ($tmp[0] =~ m/^error:.*/) { 
                   8586:         %names=(); 
                   8587:     } else {
                   8588:         %names = @tmp;
1.1075    raeburn  8589:         %oldnames = %names;
1.313     matthew  8590:     }
1.388     www      8591: #
1.1058    raeburn  8592: # If name, email and/or uid are blank (e.g., because an uploaded file
                   8593: # of users did not contain them), do not overwrite existing values
                   8594: # unless field is in $candelete array ref.  
                   8595: #
                   8596: 
                   8597:     my @fields = ('firstname','middlename','lastname','generation',
                   8598:                   'permanentemail','id');
                   8599:     my %newvalues;
                   8600:     if (ref($candelete) eq 'ARRAY') {
                   8601:         foreach my $field (@fields) {
                   8602:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   8603:                 if ($field eq 'firstname') {
                   8604:                     $names{$field} = $first;
                   8605:                 } elsif ($field eq 'middlename') {
                   8606:                     $names{$field} = $middle;
                   8607:                 } elsif ($field eq 'lastname') {
                   8608:                     $names{$field} = $last;
                   8609:                 } elsif ($field eq 'generation') { 
                   8610:                     $names{$field} = $gene;
                   8611:                 } elsif ($field eq 'permanentemail') {
                   8612:                     $names{$field} = $email;
                   8613:                 } elsif ($field eq 'id') {
                   8614:                     $names{$field}  = $uid;
                   8615:                 }
                   8616:             }
                   8617:         }
                   8618:     }
1.388     www      8619:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  8620:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      8621:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  8622:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      8623:     if ($email) {
                   8624:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  8625:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      8626:     }
1.899     raeburn  8627:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  8628:     if (defined($inststatus)) {
                   8629:         $names{'inststatus'} = '';
                   8630:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   8631:         if (ref($usertypes) eq 'HASH') {
                   8632:             my @okstatuses; 
                   8633:             foreach my $item (split(/:/,$inststatus)) {
                   8634:                 if (defined($usertypes->{$item})) {
                   8635:                     push(@okstatuses,$item);  
                   8636:                 }
                   8637:             }
                   8638:             if (@okstatuses) {
                   8639:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   8640:             }
                   8641:         }
                   8642:     }
1.1075    raeburn  8643:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  8644:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  8645:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  8646:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   8647:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   8648:     } else {
                   8649:         $logmsg .= ' during self creation';
                   8650:     }
1.1075    raeburn  8651:     my $changed;
                   8652:     if ($newuser) {
                   8653:         $changed = 1;
                   8654:     } else {
                   8655:         foreach my $field (@fields) {
                   8656:             if ($names{$field} ne $oldnames{$field}) {
                   8657:                 $changed = 1;
                   8658:                 last;
                   8659:             }
                   8660:         }
                   8661:     }
                   8662:     unless ($changed) {
                   8663:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   8664:         &logthis($logmsg);
                   8665:         return 'ok';
                   8666:     }
                   8667:     my $reply = &put('environment', \%names, $udom,$uname);
                   8668:     if ($reply ne 'ok') { 
                   8669:         return 'error: '.$reply;
                   8670:     }
1.1087    raeburn  8671:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   8672:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   8673:     }
1.1075    raeburn  8674:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   8675:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   8676:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  8677:     &logthis($logmsg);
1.134     albertel 8678:     return 'ok';
1.80      www      8679: }
                   8680: 
1.81      www      8681: # -------------------------------------------------------------- Modify student
1.80      www      8682: 
1.81      www      8683: sub modifystudent {
                   8684:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  8685:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.19  raeburn  8686:         $selfenroll,$context,$inststatus,$credits)=@_;
1.455     albertel 8687:     if (!$cid) {
1.620     albertel 8688: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8689: 	    return 'not_in_class';
                   8690: 	}
1.80      www      8691:     }
                   8692: # --------------------------------------------------------------- Make the user
1.81      www      8693:     my $reply=&modifyuser
1.209     matthew  8694: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  8695:          $desiredhome,$email,$inststatus);
1.80      www      8696:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  8697:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  8698:     # student's environment
1.297     matthew  8699:     $uid = undef if (!$forceid);
1.455     albertel 8700:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  8701: 					$gene,$usec,$end,$start,$type,$locktype,
                   8702:                                         $cid,$selfenroll,$context,$credits);
1.297     matthew  8703:     return $reply;
                   8704: }
                   8705: 
                   8706: sub modify_student_enrollment {
1.1172.2.23  raeburn  8707:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
                   8708:         $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455     albertel 8709:     my ($cdom,$cnum,$chome);
                   8710:     if (!$cid) {
1.620     albertel 8711: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8712: 	    return 'not_in_class';
                   8713: 	}
1.620     albertel 8714: 	$cdom=$env{'course.'.$cid.'.domain'};
                   8715: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 8716:     } else {
                   8717: 	($cdom,$cnum)=split(/_/,$cid);
                   8718:     }
1.620     albertel 8719:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 8720:     if (!$chome) {
1.457     raeburn  8721: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  8722:     }
1.455     albertel 8723:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  8724:     # Make sure the user exists
1.81      www      8725:     my $uhome=&homeserver($uname,$udom);
                   8726:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8727: 	return 'error: no such user';
                   8728:     }
1.297     matthew  8729:     # Get student data if we were not given enough information
                   8730:     if (!defined($first)  || $first  eq '' || 
                   8731:         !defined($last)   || $last   eq '' || 
                   8732:         !defined($uid)    || $uid    eq '' || 
                   8733:         !defined($middle) || $middle eq '' || 
                   8734:         !defined($gene)   || $gene   eq '') {
1.294     matthew  8735:         # They did not supply us with enough data to enroll the student, so
                   8736:         # we need to pick up more information.
1.297     matthew  8737:         my %tmp = &get('environment',
1.294     matthew  8738:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  8739:                        ,$udom,$uname);
                   8740: 
1.800     albertel 8741:         #foreach my $key (keys(%tmp)) {
                   8742:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 8743:         #}
1.294     matthew  8744:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   8745:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   8746:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  8747:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  8748:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   8749:     }
1.556     albertel 8750:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  8751:     my $user = "$uname:$udom";
                   8752:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 8753:     my $reply=cput('classlist',
1.1148    raeburn  8754: 		   {$user => 
1.1172.2.19  raeburn  8755: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487     albertel 8756: 		   $cdom,$cnum);
1.1148    raeburn  8757:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   8758:         &devalidate_getsection_cache($udom,$uname,$cid);
                   8759:     } else { 
1.81      www      8760: 	return 'error: '.$reply;
                   8761:     }
1.297     matthew  8762:     # Add student role to user
1.83      www      8763:     my $uurl='/'.$cid;
1.81      www      8764:     $uurl=~s/\_/\//g;
                   8765:     if ($usec) {
                   8766: 	$uurl.='/'.$usec;
                   8767:     }
1.1148    raeburn  8768:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   8769:                              $selfenroll,$context);
                   8770:     if ($result ne 'ok') {
                   8771:         if ($old_entry{$user} ne '') {
                   8772:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   8773:         } else {
                   8774:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   8775:         }
                   8776:     }
                   8777:     return $result; 
1.21      www      8778: }
                   8779: 
1.556     albertel 8780: sub format_name {
                   8781:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   8782:     my $name;
                   8783:     if ($first ne 'lastname') {
                   8784: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   8785:     } else {
                   8786: 	if ($lastname=~/\S/) {
                   8787: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   8788: 	    $name=~s/\s+,/,/;
                   8789: 	} else {
                   8790: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   8791: 	}
                   8792:     }
                   8793:     $name=~s/^\s+//;
                   8794:     $name=~s/\s+$//;
                   8795:     $name=~s/\s+/ /g;
                   8796:     return $name;
                   8797: }
                   8798: 
1.84      www      8799: # ------------------------------------------------- Write to course preferences
                   8800: 
                   8801: sub writecoursepref {
                   8802:     my ($courseid,%prefs)=@_;
                   8803:     $courseid=~s/^\///;
                   8804:     $courseid=~s/\_/\//g;
                   8805:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   8806:     my $chome=homeserver($cnum,$cdomain);
                   8807:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   8808: 	return 'error: no such course';
                   8809:     }
                   8810:     my $cstring='';
1.800     albertel 8811:     foreach my $pref (keys(%prefs)) {
                   8812: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 8813:     }
1.84      www      8814:     $cstring=~s/\&$//;
                   8815:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   8816: }
                   8817: 
                   8818: # ---------------------------------------------------------- Make/modify course
                   8819: 
                   8820: sub createcourse {
1.741     raeburn  8821:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  8822:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      8823:     $url=&declutter($url);
                   8824:     my $cid='';
1.1028    raeburn  8825:     if ($context eq 'requestcourses') {
                   8826:         my $can_create = 0;
                   8827:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   8828:         if ($udom eq $ownerdom) {
                   8829:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   8830:                                   $context)) {
                   8831:                 $can_create = 1;
                   8832:             }
                   8833:         } else {
                   8834:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   8835:                                            $category);
                   8836:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   8837:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   8838:                 if (@curr > 0) {
                   8839:                     my @options = qw(approval validate autolimit);
                   8840:                     my $optregex = join('|',@options);
                   8841:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   8842:                         $can_create = 1;
                   8843:                     }
                   8844:                 }
                   8845:             }
                   8846:         }
                   8847:         if ($can_create) {
                   8848:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   8849:                 unless (&allowed('ccc',$udom)) {
                   8850:                     return 'refused'; 
                   8851:                 }
1.1017    raeburn  8852:             }
                   8853:         } else {
                   8854:             return 'refused';
                   8855:         }
1.1028    raeburn  8856:     } elsif (!&allowed('ccc',$udom)) {
                   8857:         return 'refused';
1.84      www      8858:     }
1.1011    raeburn  8859: # --------------------------------------------------------------- Get Unique ID
                   8860:     my $uname;
                   8861:     if ($cnum =~ /^$match_courseid$/) {
                   8862:         my $chome=&homeserver($cnum,$udom,'true');
                   8863:         if (($chome eq '') || ($chome eq 'no_host')) {
                   8864:             $uname = $cnum;
                   8865:         } else {
1.1038    raeburn  8866:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8867:         }
                   8868:     } else {
1.1038    raeburn  8869:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8870:     }
                   8871:     return $uname if ($uname =~ /^error/);
                   8872: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  8873:     if (!defined($course_server)) {
                   8874:         if (defined(&domain($udom,'primary'))) {
                   8875:             $course_server = &domain($udom,'primary');
                   8876:         } else {
                   8877:             $course_server = $env{'user.home'}; 
                   8878:         }
                   8879:     }
                   8880:     my %host_servers =
                   8881:         &Apache::lonnet::get_servers($udom,'library');
                   8882:     unless ($host_servers{$course_server}) {
                   8883:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  8884:     }
1.84      www      8885: # ------------------------------------------------------------- Make the course
                   8886:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  8887:                       $course_server);
1.84      www      8888:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  8889:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      8890:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8891: 	return 'error: no such course';
                   8892:     }
1.271     www      8893: # ----------------------------------------------------------------- Course made
1.516     raeburn  8894: # log existence
1.1029    raeburn  8895:     my $now = time;
1.918     raeburn  8896:     my $newcourse = {
                   8897:                     $udom.'_'.$uname => {
1.921     raeburn  8898:                                      description => $description,
                   8899:                                      inst_code   => $inst_code,
                   8900:                                      owner       => $course_owner,
                   8901:                                      type        => $crstype,
1.1029    raeburn  8902:                                      creator     => $env{'user.name'}.':'.
                   8903:                                                     $env{'user.domain'},
                   8904:                                      created     => $now,
                   8905:                                      context     => $context,
1.918     raeburn  8906:                                                 },
                   8907:                     };
1.921     raeburn  8908:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      8909: # set toplevel url
1.271     www      8910:     my $topurl=$url;
                   8911:     unless ($nonstandard) {
                   8912: # ------------------------------------------ For standard courses, make top url
                   8913:         my $mapurl=&clutter($url);
1.278     www      8914:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 8915:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      8916: <map>
                   8917: <resource id="1" type="start"></resource>
                   8918: <resource id="2" src="$mapurl"></resource>
                   8919: <resource id="3" type="finish"></resource>
                   8920: <link index="1" from="1" to="2"></link>
                   8921: <link index="2" from="2" to="3"></link>
                   8922: </map>
                   8923: ENDINITMAP
                   8924:         $topurl=&declutter(
1.638     albertel 8925:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      8926:                           );
                   8927:     }
                   8928: # ----------------------------------------------------------- Write preferences
1.84      www      8929:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  8930:                      ('description'              => $description,
                   8931:                       'url'                      => $topurl,
                   8932:                       'internal.creator'         => $env{'user.name'}.':'.
                   8933:                                                     $env{'user.domain'},
                   8934:                       'internal.created'         => $now,
                   8935:                       'internal.creationcontext' => $context)
                   8936:                     );
1.84      www      8937:     return '/'.$udom.'/'.$uname;
                   8938: }
                   8939: 
1.1011    raeburn  8940: # ------------------------------------------------------------------- Create ID
                   8941: sub generate_coursenum {
1.1038    raeburn  8942:     my ($udom,$crstype) = @_;
1.1011    raeburn  8943:     my $domdesc = &domain($udom);
                   8944:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  8945:     my $first;
                   8946:     if ($crstype eq 'Community') {
                   8947:         $first = '0';
                   8948:     } else {
                   8949:         $first = int(1+rand(9)); 
                   8950:     } 
                   8951:     my $uname=$first.
1.1011    raeburn  8952:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8953:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8954:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8955: # ----------------------------------------------- Make sure that does not exist
                   8956:     my $uhome=&homeserver($uname,$udom,'true');
                   8957:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  8958:         if ($crstype eq 'Community') {
                   8959:             $first = '0';
                   8960:         } else {
                   8961:             $first = int(1+rand(9));
                   8962:         }
                   8963:         $uname=$first.
1.1011    raeburn  8964:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8965:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8966:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8967:         $uhome=&homeserver($uname,$udom,'true');
                   8968:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   8969:             return 'error: unable to generate unique course-ID';
                   8970:         }
                   8971:     }
                   8972:     return $uname;
                   8973: }
                   8974: 
1.813     albertel 8975: sub is_course {
1.1167    droeschl 8976:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   8977:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   8978: 
                   8979:     return unless $cdom and $cnum;
                   8980: 
                   8981:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   8982:         '.');
                   8983: 
1.1172.2.23  raeburn  8984:     return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167    droeschl 8985:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 8986: }
                   8987: 
1.1015    raeburn  8988: sub store_userdata {
                   8989:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  8990:     my $result;
1.1016    raeburn  8991:     if ($datakey ne '') {
1.1013    raeburn  8992:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  8993:             if ($udom eq '' || $uname eq '') {
                   8994:                 $udom = $env{'user.domain'};
                   8995:                 $uname = $env{'user.name'};
                   8996:             }
                   8997:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  8998:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   8999:                 $result = 'error: no_host';
                   9000:             } else {
                   9001:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   9002:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   9003: 
                   9004:                 my $namevalue='';
                   9005:                 foreach my $key (keys(%{$storehash})) {
                   9006:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   9007:                 }
                   9008:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  9009:                 unless ($namespace eq 'courserequests') {
                   9010:                     $datakey = &escape($datakey);
                   9011:                 }
1.1105    raeburn  9012:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   9013:                                   $namevalue,$uhome);
1.1013    raeburn  9014:             }
                   9015:         } else {
                   9016:             $result = 'error: data to store was not a hash reference'; 
                   9017:         }
                   9018:     } else {
                   9019:         $result= 'error: invalid requestkey'; 
                   9020:     }
                   9021:     return $result;
                   9022: }
                   9023: 
1.21      www      9024: # ---------------------------------------------------------- Assign Custom Role
                   9025: 
                   9026: sub assigncustomrole {
1.957     raeburn  9027:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9028:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  9029:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      9030: }
                   9031: 
                   9032: # ----------------------------------------------------------------- Revoke Role
                   9033: 
                   9034: sub revokerole {
1.957     raeburn  9035:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9036:     my $now=time;
1.965     raeburn  9037:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      9038: }
                   9039: 
                   9040: # ---------------------------------------------------------- Revoke Custom Role
                   9041: 
                   9042: sub revokecustomrole {
1.957     raeburn  9043:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9044:     my $now=time;
1.357     www      9045:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  9046:            $deleteflag,$selfenroll,$context);
1.17      www      9047: }
                   9048: 
1.533     banghart 9049: # ------------------------------------------------------------ Disk usage
1.535     albertel 9050: sub diskusage {
1.955     raeburn  9051:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   9052:     $directorypath =~ s/\/$//;
                   9053:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   9054:                        .&escape($getpropath).':'.&escape($uname).':'
                   9055:                        .&escape($udom),homeserver($uname,$udom));
                   9056:     if ($listing eq 'unknown_cmd') {
                   9057:         if ($getpropath) {
                   9058:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   9059:         }
                   9060:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   9061:     }
1.514     albertel 9062:     return $listing;
1.512     banghart 9063: }
                   9064: 
1.566     banghart 9065: sub is_locked {
1.1096    raeburn  9066:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 9067:     my @check;
                   9068:     my $is_locked;
1.1093    raeburn  9069:     push (@check,$file_name);
1.613     albertel 9070:     my %locked = &get('file_permissions',\@check,
1.620     albertel 9071: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 9072:     my ($tmp)=keys(%locked);
                   9073:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  9074:     
1.566     banghart 9075:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  9076:         $is_locked = 'false';
                   9077:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  9078:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  9079:                $is_locked = 'true';
1.1096    raeburn  9080:                if (ref($which) eq 'ARRAY') {
                   9081:                    push(@{$which},$entry);
                   9082:                } else {
                   9083:                    last;
                   9084:                }
1.745     raeburn  9085:            }
                   9086:        }
1.566     banghart 9087:     } else {
                   9088:         $is_locked = 'false';
                   9089:     }
1.1093    raeburn  9090:     return $is_locked;
1.566     banghart 9091: }
                   9092: 
1.759     albertel 9093: sub declutter_portfile {
                   9094:     my ($file) = @_;
1.833     albertel 9095:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 9096:     return $file;
                   9097: }
                   9098: 
1.559     banghart 9099: # ------------------------------------------------------------- Mark as Read Only
                   9100: 
                   9101: sub mark_as_readonly {
                   9102:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 9103:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9104:     my ($tmp)=keys(%current_permissions);
                   9105:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 9106:     foreach my $file (@{$files}) {
1.759     albertel 9107: 	$file = &declutter_portfile($file);
1.561     banghart 9108:         push(@{$current_permissions{$file}},$what);
1.559     banghart 9109:     }
1.613     albertel 9110:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9111:     return;
                   9112: }
                   9113: 
1.572     banghart 9114: # ------------------------------------------------------------Save Selected Files
                   9115: 
                   9116: sub save_selected_files {
                   9117:     my ($user, $path, @files) = @_;
                   9118:     my $filename = $user."savedfiles";
1.573     banghart 9119:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 9120:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 9121:     foreach my $file (@files) {
1.620     albertel 9122:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 9123:     }
                   9124:     foreach my $file (@other_files) {
1.574     banghart 9125:         print (OUT $file."\n");
1.572     banghart 9126:     }
1.574     banghart 9127:     close (OUT);
1.572     banghart 9128:     return 'ok';
                   9129: }
                   9130: 
1.574     banghart 9131: sub clear_selected_files {
                   9132:     my ($user) = @_;
                   9133:     my $filename = $user."savedfiles";
1.1117    foxr     9134:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 9135:     print (OUT undef);
                   9136:     close (OUT);
                   9137:     return ("ok");    
                   9138: }
                   9139: 
1.572     banghart 9140: sub files_in_path {
                   9141:     my ($user, $path) = @_;
                   9142:     my $filename = $user."savedfiles";
                   9143:     my %return_files;
1.1117    foxr     9144:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 9145:     while (my $line_in = <IN>) {
1.574     banghart 9146:         chomp ($line_in);
                   9147:         my @paths_and_file = split (m!/!, $line_in);
                   9148:         my $file_part = pop (@paths_and_file);
                   9149:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 9150:         $path_part.='/';
                   9151:         my $path_and_file = $path_part.$file_part;
                   9152:         if ($path_part eq $path) {
                   9153:             $return_files{$file_part}= 'selected';
                   9154:         }
                   9155:     }
1.574     banghart 9156:     close (IN);
                   9157:     return (\%return_files);
1.572     banghart 9158: }
                   9159: 
                   9160: # called in portfolio select mode, to show files selected NOT in current directory
                   9161: sub files_not_in_path {
                   9162:     my ($user, $path) = @_;
                   9163:     my $filename = $user."savedfiles";
                   9164:     my @return_files;
                   9165:     my $path_part;
1.1117    foxr     9166:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 9167:     while (my $line = <IN>) {
1.572     banghart 9168:         #ok, I know it's clunky, but I want it to work
1.800     albertel 9169:         my @paths_and_file = split(m|/|, $line);
                   9170:         my $file_part = pop(@paths_and_file);
                   9171:         chomp($file_part);
                   9172:         my $path_part = join('/', @paths_and_file);
1.572     banghart 9173:         $path_part .= '/';
                   9174:         my $path_and_file = $path_part.$file_part;
                   9175:         if ($path_part ne $path) {
1.800     albertel 9176:             push(@return_files, ($path_and_file));
1.572     banghart 9177:         }
                   9178:     }
1.800     albertel 9179:     close(OUT);
1.574     banghart 9180:     return (@return_files);
1.572     banghart 9181: }
                   9182: 
1.745     raeburn  9183: #----------------------------------------------Get portfolio file permissions
1.629     banghart 9184: 
1.745     raeburn  9185: sub get_portfile_permissions {
                   9186:     my ($domain,$user) = @_;
1.613     albertel 9187:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9188:     my ($tmp)=keys(%current_permissions);
                   9189:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9190:     return \%current_permissions;
                   9191: }
                   9192: 
                   9193: #---------------------------------------------Get portfolio file access controls
                   9194: 
1.749     raeburn  9195: sub get_access_controls {
1.745     raeburn  9196:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 9197:     my %access;
                   9198:     my $real_file = $file;
                   9199:     $file =~ s/\.meta$//;
1.745     raeburn  9200:     if (defined($file)) {
1.749     raeburn  9201:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   9202:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 9203:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  9204:             }
                   9205:         }
1.745     raeburn  9206:     } else {
1.749     raeburn  9207:         foreach my $key (keys(%{$current_permissions})) {
                   9208:             if ($key =~ /\0accesscontrol$/) {
                   9209:                 if (defined($group)) {
                   9210:                     if ($key !~ m-^\Q$group\E/-) {
                   9211:                         next;
                   9212:                     }
                   9213:                 }
                   9214:                 my ($fullpath) = split(/\0/,$key);
                   9215:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   9216:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   9217:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   9218:                     }
                   9219:                 }
                   9220:             }
                   9221:         }
                   9222:     }
                   9223:     return %access;
                   9224: }
                   9225: 
                   9226: sub modify_access_controls {
                   9227:     my ($file_name,$changes,$domain,$user)=@_;
                   9228:     my ($outcome,$deloutcome);
                   9229:     my %store_permissions;
                   9230:     my %new_values;
                   9231:     my %new_control;
                   9232:     my %translation;
                   9233:     my @deletions = ();
                   9234:     my $now = time;
                   9235:     if (exists($$changes{'activate'})) {
                   9236:         if (ref($$changes{'activate'}) eq 'HASH') {
                   9237:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   9238:             my $numnew = scalar(@newitems);
                   9239:             for (my $i=0; $i<$numnew; $i++) {
                   9240:                 my $newkey = $newitems[$i];
                   9241:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  9242:                 if ($newkey =~ /^\d+:/) { 
                   9243:                     $newkey =~ s/^(\d+)/$newid/;
                   9244:                     $translation{$1} = $newid;
                   9245:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   9246:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   9247:                     $translation{$1} = $newid;
                   9248:                 }
1.749     raeburn  9249:                 $new_values{$file_name."\0".$newkey} = 
                   9250:                                           $$changes{'activate'}{$newitems[$i]};
                   9251:                 $new_control{$newkey} = $now;
                   9252:             }
                   9253:         }
                   9254:     }
                   9255:     my %todelete;
                   9256:     my %changed_items;
                   9257:     foreach my $action ('delete','update') {
                   9258:         if (exists($$changes{$action})) {
                   9259:             if (ref($$changes{$action}) eq 'HASH') {
                   9260:                 foreach my $key (keys(%{$$changes{$action}})) {
                   9261:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   9262:                     if ($action eq 'delete') { 
                   9263:                         $todelete{$itemnum} = 1;
                   9264:                     } else {
                   9265:                         $changed_items{$itemnum} = $key;
                   9266:                     }
                   9267:                 }
1.745     raeburn  9268:             }
                   9269:         }
1.749     raeburn  9270:     }
                   9271:     # get lock on access controls for file.
                   9272:     my $lockhash = {
                   9273:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   9274:                                                        ':'.$env{'user.domain'},
                   9275:                    }; 
                   9276:     my $tries = 0;
                   9277:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9278:    
                   9279:     while (($gotlock ne 'ok') && $tries <3) {
                   9280:         $tries ++;
                   9281:         sleep 1;
                   9282:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9283:     }
                   9284:     if ($gotlock eq 'ok') {
                   9285:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   9286:         my ($tmp)=keys(%curr_permissions);
                   9287:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   9288:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   9289:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   9290:             if (ref($curr_controls) eq 'HASH') {
                   9291:                 foreach my $control_item (keys(%{$curr_controls})) {
                   9292:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   9293:                     if (defined($todelete{$itemnum})) {
                   9294:                         push(@deletions,$file_name."\0".$control_item);
                   9295:                     } else {
                   9296:                         if (defined($changed_items{$itemnum})) {
                   9297:                             $new_control{$changed_items{$itemnum}} = $now;
                   9298:                             push(@deletions,$file_name."\0".$control_item);
                   9299:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   9300:                         } else {
                   9301:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   9302:                         }
                   9303:                     }
1.745     raeburn  9304:                 }
                   9305:             }
                   9306:         }
1.970     raeburn  9307:         my ($group);
                   9308:         if (&is_course($domain,$user)) {
                   9309:             ($group,my $file) = split(/\//,$file_name,2);
                   9310:         }
1.749     raeburn  9311:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   9312:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   9313:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   9314:         #  remove lock
                   9315:         my @del_lock = ($file_name."\0".'locked_access_records');
                   9316:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  9317:         my $sqlresult =
1.970     raeburn  9318:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  9319:                                     $group);
1.749     raeburn  9320:     } else {
                   9321:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  9322:     }
1.749     raeburn  9323:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  9324: }
                   9325: 
1.827     raeburn  9326: sub make_public_indefinitely {
                   9327:     my ($requrl) = @_;
                   9328:     my $now = time;
                   9329:     my $action = 'activate';
                   9330:     my $aclnum = 0;
                   9331:     if (&is_portfolio_url($requrl)) {
                   9332:         my (undef,$udom,$unum,$file_name,$group) =
                   9333:             &parse_portfolio_url($requrl);
                   9334:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   9335:         my %access_controls = &get_access_controls($current_perms,
                   9336:                                                    $group,$file_name);
                   9337:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   9338:             my ($num,$scope,$end,$start) = 
                   9339:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   9340:             if ($scope eq 'public') {
                   9341:                 if ($start <= $now && $end == 0) {
                   9342:                     $action = 'none';
                   9343:                 } else {
                   9344:                     $action = 'update';
                   9345:                     $aclnum = $num;
                   9346:                 }
                   9347:                 last;
                   9348:             }
                   9349:         }
                   9350:         if ($action eq 'none') {
                   9351:              return 'ok';
                   9352:         } else {
                   9353:             my %changes;
                   9354:             my $newend = 0;
                   9355:             my $newstart = $now;
                   9356:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   9357:             $changes{$action}{$newkey} = {
                   9358:                 type => 'public',
                   9359:                 time => {
                   9360:                     start => $newstart,
                   9361:                     end   => $newend,
                   9362:                 },
                   9363:             };
                   9364:             my ($outcome,$deloutcome,$new_values,$translation) =
                   9365:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   9366:             return $outcome;
                   9367:         }
                   9368:     } else {
                   9369:         return 'invalid';
                   9370:     }
                   9371: }
                   9372: 
1.745     raeburn  9373: #------------------------------------------------------Get Marked as Read Only
                   9374: 
                   9375: sub get_marked_as_readonly {
                   9376:     my ($domain,$user,$what,$group) = @_;
                   9377:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 9378:     my @readonly_files;
1.629     banghart 9379:     my $cmp1=$what;
                   9380:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  9381:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9382:         if (defined($group)) {
                   9383:             if ($file_name !~ m-^\Q$group\E/-) {
                   9384:                 next;
                   9385:             }
                   9386:         }
1.561     banghart 9387:         if (ref($value) eq "ARRAY"){
                   9388:             foreach my $stored_what (@{$value}) {
1.629     banghart 9389:                 my $cmp2=$stored_what;
1.759     albertel 9390:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  9391:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  9392:                 }
1.629     banghart 9393:                 if ($cmp1 eq $cmp2) {
1.561     banghart 9394:                     push(@readonly_files, $file_name);
1.745     raeburn  9395:                     last;
1.563     banghart 9396:                 } elsif (!defined($what)) {
                   9397:                     push(@readonly_files, $file_name);
1.745     raeburn  9398:                     last;
1.561     banghart 9399:                 }
                   9400:             }
1.745     raeburn  9401:         }
1.561     banghart 9402:     }
                   9403:     return @readonly_files;
                   9404: }
1.577     banghart 9405: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 9406: 
1.577     banghart 9407: sub get_marked_as_readonly_hash {
1.745     raeburn  9408:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 9409:     my %readonly_files;
1.745     raeburn  9410:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9411:         if (defined($group)) {
                   9412:             if ($file_name !~ m-^\Q$group\E/-) {
                   9413:                 next;
                   9414:             }
                   9415:         }
1.577     banghart 9416:         if (ref($value) eq "ARRAY"){
                   9417:             foreach my $stored_what (@{$value}) {
1.745     raeburn  9418:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 9419:                     foreach my $lock_descriptor(@{$stored_what}) {
                   9420:                         if ($lock_descriptor eq 'graded') {
                   9421:                             $readonly_files{$file_name} = 'graded';
                   9422:                         } elsif ($lock_descriptor eq 'handback') {
                   9423:                             $readonly_files{$file_name} = 'handback';
                   9424:                         } else {
                   9425:                             if (!exists($readonly_files{$file_name})) {
                   9426:                                 $readonly_files{$file_name} = 'locked';
                   9427:                             }
                   9428:                         }
1.745     raeburn  9429:                     }
1.750     banghart 9430:                 } 
1.577     banghart 9431:             }
                   9432:         } 
                   9433:     }
                   9434:     return %readonly_files;
                   9435: }
1.559     banghart 9436: # ------------------------------------------------------------ Unmark as Read Only
                   9437: 
                   9438: sub unmark_as_readonly {
1.629     banghart 9439:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   9440:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  9441:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 9442:     $file_name = &declutter_portfile($file_name);
1.634     albertel 9443:     my $symb_crs = $what;
                   9444:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  9445:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 9446:     my ($tmp)=keys(%current_permissions);
                   9447:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9448:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 9449:     foreach my $file (@readonly_files) {
1.759     albertel 9450: 	my $clean_file = &declutter_portfile($file);
                   9451: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 9452: 	my $current_locks = $current_permissions{$file};
1.563     banghart 9453:         my @new_locks;
                   9454:         my @del_keys;
                   9455:         if (ref($current_locks) eq "ARRAY"){
                   9456:             foreach my $locker (@{$current_locks}) {
1.632     albertel 9457:                 my $compare=$locker;
1.749     raeburn  9458:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  9459:                     $compare=join('',@{$locker});
1.746     raeburn  9460:                     if ($compare ne $symb_crs) {
                   9461:                         push(@new_locks, $locker);
                   9462:                     }
1.563     banghart 9463:                 }
                   9464:             }
1.650     albertel 9465:             if (scalar(@new_locks) > 0) {
1.563     banghart 9466:                 $current_permissions{$file} = \@new_locks;
                   9467:             } else {
                   9468:                 push(@del_keys, $file);
1.613     albertel 9469:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 9470:                 delete($current_permissions{$file});
1.563     banghart 9471:             }
                   9472:         }
1.561     banghart 9473:     }
1.613     albertel 9474:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9475:     return;
                   9476: }
1.512     banghart 9477: 
1.17      www      9478: # ------------------------------------------------------------ Directory lister
                   9479: 
                   9480: sub dirlist {
1.955     raeburn  9481:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      9482:     $uri=~s/^\///;
                   9483:     $uri=~s/\/$//;
1.253     stredwic 9484:     my ($udom, $uname);
1.955     raeburn  9485:     if ($getuserdir) {
1.253     stredwic 9486:         $udom = $userdomain;
                   9487:         $uname = $username;
1.955     raeburn  9488:     } else {
                   9489:         (undef,$udom,$uname)=split(/\//,$uri);
                   9490:         if(defined($userdomain)) {
                   9491:             $udom = $userdomain;
                   9492:         }
                   9493:         if(defined($username)) {
                   9494:             $uname = $username;
                   9495:         }
1.253     stredwic 9496:     }
1.955     raeburn  9497:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 9498: 
1.955     raeburn  9499:     $dirRoot = $perlvar{'lonDocRoot'};
                   9500:     if (defined($getpropath)) {
                   9501:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 9502:         $dirRoot =~ s/\/$//;
1.955     raeburn  9503:     } elsif (defined($getuserdir)) {
                   9504:         my $subdir=$uname.'__';
                   9505:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   9506:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   9507:                    ."/$udom/$subdir/$uname";
                   9508:     } elsif (defined($alternateRoot)) {
                   9509:         $dirRoot = $alternateRoot;
1.751     banghart 9510:     }
1.253     stredwic 9511: 
                   9512:     if($udom) {
                   9513:         if($uname) {
1.1135    raeburn  9514:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  9515:             if ($uhome eq 'no_host') {
                   9516:                 return ([],'no_host');
                   9517:             }
1.955     raeburn  9518:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  9519:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  9520:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  9521:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9522:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  9523:             } else {
                   9524:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9525:             }
1.605     matthew  9526:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9527:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  9528:                 @listing_results = split(/:/,$listing);
                   9529:             } else {
                   9530:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9531:             }
1.1135    raeburn  9532:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  9533:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9534:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9535:                 return ([],$listing);
                   9536:             } else {
                   9537:                 return (\@listing_results);
1.1135    raeburn  9538:             }
1.955     raeburn  9539:         } elsif(!$alternateRoot) {
1.1136    raeburn  9540:             my (%allusers,%listerror);
1.841     albertel 9541: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  9542:  	    foreach my $tryserver (keys(%servers)) {
                   9543:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   9544:                                   &escape($udom),$tryserver);
                   9545:                 if ($listing eq 'unknown_cmd') {
                   9546: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9547: 				      $udom, $tryserver);
                   9548:                 } else {
                   9549:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9550:                 }
1.841     albertel 9551: 		if ($listing eq 'unknown_cmd') {
                   9552: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9553: 				      $udom, $tryserver);
                   9554: 		    @listing_results = split(/:/,$listing);
                   9555: 		} else {
                   9556: 		    @listing_results =
                   9557: 			map { &unescape($_); } split(/:/,$listing);
                   9558: 		}
1.1136    raeburn  9559:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   9560:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9561:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9562:                     $listerror{$tryserver} = $listing;
                   9563:                 } else {
1.841     albertel 9564: 		    foreach my $line (@listing_results) {
                   9565: 			my ($entry) = split(/&/,$line,2);
                   9566: 			$allusers{$entry} = 1;
                   9567: 		    }
                   9568: 		}
1.253     stredwic 9569:             }
1.1136    raeburn  9570:             my @alluserslist=();
1.800     albertel 9571:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  9572:                 push(@alluserslist,$user.'&user');
1.253     stredwic 9573:             }
1.1136    raeburn  9574:             return (\@alluserslist);
1.253     stredwic 9575:         } else {
1.1136    raeburn  9576:             return ([],'missing username');
1.253     stredwic 9577:         }
1.955     raeburn  9578:     } elsif(!defined($getpropath)) {
1.1136    raeburn  9579:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   9580:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   9581:         return (\@all_domains);
1.955     raeburn  9582:     } else {
1.1136    raeburn  9583:         return ([],'missing domain');
1.275     stredwic 9584:     }
                   9585: }
                   9586: 
                   9587: # --------------------------------------------- GetFileTimestamp
                   9588: # This function utilizes dirlist and returns the date stamp for
                   9589: # when it was last modified.  It will also return an error of -1
                   9590: # if an error occurs
                   9591: 
                   9592: sub GetFileTimestamp {
1.955     raeburn  9593:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 9594:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   9595:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  9596:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   9597:                                     undef,$getuserdir);
                   9598:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9599:         return -1;
                   9600:     }
                   9601:     if (ref($fileref) eq 'ARRAY') {
                   9602:         my @stats = split('&',$fileref->[0]);
1.375     matthew  9603:         # @stats contains first the filename, then the stat output
                   9604:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 9605:     } else {
                   9606:         return -1;
1.253     stredwic 9607:     }
1.26      www      9608: }
                   9609: 
1.712     albertel 9610: sub stat_file {
                   9611:     my ($uri) = @_;
1.787     albertel 9612:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 9613: 
1.955     raeburn  9614:     my ($udom,$uname,$file);
1.712     albertel 9615:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   9616: 	($udom,$uname,$file) =
1.811     albertel 9617: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 9618: 	$file = 'userfiles/'.$file;
                   9619:     }
                   9620:     if ($uri =~ m-^/res/-) {
                   9621: 	($udom,$uname) = 
1.807     albertel 9622: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 9623: 	$file = $uri;
                   9624:     }
                   9625: 
                   9626:     if (!$udom || !$uname || !$file) {
                   9627: 	# unable to handle the uri
                   9628: 	return ();
                   9629:     }
1.956     raeburn  9630:     my $getpropath;
                   9631:     if ($file =~ /^userfiles\//) {
                   9632:         $getpropath = 1;
                   9633:     }
1.1136    raeburn  9634:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   9635:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9636:         return ();
                   9637:     } else {
                   9638:         if (ref($listref) eq 'ARRAY') {
                   9639:             my @stats = split('&',$listref->[0]);
                   9640: 	    shift(@stats); #filename is first
                   9641: 	    return @stats;
                   9642:         }
1.712     albertel 9643:     }
                   9644:     return ();
                   9645: }
                   9646: 
1.26      www      9647: # -------------------------------------------------------- Value of a Condition
                   9648: 
1.713     albertel 9649: # gets the value of a specific preevaluated condition
                   9650: #    stored in the string  $env{user.state.<cid>}
                   9651: # or looks up a condition reference in the bighash and if if hasn't
                   9652: # already been evaluated recurses into docondval to get the value of
                   9653: # the condition, then memoizing it to 
                   9654: #   $env{user.state.<cid>.<condition>}
1.40      www      9655: sub directcondval {
                   9656:     my $number=shift;
1.620     albertel 9657:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 9658: 	&Apache::lonuserstate::evalstate();
                   9659:     }
1.713     albertel 9660:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   9661: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   9662:     } elsif ($number =~ /^_/) {
                   9663: 	my $sub_condition;
                   9664: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   9665: 		&GDBM_READER(),0640)) {
                   9666: 	    $sub_condition=$bighash{'conditions'.$number};
                   9667: 	    untie(%bighash);
                   9668: 	}
                   9669: 	my $value = &docondval($sub_condition);
1.949     raeburn  9670: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 9671: 	return $value;
                   9672:     }
1.620     albertel 9673:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   9674:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      9675:     } else {
                   9676:        return 2;
                   9677:     }
                   9678: }
                   9679: 
1.713     albertel 9680: # get the collection of conditions for this resource
1.26      www      9681: sub condval {
                   9682:     my $condidx=shift;
1.54      www      9683:     my $allpathcond='';
1.713     albertel 9684:     foreach my $cond (split(/\|/,$condidx)) {
                   9685: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   9686: 	    $allpathcond.=
                   9687: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   9688: 	}
1.191     harris41 9689:     }
1.54      www      9690:     $allpathcond=~s/\|$//;
1.713     albertel 9691:     return &docondval($allpathcond);
                   9692: }
                   9693: 
                   9694: #evaluates an expression of conditions
                   9695: sub docondval {
                   9696:     my ($allpathcond) = @_;
                   9697:     my $result=0;
                   9698:     if ($env{'request.course.id'}
                   9699: 	&& defined($allpathcond)) {
                   9700: 	my $operand='|';
                   9701: 	my @stack;
                   9702: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   9703: 	    if ($chunk eq '(') {
                   9704: 		push @stack,($operand,$result);
                   9705: 	    } elsif ($chunk eq ')') {
                   9706: 		my $before=pop @stack;
                   9707: 		if (pop @stack eq '&') {
                   9708: 		    $result=$result>$before?$before:$result;
                   9709: 		} else {
                   9710: 		    $result=$result>$before?$result:$before;
                   9711: 		}
                   9712: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   9713: 		$operand=$chunk;
                   9714: 	    } else {
                   9715: 		my $new=directcondval($chunk);
                   9716: 		if ($operand eq '&') {
                   9717: 		    $result=$result>$new?$new:$result;
                   9718: 		} else {
                   9719: 		    $result=$result>$new?$result:$new;
                   9720: 		}
                   9721: 	    }
                   9722: 	}
1.26      www      9723:     }
                   9724:     return $result;
1.421     albertel 9725: }
                   9726: 
                   9727: # ---------------------------------------------------- Devalidate courseresdata
                   9728: 
                   9729: sub devalidatecourseresdata {
                   9730:     my ($coursenum,$coursedomain)=@_;
                   9731:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9732:     &devalidate_cache_new('courseres',$hashid);
1.28      www      9733: }
                   9734: 
1.763     www      9735: 
1.200     www      9736: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     9737: #
                   9738: #  Parameters:
                   9739: #      $coursenum    - Number of the course.
                   9740: #      $coursedomain - Domain at which the course was created.
                   9741: #  Returns:
                   9742: #     A hash of the course parameters along (I think) with timestamps
                   9743: #     and version info.
1.877     foxr     9744: 
1.624     albertel 9745: sub get_courseresdata {
                   9746:     my ($coursenum,$coursedomain)=@_;
1.200     www      9747:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   9748:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9749:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 9750:     my %dumpreply;
1.417     albertel 9751:     unless (defined($cached)) {
1.624     albertel 9752: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 9753: 	$result=\%dumpreply;
1.251     albertel 9754: 	my ($tmp) = keys(%dumpreply);
                   9755: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 9756: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 9757: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   9758: 	    return $tmp;
1.416     albertel 9759: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 9760: 	    $result=undef;
1.599     albertel 9761: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 9762: 	}
                   9763:     }
1.624     albertel 9764:     return $result;
                   9765: }
                   9766: 
1.633     albertel 9767: sub devalidateuserresdata {
                   9768:     my ($uname,$udom)=@_;
                   9769:     my $hashid="$udom:$uname";
                   9770:     &devalidate_cache_new('userres',$hashid);
                   9771: }
                   9772: 
1.624     albertel 9773: sub get_userresdata {
                   9774:     my ($uname,$udom)=@_;
                   9775:     #most student don\'t have any data set, check if there is some data
                   9776:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   9777: 
                   9778:     my $hashid="$udom:$uname";
                   9779:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   9780:     if (!defined($cached)) {
                   9781: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   9782: 	$result=\%resourcedata;
                   9783: 	&do_cache_new('userres',$hashid,$result,600);
                   9784:     }
                   9785:     my ($tmp)=keys(%$result);
                   9786:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   9787: 	return $result;
                   9788:     }
                   9789:     #error 2 occurs when the .db doesn't exist
                   9790:     if ($tmp!~/error: 2 /) {
1.672     albertel 9791: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 9792: 		 " Trying to get resource data for ".
                   9793: 		 $uname." at ".$udom.": ".
                   9794: 		 $tmp."</font>");
                   9795:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 9796: 	#&EXT_cache_set($udom,$uname);
                   9797: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 9798: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 9799:     }
                   9800:     return $tmp;
                   9801: }
1.879     foxr     9802: #----------------------------------------------- resdata - return resource data
                   9803: #  Purpose:
                   9804: #    Return resource data for either users or for a course.
                   9805: #  Parameters:
                   9806: #     $name      - Course/user name.
                   9807: #     $domain    - Name of the domain the user/course is registered on.
                   9808: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   9809: #     @which     - Array of names of resources desired.
                   9810: #  Returns:
                   9811: #     The value of the first reasource in @which that is found in the
                   9812: #     resource hash.
                   9813: #  Exceptional Conditions:
                   9814: #     If the $type passed in is not valid (not the string 'course' or 
                   9815: #     'user', an undefined  reference is returned.
                   9816: #     If none of the resources are found, an undef is returned
1.624     albertel 9817: sub resdata {
                   9818:     my ($name,$domain,$type,@which)=@_;
                   9819:     my $result;
                   9820:     if ($type eq 'course') {
                   9821: 	$result=&get_courseresdata($name,$domain);
                   9822:     } elsif ($type eq 'user') {
                   9823: 	$result=&get_userresdata($name,$domain);
                   9824:     }
                   9825:     if (!ref($result)) { return $result; }    
1.251     albertel 9826:     foreach my $item (@which) {
1.927     albertel 9827: 	if (defined($result->{$item->[0]})) {
                   9828: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 9829: 	}
1.250     albertel 9830:     }
1.291     albertel 9831:     return undef;
1.200     www      9832: }
                   9833: 
1.1172.2.31  raeburn  9834: sub get_numsuppfiles {
                   9835:     my ($cnum,$cdom,$ignorecache)=@_;
                   9836:     my $hashid=$cnum.':'.$cdom;
                   9837:     my ($suppcount,$cached);
                   9838:     unless ($ignorecache) {
                   9839:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   9840:     }
                   9841:     unless (defined($cached)) {
                   9842:         my $chome=&homeserver($cnum,$cdom);
                   9843:         unless ($chome eq 'no_host') {
                   9844:             ($suppcount,my $errors) = (0,0);
                   9845:             my $suppmap = 'supplemental.sequence';
                   9846:             ($suppcount,$errors) =
                   9847:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   9848:         }
                   9849:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   9850:     }
                   9851:     return $suppcount;
                   9852: }
                   9853: 
1.379     matthew  9854: #
                   9855: # EXT resource caching routines
                   9856: #
                   9857: 
                   9858: sub clear_EXT_cache_status {
1.383     albertel 9859:     &delenv('cache.EXT.');
1.379     matthew  9860: }
                   9861: 
                   9862: sub EXT_cache_status {
                   9863:     my ($target_domain,$target_user) = @_;
1.383     albertel 9864:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 9865:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  9866:         # We know already the user has no data
                   9867:         return 1;
                   9868:     } else {
                   9869:         return 0;
                   9870:     }
                   9871: }
                   9872: 
                   9873: sub EXT_cache_set {
                   9874:     my ($target_domain,$target_user) = @_;
1.383     albertel 9875:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  9876:     #&appenv({$cachename => time});
1.379     matthew  9877: }
                   9878: 
1.28      www      9879: # --------------------------------------------------------- Value of a Variable
1.58      www      9880: sub EXT {
1.715     albertel 9881: 
1.1172.2.28  raeburn  9882:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      9883:     unless ($varname) { return ''; }
1.218     albertel 9884:     #get real user name/domain, courseid and symb
                   9885:     my $courseid;
1.359     albertel 9886:     my $publicuser;
1.427     www      9887:     if ($symbparm) {
                   9888: 	$symbparm=&get_symb_from_alias($symbparm);
                   9889:     }
1.218     albertel 9890:     if (!($uname && $udom)) {
1.790     albertel 9891:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 9892:       if (!$symbparm) {	$symbparm=$cursymb; }
                   9893:     } else {
1.620     albertel 9894: 	$courseid=$env{'request.course.id'};
1.218     albertel 9895:     }
1.48      www      9896:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   9897:     my $rest;
1.320     albertel 9898:     if (defined($therest[0])) {
1.48      www      9899:        $rest=join('.',@therest);
                   9900:     } else {
                   9901:        $rest='';
                   9902:     }
1.320     albertel 9903: 
1.57      www      9904:     my $qualifierrest=$qualifier;
                   9905:     if ($rest) { $qualifierrest.='.'.$rest; }
                   9906:     my $spacequalifierrest=$space;
                   9907:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      9908:     if ($realm eq 'user') {
1.48      www      9909: # --------------------------------------------------------------- user.resource
                   9910: 	if ($space eq 'resource') {
1.651     albertel 9911: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   9912: 		  || defined($Apache::lonhomework::parsing_a_task))
                   9913: 		 &&
1.744     albertel 9914: 		 ($symbparm eq &symbread()) ) {	
                   9915: 		# if we are in the middle of processing the resource the
                   9916: 		# get the value we are planning on committing
                   9917:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   9918:                     return $Apache::lonhomework::results{$qualifierrest};
                   9919:                 } else {
                   9920:                     return $Apache::lonhomework::history{$qualifierrest};
                   9921:                 }
1.335     albertel 9922: 	    } else {
1.359     albertel 9923: 		my %restored;
1.620     albertel 9924: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 9925: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   9926: 		} else {
                   9927: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   9928: 		}
1.335     albertel 9929: 		return $restored{$qualifierrest};
                   9930: 	    }
1.48      www      9931: # ----------------------------------------------------------------- user.access
                   9932:         } elsif ($space eq 'access') {
1.218     albertel 9933: 	    # FIXME - not supporting calls for a specific user
1.48      www      9934:             return &allowed($qualifier,$rest);
                   9935: # ------------------------------------------ user.preferences, user.environment
                   9936:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 9937: 	    if (($uname eq $env{'user.name'}) &&
                   9938: 		($udom eq $env{'user.domain'})) {
                   9939: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 9940: 	    } else {
1.359     albertel 9941: 		my %returnhash;
                   9942: 		if (!$publicuser) {
                   9943: 		    %returnhash=&userenvironment($udom,$uname,
                   9944: 						 $qualifierrest);
                   9945: 		}
1.218     albertel 9946: 		return $returnhash{$qualifierrest};
                   9947: 	    }
1.48      www      9948: # ----------------------------------------------------------------- user.course
                   9949:         } elsif ($space eq 'course') {
1.218     albertel 9950: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9951:             return $env{join('.',('request.course',$qualifier))};
1.48      www      9952: # ------------------------------------------------------------------- user.role
                   9953:         } elsif ($space eq 'role') {
1.218     albertel 9954: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9955:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      9956:             if ($qualifier eq 'value') {
                   9957: 		return $role;
                   9958:             } elsif ($qualifier eq 'extent') {
                   9959:                 return $where;
                   9960:             }
                   9961: # ----------------------------------------------------------------- user.domain
                   9962:         } elsif ($space eq 'domain') {
1.218     albertel 9963:             return $udom;
1.48      www      9964: # ------------------------------------------------------------------- user.name
                   9965:         } elsif ($space eq 'name') {
1.218     albertel 9966:             return $uname;
1.48      www      9967: # ---------------------------------------------------- Any other user namespace
1.29      www      9968:         } else {
1.359     albertel 9969: 	    my %reply;
                   9970: 	    if (!$publicuser) {
                   9971: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   9972: 	    }
                   9973: 	    return $reply{$qualifierrest};
1.48      www      9974:         }
1.236     www      9975:     } elsif ($realm eq 'query') {
                   9976: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 9977:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   9978: 						[$spacequalifierrest]);
1.620     albertel 9979: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      9980:    } elsif ($realm eq 'request') {
1.48      www      9981: # ------------------------------------------------------------- request.browser
                   9982:         if ($space eq 'browser') {
1.1145    bisitz   9983:             return $env{'browser.'.$qualifier};
1.57      www      9984: # ------------------------------------------------------------ request.filename
                   9985:         } else {
1.620     albertel 9986:             return $env{'request.'.$spacequalifierrest};
1.29      www      9987:         }
1.28      www      9988:     } elsif ($realm eq 'course') {
1.48      www      9989: # ---------------------------------------------------------- course.description
1.620     albertel 9990:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      9991:     } elsif ($realm eq 'resource') {
1.165     www      9992: 
1.620     albertel 9993: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 9994: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   9995: 	}
1.693     albertel 9996: 
1.1172.2.30  raeburn  9997:         if ($qualifier eq '') {
                   9998: 	    if ($space eq 'title') {
                   9999: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   10000: 	        return &gettitle($symbparm);
                   10001: 	    }
1.693     albertel 10002: 	
1.1172.2.30  raeburn  10003: 	    if ($space eq 'map') {
                   10004: 	        my ($map) = &decode_symb($symbparm);
                   10005: 	        return &symbread($map);
                   10006: 	    }
                   10007:             if ($space eq 'maptitle') {
                   10008:                 my ($map) = &decode_symb($symbparm);
                   10009:                 return &gettitle($map);
                   10010:             }
                   10011: 	    if ($space eq 'filename') {
                   10012: 	        if ($symbparm) {
                   10013: 		    return &clutter((&decode_symb($symbparm))[2]);
                   10014: 	        }
                   10015: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 10016: 	    }
1.1172.2.30  raeburn  10017: 
                   10018:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   10019:                 if ($space eq 'visibleparts') {
                   10020:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   10021:                     my $item;
                   10022:                     if (ref($navmap)) {
                   10023:                         my $res = $navmap->getBySymb($symbparm);
                   10024:                         my $parts = $res->parts();
                   10025:                         if (ref($parts) eq 'ARRAY') {
                   10026:                             $item = join(',',@{$parts});
                   10027:                         }
                   10028:                         undef($navmap);
                   10029:                     }
                   10030:                     return $item;
                   10031:                 }
                   10032:             }
                   10033:         }
1.693     albertel 10034: 
                   10035: 	my ($section, $group, @groups);
1.593     albertel 10036: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  10037:         if (($courseid eq '') && ($cid)) {
                   10038:             $courseid = $cid;
                   10039:         }
                   10040: 	if (($symbparm && $courseid) && 
                   10041: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      10042: 
1.218     albertel 10043: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      10044: 
1.60      www      10045: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 10046: 	    my $symbp=$symbparm;
1.735     albertel 10047: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 10048: 
                   10049: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   10050: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   10051: 
1.620     albertel 10052: 	    if (($env{'user.name'} eq $uname) &&
                   10053: 		($env{'user.domain'} eq $udom)) {
                   10054: 		$section=$env{'request.course.sec'};
1.733     raeburn  10055:                 @groups = split(/:/,$env{'request.course.groups'});  
                   10056:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 10057: 	    } else {
1.539     albertel 10058: 		if (! defined($usection)) {
1.551     albertel 10059: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 10060: 		} else {
                   10061: 		    $section = $usection;
                   10062: 		}
1.733     raeburn  10063:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 10064: 	    }
                   10065: 
                   10066: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   10067: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   10068: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   10069: 
1.593     albertel 10070: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 10071: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 10072: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      10073: 
1.60      www      10074: # ----------------------------------------------------------- first, check user
1.624     albertel 10075: 
                   10076: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 10077: 				       ([$courselevelr,'resource'],
                   10078: 					[$courselevelm,'map'     ],
                   10079: 					[$courselevel, 'course'  ]));
1.931     albertel 10080: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      10081: 
1.594     albertel 10082: # ------------------------------------------------ second, check some of course
1.684     raeburn  10083:             my $coursereply;
1.691     raeburn  10084:             if (@groups > 0) {
                   10085:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   10086:                                        $mapparm,$spacequalifierrest);
1.927     albertel 10087:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  10088:             }
1.96      www      10089: 
1.684     raeburn  10090: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 10091: 				  $env{'course.'.$courseid.'.domain'},
                   10092: 				  'course',
                   10093: 				  ([$seclevelr,   'resource'],
                   10094: 				   [$seclevelm,   'map'     ],
                   10095: 				   [$seclevel,    'course'  ],
                   10096: 				   [$courselevelr,'resource']));
                   10097: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      10098: 
1.60      www      10099: # ------------------------------------------------------ third, check map parms
1.218     albertel 10100: 	    my %parmhash=();
                   10101: 	    my $thisparm='';
                   10102: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 10103: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 10104: 		    &GDBM_READER(),0640)) {
1.218     albertel 10105: 		$thisparm=$parmhash{$symbparm};
                   10106: 		untie(%parmhash);
                   10107: 	    }
1.927     albertel 10108: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 10109: 	}
1.594     albertel 10110: # ------------------------------------------ fourth, look in resource metadata
1.71      www      10111: 
1.218     albertel 10112: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 10113: 	my $filename;
                   10114: 	if (!$symbparm) { $symbparm=&symbread(); }
                   10115: 	if ($symbparm) {
1.409     www      10116: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 10117: 	} else {
1.620     albertel 10118: 	    $filename=$env{'request.filename'};
1.282     albertel 10119: 	}
                   10120: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 10121: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 10122: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 10123: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      10124: 
1.927     albertel 10125: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 10126: 	if ($symbparm && defined($courseid) && 
1.620     albertel 10127: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 10128: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   10129: 				     $env{'course.'.$courseid.'.domain'},
                   10130: 				     'course',
1.927     albertel 10131: 				     ([$courselevelm,'map'   ],
                   10132: 				      [$courselevel, 'course']));
                   10133: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 10134: 	}
1.145     www      10135: # ------------------------------------------------------------------ Cascade up
1.218     albertel 10136: 	unless ($space eq '0') {
1.336     albertel 10137: 	    my @parts=split(/_/,$space);
                   10138: 	    my $id=pop(@parts);
                   10139: 	    my $part=join('_',@parts);
                   10140: 	    if ($part eq '') { $part='0'; }
1.927     albertel 10141: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 10142: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  10143: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 10144: 	}
1.395     albertel 10145: 	if ($recurse) { return undef; }
                   10146: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 10147: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      10148: # ---------------------------------------------------- Any other user namespace
                   10149:     } elsif ($realm eq 'environment') {
                   10150: # ----------------------------------------------------------------- environment
1.620     albertel 10151: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   10152: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 10153: 	} else {
1.770     albertel 10154: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   10155: 		return '';
                   10156: 	    }
1.219     albertel 10157: 	    my %returnhash=&userenvironment($udom,$uname,
                   10158: 					    $spacequalifierrest);
                   10159: 	    return $returnhash{$spacequalifierrest};
                   10160: 	}
1.28      www      10161:     } elsif ($realm eq 'system') {
1.48      www      10162: # ----------------------------------------------------------------- system.time
                   10163: 	if ($space eq 'time') {
                   10164: 	    return time;
                   10165:         }
1.696     albertel 10166:     } elsif ($realm eq 'server') {
                   10167: # ----------------------------------------------------------------- system.time
                   10168: 	if ($space eq 'name') {
                   10169: 	    return $ENV{'SERVER_NAME'};
                   10170:         }
1.28      www      10171:     }
1.48      www      10172:     return '';
1.61      www      10173: }
                   10174: 
1.927     albertel 10175: sub get_reply {
                   10176:     my ($reply_value) = @_;
1.940     raeburn  10177:     if (ref($reply_value) eq 'ARRAY') {
                   10178:         if (wantarray) {
                   10179: 	    return @$reply_value;
                   10180:         }
                   10181:         return $reply_value->[0];
                   10182:     } else {
                   10183:         return $reply_value;
1.927     albertel 10184:     }
                   10185: }
                   10186: 
1.691     raeburn  10187: sub check_group_parms {
                   10188:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   10189:     my @groupitems = ();
                   10190:     my $resultitem;
1.927     albertel 10191:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  10192:     foreach my $group (@{$groups}) {
                   10193:         foreach my $level (@levels) {
1.927     albertel 10194:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   10195:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  10196:         }
                   10197:     }
                   10198:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   10199:                             $env{'course.'.$courseid.'.domain'},
                   10200:                                      'course',@groupitems);
                   10201:     return $coursereply;
                   10202: }
                   10203: 
                   10204: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  10205:     my ($courseid,@groups) = @_;
                   10206:     @groups = sort(@groups);
1.691     raeburn  10207:     return @groups;
                   10208: }
                   10209: 
1.395     albertel 10210: sub packages_tab_default {
                   10211:     my ($uri,$varname)=@_;
                   10212:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 10213: 
                   10214:     my (@extension,@specifics,$do_default);
                   10215:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 10216: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 10217: 	if ($pack_type eq 'default') {
                   10218: 	    $do_default=1;
                   10219: 	} elsif ($pack_type eq 'extension') {
                   10220: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 10221: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 10222: 	    # only look at packages defaults for packages that this id is
1.738     albertel 10223: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   10224: 	}
                   10225:     }
                   10226:     # first look for a package that matches the requested part id
                   10227:     foreach my $package (@specifics) {
                   10228: 	my (undef,$pack_type,$pack_part)=@{$package};
                   10229: 	next if ($pack_part ne $part);
                   10230: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10231: 	    return $packagetab{"$pack_type&$name&default"};
                   10232: 	}
                   10233:     }
                   10234:     # look for any possible matching non extension_ package
                   10235:     foreach my $package (@specifics) {
                   10236: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 10237: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10238: 	    return $packagetab{"$pack_type&$name&default"};
                   10239: 	}
1.585     albertel 10240: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 10241: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   10242: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 10243: 	}
                   10244:     }
1.738     albertel 10245:     # look for any posible extension_ match
                   10246:     foreach my $package (@extension) {
                   10247: 	my ($package,$pack_type)=@{$package};
                   10248: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10249: 	    return $packagetab{"$pack_type&$name&default"};
                   10250: 	}
                   10251: 	if (defined($packagetab{$package."&$name&default"})) {
                   10252: 	    return $packagetab{$package."&$name&default"};
                   10253: 	}
                   10254:     }
                   10255:     # look for a global default setting
                   10256:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   10257: 	return $packagetab{"default&$name&default"};
                   10258:     }
1.395     albertel 10259:     return undef;
                   10260: }
                   10261: 
1.334     albertel 10262: sub add_prefix_and_part {
                   10263:     my ($prefix,$part)=@_;
                   10264:     my $keyroot;
                   10265:     if (defined($prefix) && $prefix !~ /^__/) {
                   10266: 	# prefix that has a part already
                   10267: 	$keyroot=$prefix;
                   10268:     } elsif (defined($prefix)) {
                   10269: 	# prefix that is missing a part
                   10270: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   10271:     } else {
                   10272: 	# no prefix at all
                   10273: 	if (defined($part)) { $keyroot='_'.$part; }
                   10274:     }
                   10275:     return $keyroot;
                   10276: }
                   10277: 
1.71      www      10278: # ---------------------------------------------------------------- Get metadata
                   10279: 
1.599     albertel 10280: my %metaentry;
1.1070    www      10281: my %importedpartids;
1.71      www      10282: sub metadata {
1.176     www      10283:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      10284:     $uri=&declutter($uri);
1.288     albertel 10285:     # if it is a non metadata possible uri return quickly
1.529     albertel 10286:     if (($uri eq '') || 
                   10287: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.20  raeburn  10288: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108    raeburn  10289:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 10290: 	return undef;
                   10291:     }
1.1140    www      10292:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
1.924     albertel 10293: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 10294: 	return undef;
1.288     albertel 10295:     }
1.73      www      10296:     my $filename=$uri;
                   10297:     $uri=~s/\.meta$//;
1.172     www      10298: #
                   10299: # Is the metadata already cached?
1.177     www      10300: # Look at timestamp of caching
1.172     www      10301: # Everything is cached by the main uri, libraries are never directly cached
                   10302: #
1.428     albertel 10303:     if (!defined($liburi)) {
1.599     albertel 10304: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 10305: 	if (defined($cached)) { return $result->{':'.$what}; }
                   10306:     }
                   10307:     {
1.1069    www      10308: # Imported parts would go here
1.1070    www      10309:         my %importedids=();
                   10310:         my @origfileimportpartids=();
1.1069    www      10311:         my $importedparts=0;
1.172     www      10312: #
                   10313: # Is this a recursive call for a library?
                   10314: #
1.599     albertel 10315: #	if (! exists($metacache{$uri})) {
                   10316: #	    $metacache{$uri}={};
                   10317: #	}
1.924     albertel 10318: 	my $cachetime = 60*60;
1.171     www      10319:         if ($liburi) {
                   10320: 	    $liburi=&declutter($liburi);
                   10321:             $filename=$liburi;
1.401     bowersj2 10322:         } else {
1.599     albertel 10323: 	    &devalidate_cache_new('meta',$uri);
                   10324: 	    undef(%metaentry);
1.401     bowersj2 10325: 	}
1.140     www      10326:         my %metathesekeys=();
1.73      www      10327:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 10328: 	my $metastring;
1.1140    www      10329: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 10330: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 10331: 	    $metastring = 
1.929     albertel 10332: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 10333: 					  ('grade_target' => 'meta'));
                   10334: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  10335: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   10336:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 10337: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 10338: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 10339: 	    $metastring=&getfile($file);
1.489     albertel 10340: 	}
1.208     albertel 10341:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      10342:         my $token;
1.140     www      10343:         undef %metathesekeys;
1.71      www      10344:         while ($token=$parser->get_token) {
1.339     albertel 10345: 	    if ($token->[0] eq 'S') {
                   10346: 		if (defined($token->[2]->{'package'})) {
1.172     www      10347: #
                   10348: # This is a package - get package info
                   10349: #
1.339     albertel 10350: 		    my $package=$token->[2]->{'package'};
                   10351: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10352: 		    if (defined($token->[2]->{'id'})) { 
                   10353: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   10354: 		    }
1.599     albertel 10355: 		    if ($metaentry{':packages'}) {
                   10356: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 10357: 		    } else {
1.599     albertel 10358: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 10359: 		    }
1.736     albertel 10360: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 10361: 			my $part=$keyroot;
                   10362: 			$part=~s/^\_//;
1.736     albertel 10363: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   10364: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   10365: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 10366: 			    # ignore package.tab specified default values
                   10367:                             # here &package_tab_default() will fetch those
                   10368: 			    if ($subp eq 'default') { next; }
1.736     albertel 10369: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 10370: 			    my $unikey;
                   10371: 			    if ($pack =~ /_0$/) {
                   10372: 				$unikey='parameter_0_'.$name;
                   10373: 				$part=0;
                   10374: 			    } else {
                   10375: 				$unikey='parameter'.$keyroot.'_'.$name;
                   10376: 			    }
1.339     albertel 10377: 			    if ($subp eq 'display') {
                   10378: 				$value.=' [Part: '.$part.']';
                   10379: 			    }
1.599     albertel 10380: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 10381: 			    $metathesekeys{$unikey}=1;
1.599     albertel 10382: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10383: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 10384: 			    }
1.599     albertel 10385: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   10386: 				$metaentry{':'.$unikey}=
                   10387: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 10388: 			    }
1.339     albertel 10389: 			}
                   10390: 		    }
                   10391: 		} else {
1.172     www      10392: #
                   10393: # This is not a package - some other kind of start tag
1.339     albertel 10394: #
                   10395: 		    my $entry=$token->[1];
1.1068    www      10396: 		    my $unikey='';
1.175     www      10397: 
1.339     albertel 10398: 		    if ($entry eq 'import') {
1.175     www      10399: #
                   10400: # Importing a library here
1.339     albertel 10401: #
1.1067    www      10402:                         my $location=$parser->get_text('/import');
                   10403:                         my $dir=$filename;
                   10404:                         $dir=~s|[^/]*$||;
                   10405:                         $location=&filelocation($dir,$location);
1.1069    www      10406:                        
1.1068    www      10407:                         my $importmode=$token->[2]->{'importmode'};
                   10408:                         if ($importmode eq 'problem') {
1.1069    www      10409: # Import as problem/response
1.1068    www      10410:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10411:                         } elsif ($importmode eq 'part') {
                   10412: # Import as part(s)
1.1069    www      10413:                            $importedparts=1;
                   10414: # We need to get the original file and the imported file to get the part order correct
                   10415: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   10416: # Load and inspect original file
1.1070    www      10417:                            if ($#origfileimportpartids<0) {
                   10418:                               undef(%importedpartids);
                   10419:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   10420:                               my $origfile=&getfile($origfilelocation);
                   10421:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10422:                            }
                   10423: 
1.1069    www      10424: # Load and inspect imported file
                   10425:                            my $impfile=&getfile($location);
                   10426:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10427:                            if ($#impfilepartids>=0) {
                   10428: # This problem had parts
1.1070    www      10429:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      10430:                            } else {
                   10431: # Importing by turning a single problem into a problem part
                   10432: # It gets the import-tags ID as part-ID
                   10433:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      10434:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      10435:                            }
1.1068    www      10436:                         } else {
                   10437: # Normal import
                   10438:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10439:                            if (defined($token->[2]->{'id'})) {
                   10440:                               $unikey.='_'.$token->[2]->{'id'};
                   10441:                            }
1.1067    www      10442:                         }
                   10443: 
1.339     albertel 10444: 			if ($depthcount<20) {
1.736     albertel 10445: 			    my $metadata = 
                   10446: 				&metadata($uri,'keys', $location,$unikey,
                   10447: 					  $depthcount+1);
                   10448: 			    foreach my $meta (split(',',$metadata)) {
                   10449: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   10450: 				$metathesekeys{$meta}=1;
1.339     albertel 10451: 			    }
1.1068    www      10452: 			
                   10453:                         }
1.1067    www      10454: 		    } else {
                   10455: #
                   10456: # Not importing, some other kind of non-package, non-library start tag
                   10457: # 
                   10458:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10459:                         if (defined($token->[2]->{'id'})) {
                   10460:                             $unikey.='_'.$token->[2]->{'id'};
                   10461:                         }
1.339     albertel 10462: 			if (defined($token->[2]->{'name'})) { 
                   10463: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   10464: 			}
                   10465: 			$metathesekeys{$unikey}=1;
1.736     albertel 10466: 			foreach my $param (@{$token->[3]}) {
                   10467: 			    $metaentry{':'.$unikey.'.'.$param} =
                   10468: 				$token->[2]->{$param};
1.339     albertel 10469: 			}
                   10470: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 10471: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 10472: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   10473: 		 # only ws inside the tag, and not in default, so use default
                   10474: 		 # as value
1.599     albertel 10475: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 10476: 			} elsif ( $internaltext =~ /\S/ ) {
                   10477: 		  # something interesting inside the tag
                   10478: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 10479: 			} else {
1.908     albertel 10480: 		  # no interesting values, don't set a default
1.339     albertel 10481: 			}
1.172     www      10482: # end of not-a-package not-a-library import
1.339     albertel 10483: 		    }
1.172     www      10484: # end of not-a-package start tag
1.339     albertel 10485: 		}
1.172     www      10486: # the next is the end of "start tag"
1.339     albertel 10487: 	    }
                   10488: 	}
1.483     albertel 10489: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 10490: 	$extension = lc($extension);
                   10491: 	if ($extension eq 'htm') { $extension='html'; }
                   10492: 
1.737     albertel 10493: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 10494: 	    #no specific packages #how's our extension
                   10495: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 10496: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 10497: 					 \%metathesekeys);
                   10498: 	}
1.883     albertel 10499: 
                   10500: 	if (!exists($metaentry{':packages'})
                   10501: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 10502: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 10503: 		#no specific packages well let's get default then
                   10504: 		if ($key!~/^default&/) { next; }
1.488     albertel 10505: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 10506: 					     \%metathesekeys);
                   10507: 	    }
                   10508: 	}
1.338     www      10509: # are there custom rights to evaluate
1.599     albertel 10510: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 10511: 
1.338     www      10512:     #
                   10513:     # Importing a rights file here
1.339     albertel 10514:     #
                   10515: 	    unless ($depthcount) {
1.599     albertel 10516: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 10517: 		my $dir=$filename;
                   10518: 		$dir=~s|[^/]*$||;
                   10519: 		$location=&filelocation($dir,$location);
1.736     albertel 10520: 		my $rights_metadata =
                   10521: 		    &metadata($uri,'keys',$location,'_rights',
                   10522: 			      $depthcount+1);
                   10523: 		foreach my $rights (split(',',$rights_metadata)) {
                   10524: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   10525: 		    $metathesekeys{$rights}=1;
1.339     albertel 10526: 		}
                   10527: 	    }
                   10528: 	}
1.737     albertel 10529: 	# uniqifiy package listing
                   10530: 	my %seen;
                   10531: 	my @uniq_packages =
                   10532: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   10533: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   10534: 
1.1070    www      10535:         if ($importedparts) {
                   10536: # We had imported parts and need to rebuild partorder
                   10537:            $metaentry{':partorder'}='';
                   10538:            $metathesekeys{'partorder'}=1;
                   10539:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   10540:                if ($origfileimportpartids[$index] eq 'part') {
                   10541: # original part, part of the problem
                   10542:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   10543:                } else {
                   10544: # we have imported parts at this position
                   10545:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   10546:                }
                   10547:            }
                   10548:            $metaentry{':partorder'}=~s/^\,//;
                   10549:         }
                   10550: 
1.737     albertel 10551: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 10552: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   10553: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 10554: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      10555: # this is the end of "was not already recently cached
1.71      www      10556:     }
1.599     albertel 10557:     return $metaentry{':'.$what};
1.261     albertel 10558: }
                   10559: 
1.488     albertel 10560: sub metadata_create_package_def {
1.483     albertel 10561:     my ($uri,$key,$package,$metathesekeys)=@_;
                   10562:     my ($pack,$name,$subp)=split(/\&/,$key);
                   10563:     if ($subp eq 'default') { next; }
                   10564:     
1.599     albertel 10565:     if (defined($metaentry{':packages'})) {
                   10566: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 10567:     } else {
1.599     albertel 10568: 	$metaentry{':packages'}=$package;
1.483     albertel 10569:     }
                   10570:     my $value=$packagetab{$key};
                   10571:     my $unikey;
                   10572:     $unikey='parameter_0_'.$name;
1.599     albertel 10573:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 10574:     $$metathesekeys{$unikey}=1;
1.599     albertel 10575:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10576: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 10577:     }
1.599     albertel 10578:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   10579: 	$metaentry{':'.$unikey}=
                   10580: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 10581:     }
                   10582: }
                   10583: 
1.261     albertel 10584: sub metadata_generate_part0 {
                   10585:     my ($metadata,$metacache,$uri) = @_;
                   10586:     my %allnames;
1.737     albertel 10587:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 10588: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 10589: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   10590: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 10591: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 10592: 	    $allnames{$name}=$part;
                   10593: 	  }
                   10594: 	}
                   10595:     }
                   10596:     foreach my $name (keys(%allnames)) {
                   10597:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 10598:       my $key=":parameter_0_$name";
1.261     albertel 10599:       $$metacache{"$key.part"}='0';
                   10600:       $$metacache{"$key.name"}=$name;
1.428     albertel 10601:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 10602: 					   $allnames{$name}.'_'.$name.
                   10603: 					   '.type'};
1.428     albertel 10604:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 10605: 			     '.display'};
1.644     www      10606:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 10607:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 10608:       $$metacache{"$key.display"}=$olddis;
                   10609:     }
1.71      www      10610: }
                   10611: 
1.764     albertel 10612: # ------------------------------------------------------ Devalidate title cache
                   10613: 
                   10614: sub devalidate_title_cache {
                   10615:     my ($url)=@_;
                   10616:     if (!$env{'request.course.id'}) { return; }
                   10617:     my $symb=&symbread($url);
                   10618:     if (!$symb) { return; }
                   10619:     my $key=$env{'request.course.id'}."\0".$symb;
                   10620:     &devalidate_cache_new('title',$key);
                   10621: }
                   10622: 
1.1014    droeschl 10623: # ------------------------------------------------- Get the title of a course
                   10624: 
                   10625: sub current_course_title {
                   10626:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   10627: }
1.301     www      10628: # ------------------------------------------------- Get the title of a resource
                   10629: 
                   10630: sub gettitle {
                   10631:     my $urlsymb=shift;
                   10632:     my $symb=&symbread($urlsymb);
1.534     albertel 10633:     if ($symb) {
1.620     albertel 10634: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 10635: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 10636: 	if (defined($cached)) { 
                   10637: 	    return $result;
                   10638: 	}
1.534     albertel 10639: 	my ($map,$resid,$url)=&decode_symb($symb);
                   10640: 	my $title='';
1.907     albertel 10641: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   10642: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   10643: 	} else {
                   10644: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10645: 		    &GDBM_READER(),0640)) {
                   10646: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   10647: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   10648: 		untie(%bighash);
                   10649: 	    }
1.534     albertel 10650: 	}
                   10651: 	$title=~s/\&colon\;/\:/gs;
                   10652: 	if ($title) {
1.1159    www      10653: # Remember both $symb and $title for dynamic metadata
                   10654:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      10655:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      10656: # Cache this title and then return it
1.599     albertel 10657: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 10658: 	}
                   10659: 	$urlsymb=$url;
                   10660:     }
                   10661:     my $title=&metadata($urlsymb,'title');
                   10662:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   10663:     return $title;
1.301     www      10664: }
1.613     albertel 10665: 
1.614     albertel 10666: sub get_slot {
                   10667:     my ($which,$cnum,$cdom)=@_;
                   10668:     if (!$cnum || !$cdom) {
1.790     albertel 10669: 	(undef,my $courseid)=&whichuser();
1.620     albertel 10670: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   10671: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 10672:     }
1.703     albertel 10673:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   10674:     my %slotinfo;
                   10675:     if (exists($remembered{$key})) {
                   10676: 	$slotinfo{$which} = $remembered{$key};
                   10677:     } else {
                   10678: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   10679: 	&Apache::lonhomework::showhash(%slotinfo);
                   10680: 	my ($tmp)=keys(%slotinfo);
                   10681: 	if ($tmp=~/^error:/) { return (); }
                   10682: 	$remembered{$key} = $slotinfo{$which};
                   10683:     }
1.616     albertel 10684:     if (ref($slotinfo{$which}) eq 'HASH') {
                   10685: 	return %{$slotinfo{$which}};
                   10686:     }
                   10687:     return $slotinfo{$which};
1.614     albertel 10688: }
1.1150    raeburn  10689: 
                   10690: sub get_reservable_slots {
                   10691:     my ($cnum,$cdom,$uname,$udom) = @_;
                   10692:     my $now = time;
                   10693:     my $reservable_info;
                   10694:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   10695:     if (exists($remembered{$key})) {
                   10696:         $reservable_info = $remembered{$key};
                   10697:     } else {
                   10698:         my %resv;
                   10699:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   10700:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   10701:         $reservable_info = \%resv;
                   10702:         $remembered{$key} = $reservable_info;
                   10703:     }
                   10704:     return $reservable_info;
                   10705: }
                   10706: 
                   10707: sub get_course_slots {
                   10708:     my ($cnum,$cdom) = @_;
                   10709:     my $hashid=$cnum.':'.$cdom;
                   10710:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   10711:     if (defined($cached)) {
                   10712:         if (ref($result) eq 'HASH') {
                   10713:             return %{$result};
                   10714:         }
                   10715:     } else {
                   10716:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   10717:         my ($tmp) = keys(%slots);
                   10718:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  10719:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  10720:             return %slots;
                   10721:         }
                   10722:     }
                   10723:     return;
                   10724: }
                   10725: 
                   10726: sub devalidate_slots_cache {
                   10727:     my ($cnum,$cdom)=@_;
                   10728:     my $hashid=$cnum.':'.$cdom;
                   10729:     &devalidate_cache_new('allslots',$hashid);
                   10730: }
                   10731: 
1.1172.2.8  raeburn  10732: sub get_coursechange {
                   10733:     my ($cdom,$cnum) = @_;
                   10734:     if ($cdom eq '' || $cnum eq '') {
                   10735:         return unless ($env{'request.course.id'});
                   10736:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10737:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10738:     }
                   10739:     my $hashid=$cdom.'_'.$cnum;
                   10740:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   10741:     if ((defined($cached)) && ($change ne '')) {
                   10742:         return $change;
                   10743:     } else {
                   10744:         my %crshash;
                   10745:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   10746:         if ($crshash{'internal.contentchange'} eq '') {
                   10747:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   10748:             if ($change eq '') {
                   10749:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   10750:                 $change = $crshash{'internal.created'};
                   10751:             }
                   10752:         } else {
                   10753:             $change = $crshash{'internal.contentchange'};
                   10754:         }
                   10755:         my $cachetime = 600;
                   10756:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   10757:     }
                   10758:     return $change;
                   10759: }
                   10760: 
                   10761: sub devalidate_coursechange_cache {
                   10762:     my ($cnum,$cdom)=@_;
                   10763:     my $hashid=$cnum.':'.$cdom;
                   10764:     &devalidate_cache_new('crschange',$hashid);
                   10765: }
                   10766: 
1.31      www      10767: # ------------------------------------------------- Update symbolic store links
                   10768: 
                   10769: sub symblist {
                   10770:     my ($mapname,%newhash)=@_;
1.438     www      10771:     $mapname=&deversion(&declutter($mapname));
1.31      www      10772:     my %hash;
1.620     albertel 10773:     if (($env{'request.course.fn'}) && (%newhash)) {
                   10774:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10775:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  10776: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 10777: 		next if ($url eq 'last_known'
                   10778: 			 && $env{'form.no_update_last_known'});
                   10779: 		$hash{declutter($url)}=&encode_symb($mapname,
                   10780: 						    $newhash{$url}->[1],
                   10781: 						    $newhash{$url}->[0]);
1.191     harris41 10782:             }
1.31      www      10783:             if (untie(%hash)) {
                   10784: 		return 'ok';
                   10785:             }
                   10786:         }
                   10787:     }
                   10788:     return 'error';
1.212     www      10789: }
                   10790: 
                   10791: # --------------------------------------------------------------- Verify a symb
                   10792: 
                   10793: sub symbverify {
1.1172.2.11  raeburn  10794:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      10795:     my $thisfn=$thisurl;
1.439     www      10796:     $thisfn=&declutter($thisfn);
1.215     www      10797: # direct jump to resource in page or to a sequence - will construct own symbs
                   10798:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   10799: # check URL part
1.409     www      10800:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      10801: 
1.431     www      10802:     unless ($url eq $thisfn) { return 0; }
1.213     www      10803: 
1.216     www      10804:     $symb=&symbclean($symb);
1.510     www      10805:     $thisurl=&deversion($thisurl);
1.439     www      10806:     $thisfn=&deversion($thisfn);
1.213     www      10807: 
                   10808:     my %bighash;
                   10809:     my $okay=0;
1.431     www      10810: 
1.620     albertel 10811:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10812:                             &GDBM_READER(),0640)) {
1.1172.2.13  raeburn  10813:         my $noclutter;
1.1032    raeburn  10814:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   10815:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  10816:             if ($map =~ m{^uploaded/.+\.page$}) {
                   10817:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   10818:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   10819:                 $noclutter = 1;
                   10820:             }
                   10821:         }
                   10822:         my $ids;
                   10823:         if ($noclutter) {
                   10824:             $ids=$bighash{'ids_'.$thisurl};
                   10825:         } else {
                   10826:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  10827:         }
1.1102    raeburn  10828:         unless ($ids) {
1.1172.2.13  raeburn  10829:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  10830:             $ids=$bighash{$idkey};
1.216     www      10831:         }
                   10832:         if ($ids) {
                   10833: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  10834:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   10835:                 $symb =~ s/\?.+$//;
                   10836:             }
1.800     albertel 10837: 	    foreach my $id (split(/\,/,$ids)) {
                   10838: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      10839:                if (
                   10840:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  10841:    eq $symb) {
1.1172.2.11  raeburn  10842:                    if (ref($encstate)) {
                   10843:                        $$encstate = $bighash{'encrypted_'.$id};
                   10844:                    }
1.1172.2.13  raeburn  10845:                    if (($env{'request.role.adv'}) ||
                   10846:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  10847:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  10848:                        $okay=1;
                   10849:                        last;
                   10850:                    }
                   10851:                }
                   10852:            }
1.216     www      10853:         }
1.213     www      10854: 	untie(%bighash);
                   10855:     }
                   10856:     return $okay;
1.31      www      10857: }
                   10858: 
1.210     www      10859: # --------------------------------------------------------------- Clean-up symb
                   10860: 
                   10861: sub symbclean {
                   10862:     my $symb=shift;
1.568     albertel 10863:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      10864: # remove version from map
                   10865:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      10866: 
1.210     www      10867: # remove version from URL
                   10868:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      10869: 
1.507     www      10870: # remove wrapper
                   10871: 
1.510     www      10872:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 10873:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      10874:     return $symb;
1.409     www      10875: }
                   10876: 
                   10877: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 10878: 
                   10879: sub encode_symb {
                   10880:     my ($map,$resid,$url)=@_;
                   10881:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   10882: }
1.409     www      10883: 
                   10884: sub decode_symb {
1.568     albertel 10885:     my $symb=shift;
                   10886:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   10887:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      10888:     return (&fixversion($map),$resid,&fixversion($url));
                   10889: }
                   10890: 
                   10891: sub fixversion {
                   10892:     my $fn=shift;
1.609     banghart 10893:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      10894:     my %bighash;
                   10895:     my $uri=&clutter($fn);
1.620     albertel 10896:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      10897: # is this cached?
1.599     albertel 10898:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      10899:     if (defined($cached)) { return $result; }
                   10900: # unfortunately not cached, or expired
1.620     albertel 10901:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      10902: 	    &GDBM_READER(),0640)) {
                   10903:  	if ($bighash{'version_'.$uri}) {
                   10904:  	    my $version=$bighash{'version_'.$uri};
1.444     www      10905:  	    unless (($version eq 'mostrecent') || 
                   10906: 		    ($version==&getversion($uri))) {
1.440     www      10907:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   10908:  	    }
                   10909:  	}
                   10910:  	untie %bighash;
1.413     www      10911:     }
1.599     albertel 10912:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      10913: }
                   10914: 
                   10915: sub deversion {
                   10916:     my $url=shift;
                   10917:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   10918:     return $url;
1.210     www      10919: }
                   10920: 
1.31      www      10921: # ------------------------------------------------------ Return symb list entry
                   10922: 
                   10923: sub symbread {
1.249     www      10924:     my ($thisfn,$donotrecurse)=@_;
1.1172.2.13  raeburn  10925:     my $cache_str;
                   10926:     if ($thisfn ne '') {
                   10927:         $cache_str='request.symbread.cached.'.$thisfn;
                   10928:         if ($env{$cache_str} ne '') {
1.1172.2.8  raeburn  10929:             return $env{$cache_str};
                   10930:         }
1.1172.2.13  raeburn  10931:    } else {
1.242     www      10932: # no filename provided? try from environment
1.620     albertel 10933:         if ($env{'request.symb'}) {
1.1172.2.13  raeburn  10934:             return $env{$cache_str}=&symbclean($env{'request.symb'});
                   10935:         }
                   10936:         $thisfn=$env{'request.filename'};
1.44      www      10937:     }
1.569     albertel 10938:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      10939: # is that filename actually a symb? Verify, clean, and return
                   10940:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 10941: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 10942: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 10943: 	}
1.242     www      10944:     }
1.44      www      10945:     $thisfn=declutter($thisfn);
1.31      www      10946:     my %hash;
1.37      www      10947:     my %bighash;
                   10948:     my $syval='';
1.620     albertel 10949:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  10950:         my $targetfn = $thisfn;
1.609     banghart 10951:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  10952:             $targetfn = 'adm/wrapper/'.$thisfn;
                   10953:         }
1.687     albertel 10954: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   10955: 	    $targetfn=$1;
                   10956: 	}
1.620     albertel 10957:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10958:                       &GDBM_READER(),0640)) {
1.481     raeburn  10959: 	    $syval=$hash{$targetfn};
1.37      www      10960:             untie(%hash);
                   10961:         }
                   10962: # ---------------------------------------------------------- There was an entry
                   10963:         if ($syval) {
1.601     albertel 10964: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 10965: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  10966: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10967: 		    #return $env{$cache_str}='';
1.601     albertel 10968: 		#}    
                   10969: 		#$syval.=$1;
                   10970: 	    #}
1.37      www      10971:         } else {
                   10972: # ------------------------------------------------------- Was not in symb table
1.620     albertel 10973:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10974:                             &GDBM_READER(),0640)) {
1.37      www      10975: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      10976:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      10977:               unless ($ids) { 
                   10978:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      10979:               }
                   10980:               unless ($ids) {
                   10981: # alias?
                   10982: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      10983:               }
1.37      www      10984:               if ($ids) {
                   10985: # ------------------------------------------------------------------- Has ID(s)
                   10986:                  my @possibilities=split(/\,/,$ids);
1.39      www      10987:                  if ($#possibilities==0) {
                   10988: # ----------------------------------------------- There is only one possibility
1.37      www      10989: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 10990: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10991: 						    $resid,$thisfn);
1.249     www      10992:                  } elsif (!$donotrecurse) {
1.39      www      10993: # ------------------------------------------ There is more than one possibility
                   10994:                      my $realpossible=0;
1.800     albertel 10995:                      foreach my $id (@possibilities) {
                   10996: 			 my $file=$bighash{'src_'.$id};
1.39      www      10997:                          if (&allowed('bre',$file)) {
1.800     albertel 10998:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      10999:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   11000: 				$realpossible++;
1.626     albertel 11001:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11002: 						    $resid,$thisfn);
1.39      www      11003:                             }
                   11004: 			 }
1.191     harris41 11005:                      }
1.39      www      11006: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      11007:                  } else {
                   11008:                      $syval='';
1.37      www      11009:                  }
                   11010: 	      }
                   11011:               untie(%bighash)
1.481     raeburn  11012:            }
1.31      www      11013:         }
1.62      www      11014:         if ($syval) {
1.620     albertel 11015: 	    return $env{$cache_str}=$syval;
1.62      www      11016:         }
1.31      www      11017:     }
1.949     raeburn  11018:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11019:     return $env{$cache_str}='';
1.31      www      11020: }
                   11021: 
                   11022: # ---------------------------------------------------------- Return random seed
                   11023: 
1.32      www      11024: sub numval {
                   11025:     my $txt=shift;
                   11026:     $txt=~tr/A-J/0-9/;
                   11027:     $txt=~tr/a-j/0-9/;
                   11028:     $txt=~tr/K-T/0-9/;
                   11029:     $txt=~tr/k-t/0-9/;
                   11030:     $txt=~tr/U-Z/0-5/;
                   11031:     $txt=~tr/u-z/0-5/;
                   11032:     $txt=~s/\D//g;
1.564     albertel 11033:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      11034:     return int($txt);
1.368     albertel 11035: }
                   11036: 
1.484     albertel 11037: sub numval2 {
                   11038:     my $txt=shift;
                   11039:     $txt=~tr/A-J/0-9/;
                   11040:     $txt=~tr/a-j/0-9/;
                   11041:     $txt=~tr/K-T/0-9/;
                   11042:     $txt=~tr/k-t/0-9/;
                   11043:     $txt=~tr/U-Z/0-5/;
                   11044:     $txt=~tr/u-z/0-5/;
                   11045:     $txt=~s/\D//g;
                   11046:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11047:     my $total;
                   11048:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 11049:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 11050:     return int($total);
                   11051: }
                   11052: 
1.575     albertel 11053: sub numval3 {
                   11054:     use integer;
                   11055:     my $txt=shift;
                   11056:     $txt=~tr/A-J/0-9/;
                   11057:     $txt=~tr/a-j/0-9/;
                   11058:     $txt=~tr/K-T/0-9/;
                   11059:     $txt=~tr/k-t/0-9/;
                   11060:     $txt=~tr/U-Z/0-5/;
                   11061:     $txt=~tr/u-z/0-5/;
                   11062:     $txt=~s/\D//g;
                   11063:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11064:     my $total;
                   11065:     foreach my $val (@txts) { $total+=$val; }
                   11066:     if ($_64bit) { $total=(($total<<32)>>32); }
                   11067:     return $total;
                   11068: }
                   11069: 
1.675     albertel 11070: sub digest {
                   11071:     my ($data)=@_;
                   11072:     my $digest=&Digest::MD5::md5($data);
                   11073:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   11074:     my ($e,$f);
                   11075:     {
                   11076:         use integer;
                   11077:         $e=($a+$b);
                   11078:         $f=($c+$d);
                   11079:         if ($_64bit) {
                   11080:             $e=(($e<<32)>>32);
                   11081:             $f=(($f<<32)>>32);
                   11082:         }
                   11083:     }
                   11084:     if (wantarray) {
                   11085: 	return ($e,$f);
                   11086:     } else {
                   11087: 	my $g;
                   11088: 	{
                   11089: 	    use integer;
                   11090: 	    $g=($e+$f);
                   11091: 	    if ($_64bit) {
                   11092: 		$g=(($g<<32)>>32);
                   11093: 	    }
                   11094: 	}
                   11095: 	return $g;
                   11096:     }
                   11097: }
                   11098: 
1.368     albertel 11099: sub latest_rnd_algorithm_id {
1.675     albertel 11100:     return '64bit5';
1.366     albertel 11101: }
1.32      www      11102: 
1.503     albertel 11103: sub get_rand_alg {
                   11104:     my ($courseid)=@_;
1.790     albertel 11105:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 11106:     if ($courseid) {
1.620     albertel 11107: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 11108:     }
                   11109:     return &latest_rnd_algorithm_id();
                   11110: }
                   11111: 
1.562     albertel 11112: sub validCODE {
                   11113:     my ($CODE)=@_;
                   11114:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   11115:     return 0;
                   11116: }
                   11117: 
1.491     albertel 11118: sub getCODE {
1.620     albertel 11119:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 11120:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   11121: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   11122: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 11123: 	return $Apache::lonhomework::history{'resource.CODE'};
                   11124:     }
                   11125:     return undef;
                   11126: }
1.1133    foxr     11127: #
                   11128: #  Determines the random seed for a specific context:
                   11129: #
                   11130: # parameters:
                   11131: #   symb      - in course context the symb for the seed.
                   11132: #   course_id - The course id of the form domain_coursenum.
                   11133: #   domain    - Domain for the user.
                   11134: #   course    - Course for the user.
                   11135: #   cenv      - environment of the course.
                   11136: #
                   11137: # NOTE:
                   11138: #   All parameters are picked out of the environment if missing
                   11139: #   or not defined.
                   11140: #   If a symb cannot be determined the current time is used instead.
                   11141: #
                   11142: #  For a given well defined symb, courside, domain, username,
                   11143: #  and course environment, the seed is reproducible.
                   11144: #
1.31      www      11145: sub rndseed {
1.1133    foxr     11146:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 11147:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 11148:     if (!defined($symb)) {
1.366     albertel 11149: 	unless ($symb=$wsymb) { return time; }
                   11150:     }
1.1146    foxr     11151:     if (!defined $courseid) { 
                   11152: 	$courseid=$wcourseid; 
                   11153:     }
                   11154:     if (!defined $domain) { $domain=$wdomain; }
                   11155:     if (!defined $username) { $username=$wusername }
1.1133    foxr     11156: 
                   11157:     my $which;
                   11158:     if (defined($cenv->{'rndseed'})) {
                   11159: 	$which = $cenv->{'rndseed'};
                   11160:     } else {
                   11161: 	$which =&get_rand_alg($courseid);
                   11162:     }
1.491     albertel 11163:     if (defined(&getCODE())) {
1.675     albertel 11164: 	if ($which eq '64bit5') {
                   11165: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   11166: 	} elsif ($which eq '64bit4') {
1.575     albertel 11167: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   11168: 	} else {
                   11169: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   11170: 	}
1.675     albertel 11171:     } elsif ($which eq '64bit5') {
                   11172: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 11173:     } elsif ($which eq '64bit4') {
                   11174: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 11175:     } elsif ($which eq '64bit3') {
                   11176: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 11177:     } elsif ($which eq '64bit2') {
                   11178: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 11179:     } elsif ($which eq '64bit') {
                   11180: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   11181:     }
                   11182:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   11183: }
                   11184: 
                   11185: sub rndseed_32bit {
                   11186:     my ($symb,$courseid,$domain,$username)=@_;
                   11187:     {
                   11188: 	use integer;
                   11189: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   11190: 	my $symbseed=numval($symb) << 22;
                   11191: 	my $namechck=unpack("%32C*",$username) << 17;
                   11192: 	my $nameseed=numval($username) << 12;
                   11193: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   11194: 	my $courseseed=unpack("%32C*",$courseid);
                   11195: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 11196: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11197: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 11198: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 11199: 	return $num;
                   11200:     }
                   11201: }
                   11202: 
                   11203: sub rndseed_64bit {
                   11204:     my ($symb,$courseid,$domain,$username)=@_;
                   11205:     {
                   11206: 	use integer;
                   11207: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   11208: 	my $symbseed=numval($symb) << 10;
                   11209: 	my $namechck=unpack("%32S*",$username);
                   11210: 	
                   11211: 	my $nameseed=numval($username) << 21;
                   11212: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   11213: 	my $courseseed=unpack("%32S*",$courseid);
                   11214: 	
                   11215: 	my $num1=$symbchck+$symbseed+$namechck;
                   11216: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11217: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11218: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 11219: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 11220: 	return "$num1,$num2";
1.155     albertel 11221:     }
1.366     albertel 11222: }
                   11223: 
1.443     albertel 11224: sub rndseed_64bit2 {
                   11225:     my ($symb,$courseid,$domain,$username)=@_;
                   11226:     {
                   11227: 	use integer;
                   11228: 	# strings need to be an even # of cahracters long, it it is odd the
                   11229:         # last characters gets thrown away
                   11230: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11231: 	my $symbseed=numval($symb) << 10;
                   11232: 	my $namechck=unpack("%32S*",$username.' ');
                   11233: 	
                   11234: 	my $nameseed=numval($username) << 21;
1.501     albertel 11235: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11236: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11237: 	
                   11238: 	my $num1=$symbchck+$symbseed+$namechck;
                   11239: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11240: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11241: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 11242: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 11243: 	return "$num1,$num2";
                   11244:     }
                   11245: }
                   11246: 
                   11247: sub rndseed_64bit3 {
                   11248:     my ($symb,$courseid,$domain,$username)=@_;
                   11249:     {
                   11250: 	use integer;
                   11251: 	# strings need to be an even # of cahracters long, it it is odd the
                   11252:         # last characters gets thrown away
                   11253: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11254: 	my $symbseed=numval2($symb) << 10;
                   11255: 	my $namechck=unpack("%32S*",$username.' ');
                   11256: 	
                   11257: 	my $nameseed=numval2($username) << 21;
1.443     albertel 11258: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11259: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11260: 	
                   11261: 	my $num1=$symbchck+$symbseed+$namechck;
                   11262: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11263: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11264: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 11265: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11266: 	
1.503     albertel 11267: 	return "$num1:$num2";
1.443     albertel 11268:     }
                   11269: }
                   11270: 
1.575     albertel 11271: sub rndseed_64bit4 {
                   11272:     my ($symb,$courseid,$domain,$username)=@_;
                   11273:     {
                   11274: 	use integer;
                   11275: 	# strings need to be an even # of cahracters long, it it is odd the
                   11276:         # last characters gets thrown away
                   11277: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11278: 	my $symbseed=numval3($symb) << 10;
                   11279: 	my $namechck=unpack("%32S*",$username.' ');
                   11280: 	
                   11281: 	my $nameseed=numval3($username) << 21;
                   11282: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11283: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11284: 	
                   11285: 	my $num1=$symbchck+$symbseed+$namechck;
                   11286: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11287: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11288: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 11289: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11290: 	
1.575     albertel 11291: 	return "$num1:$num2";
                   11292:     }
                   11293: }
                   11294: 
1.675     albertel 11295: sub rndseed_64bit5 {
                   11296:     my ($symb,$courseid,$domain,$username)=@_;
                   11297:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   11298:     return "$num1:$num2";
                   11299: }
                   11300: 
1.366     albertel 11301: sub rndseed_CODE_64bit {
                   11302:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 11303:     {
1.366     albertel 11304: 	use integer;
1.443     albertel 11305: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 11306: 	my $symbseed=numval2($symb);
1.491     albertel 11307: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11308: 	my $CODEseed=numval(&getCODE());
1.443     albertel 11309: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 11310: 	my $num1=$symbseed+$CODEchck;
                   11311: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11312: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11313: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 11314: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11315: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 11316: 	return "$num1:$num2";
1.366     albertel 11317:     }
                   11318: }
                   11319: 
1.575     albertel 11320: sub rndseed_CODE_64bit4 {
                   11321:     my ($symb,$courseid,$domain,$username)=@_;
                   11322:     {
                   11323: 	use integer;
                   11324: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   11325: 	my $symbseed=numval3($symb);
                   11326: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11327: 	my $CODEseed=numval3(&getCODE());
                   11328: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11329: 	my $num1=$symbseed+$CODEchck;
                   11330: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11331: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11332: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 11333: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11334: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   11335: 	return "$num1:$num2";
                   11336:     }
                   11337: }
                   11338: 
1.675     albertel 11339: sub rndseed_CODE_64bit5 {
                   11340:     my ($symb,$courseid,$domain,$username)=@_;
                   11341:     my $code = &getCODE();
                   11342:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   11343:     return "$num1:$num2";
                   11344: }
                   11345: 
1.366     albertel 11346: sub setup_random_from_rndseed {
                   11347:     my ($rndseed)=@_;
1.503     albertel 11348:     if ($rndseed =~/([,:])/) {
                   11349: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 11350: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   11351:     } else {
                   11352: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 11353:     }
1.36      albertel 11354: }
                   11355: 
1.474     albertel 11356: sub latest_receipt_algorithm_id {
1.835     albertel 11357:     return 'receipt3';
1.474     albertel 11358: }
                   11359: 
1.480     www      11360: sub recunique {
                   11361:     my $fucourseid=shift;
                   11362:     my $unique;
1.835     albertel 11363:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   11364: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11365: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      11366:     } else {
                   11367: 	$unique=$perlvar{'lonReceipt'};
                   11368:     }
                   11369:     return unpack("%32C*",$unique);
                   11370: }
                   11371: 
                   11372: sub recprefix {
                   11373:     my $fucourseid=shift;
                   11374:     my $prefix;
1.835     albertel 11375:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   11376: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11377: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      11378:     } else {
                   11379: 	$prefix=$perlvar{'lonHostID'};
                   11380:     }
                   11381:     return unpack("%32C*",$prefix);
                   11382: }
                   11383: 
1.76      www      11384: sub ireceipt {
1.474     albertel 11385:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 11386: 
                   11387:     my $return =&recprefix($fucourseid).'-';
                   11388: 
                   11389:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   11390: 	$env{'request.state'} eq 'construct') {
                   11391: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   11392: 	return $return;
                   11393:     }
                   11394: 
1.76      www      11395:     my $cuname=unpack("%32C*",$funame);
                   11396:     my $cudom=unpack("%32C*",$fudom);
                   11397:     my $cucourseid=unpack("%32C*",$fucourseid);
                   11398:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      11399:     my $cunique=&recunique($fucourseid);
1.474     albertel 11400:     my $cpart=unpack("%32S*",$part);
1.835     albertel 11401:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   11402: 
1.790     albertel 11403: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 11404: 			       
                   11405: 	$return.= ($cunique%$cuname+
                   11406: 		   $cunique%$cudom+
                   11407: 		   $cusymb%$cuname+
                   11408: 		   $cusymb%$cudom+
                   11409: 		   $cucourseid%$cuname+
                   11410: 		   $cucourseid%$cudom+
                   11411: 		   $cpart%$cuname+
                   11412: 		   $cpart%$cudom);
                   11413:     } else {
                   11414: 	$return.= ($cunique%$cuname+
                   11415: 		   $cunique%$cudom+
                   11416: 		   $cusymb%$cuname+
                   11417: 		   $cusymb%$cudom+
                   11418: 		   $cucourseid%$cuname+
                   11419: 		   $cucourseid%$cudom);
                   11420:     }
                   11421:     return $return;
1.76      www      11422: }
                   11423: 
                   11424: sub receipt {
1.474     albertel 11425:     my ($part)=@_;
1.790     albertel 11426:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 11427:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      11428: }
1.260     ng       11429: 
1.790     albertel 11430: sub whichuser {
                   11431:     my ($passedsymb)=@_;
                   11432:     my ($symb,$courseid,$domain,$name,$publicuser);
                   11433:     if (defined($env{'form.grade_symb'})) {
                   11434: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   11435: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   11436: 	if (!$allowed &&
                   11437: 	    exists($env{'request.course.sec'}) &&
                   11438: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   11439: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   11440: 			      '/'.$env{'request.course.sec'});
                   11441: 	}
                   11442: 	if ($allowed) {
                   11443: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   11444: 	    $courseid=$tmp_courseid;
                   11445: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   11446: 	    ($name)=&get_env_multiple('form.grade_username');
                   11447: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   11448: 	}
                   11449:     }
                   11450:     if (!$passedsymb) {
                   11451: 	$symb=&symbread();
                   11452:     } else {
                   11453: 	$symb=$passedsymb;
                   11454:     }
                   11455:     $courseid=$env{'request.course.id'};
                   11456:     $domain=$env{'user.domain'};
                   11457:     $name=$env{'user.name'};
                   11458:     if ($name eq 'public' && $domain eq 'public') {
                   11459: 	if (!defined($env{'form.username'})) {
                   11460: 	    $env{'form.username'}.=time.rand(10000000);
                   11461: 	}
                   11462: 	$name.=$env{'form.username'};
                   11463:     }
                   11464:     return ($symb,$courseid,$domain,$name,$publicuser);
                   11465: 
                   11466: }
                   11467: 
1.36      albertel 11468: # ------------------------------------------------------------ Serves up a file
1.472     albertel 11469: # returns either the contents of the file or 
                   11470: # -1 if the file doesn't exist
1.481     raeburn  11471: #
                   11472: # if the target is a file that was uploaded via DOCS, 
                   11473: # a check will be made to see if a current copy exists on the local server,
                   11474: # if it does this will be served, otherwise a copy will be retrieved from
                   11475: # the home server for the course and stored in /home/httpd/html/userfiles on
                   11476: # the local server.   
1.472     albertel 11477: 
1.36      albertel 11478: sub getfile {
1.538     albertel 11479:     my ($file) = @_;
1.609     banghart 11480:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 11481:     &repcopy($file);
                   11482:     return &readfile($file);
                   11483: }
                   11484: 
                   11485: sub repcopy_userfile {
                   11486:     my ($file)=@_;
1.1142    raeburn  11487:     my $londocroot = $perlvar{'lonDocRoot'};
                   11488:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  11489:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 11490:     my ($cdom,$cnum,$filename) = 
1.811     albertel 11491: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 11492:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   11493:     if (-e "$file") {
1.828     www      11494: # we already have a local copy, check it out
1.538     albertel 11495: 	my @fileinfo = stat($file);
1.828     www      11496: 	my $rtncode;
                   11497: 	my $info;
1.538     albertel 11498: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 11499: 	if ($lwpresp ne 'ok') {
1.828     www      11500: # there is no such file anymore, even though we had a local copy
1.482     albertel 11501: 	    if ($rtncode eq '404') {
1.538     albertel 11502: 		unlink($file);
1.482     albertel 11503: 	    }
                   11504: 	    return -1;
                   11505: 	}
                   11506: 	if ($info < $fileinfo[9]) {
1.828     www      11507: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  11508: 	    return 'ok';
1.828     www      11509: 	} else {
                   11510: # the file is outdated, get rid of it
                   11511: 	    unlink($file);
1.482     albertel 11512: 	}
1.828     www      11513:     }
                   11514: # one way or the other, at this point, we don't have the file
                   11515: # construct the correct path for the file
                   11516:     my @parts = ($cdom,$cnum); 
                   11517:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   11518: 	push @parts, split(/\//,$1);
                   11519:     }
                   11520:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   11521:     foreach my $part (@parts) {
                   11522: 	$path .= '/'.$part;
                   11523: 	if (!-e $path) {
                   11524: 	    mkdir($path,0770);
1.482     albertel 11525: 	}
                   11526:     }
1.828     www      11527: # now the path exists for sure
                   11528: # get a user agent
                   11529:     my $ua=new LWP::UserAgent;
                   11530:     my $transferfile=$file.'.in.transfer';
                   11531: # FIXME: this should flock
                   11532:     if (-e $transferfile) { return 'ok'; }
                   11533:     my $request;
                   11534:     $uri=~s/^\///;
1.980     raeburn  11535:     my $homeserver = &homeserver($cnum,$cdom);
                   11536:     my $protocol = $protocol{$homeserver};
                   11537:     $protocol = 'http' if ($protocol ne 'https');
                   11538:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      11539:     my $response=$ua->request($request,$transferfile);
                   11540: # did it work?
                   11541:     if ($response->is_error()) {
                   11542: 	unlink($transferfile);
                   11543: 	&logthis("Userfile repcopy failed for $uri");
                   11544: 	return -1;
                   11545:     }
                   11546: # worked, rename the transfer file
                   11547:     rename($transferfile,$file);
1.607     raeburn  11548:     return 'ok';
1.481     raeburn  11549: }
                   11550: 
1.517     albertel 11551: sub tokenwrapper {
                   11552:     my $uri=shift;
1.980     raeburn  11553:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 11554:     $uri=~s|^/||;
1.620     albertel 11555:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 11556:     my $token=$1;
1.552     albertel 11557:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   11558:     if ($udom && $uname && $file) {
                   11559: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  11560:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  11561:         my $homeserver = &homeserver($uname,$udom);
                   11562:         my $protocol = $protocol{$homeserver};
                   11563:         $protocol = 'http' if ($protocol ne 'https');
                   11564:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 11565:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   11566:                                '&tokenissued='.$perlvar{'lonHostID'};
                   11567:     } else {
                   11568:         return '/adm/notfound.html';
                   11569:     }
                   11570: }
                   11571: 
1.828     www      11572: # call with reqtype HEAD: get last modification time
                   11573: # call with reqtype GET: get the file contents
                   11574: # Do not call this with reqtype GET for large files! It loads everything into memory
                   11575: #
1.481     raeburn  11576: sub getuploaded {
                   11577:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   11578:     $uri=~s/^\///;
1.980     raeburn  11579:     my $homeserver = &homeserver($cnum,$cdom);
                   11580:     my $protocol = $protocol{$homeserver};
                   11581:     $protocol = 'http' if ($protocol ne 'https');
                   11582:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  11583:     my $ua=new LWP::UserAgent;
                   11584:     my $request=new HTTP::Request($reqtype,$uri);
                   11585:     my $response=$ua->request($request);
                   11586:     $$rtncode = $response->code;
1.482     albertel 11587:     if (! $response->is_success()) {
                   11588: 	return 'failed';
                   11589:     }      
                   11590:     if ($reqtype eq 'HEAD') {
1.486     www      11591: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 11592:     } elsif ($reqtype eq 'GET') {
                   11593: 	$$info = $response->content;
1.472     albertel 11594:     }
1.482     albertel 11595:     return 'ok';
1.36      albertel 11596: }
                   11597: 
1.481     raeburn  11598: sub readfile {
                   11599:     my $file = shift;
                   11600:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   11601:     my $fh;
                   11602:     open($fh,"<$file");
                   11603:     my $a='';
1.800     albertel 11604:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  11605:     return $a;
                   11606: }
                   11607: 
1.36      albertel 11608: sub filelocation {
1.590     banghart 11609:     my ($dir,$file) = @_;
                   11610:     my $location;
                   11611:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 11612: 
                   11613:     if ($file =~ m-^/adm/-) {
                   11614: 	$file=~s-^/adm/wrapper/-/-;
                   11615: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   11616:     }
1.882     albertel 11617: 
1.1139    www      11618:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  11619:         $location = $file;
1.609     banghart 11620:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 11621:         my ($udom,$uname,$filename)=
1.811     albertel 11622:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 11623:         my $home=&homeserver($uname,$udom);
                   11624:         my $is_me=0;
                   11625:         my @ids=&current_machine_ids();
                   11626:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   11627:         if ($is_me) {
1.1117    foxr     11628:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 11629:         } else {
                   11630:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   11631:   	      $udom.'/'.$uname.'/'.$filename;
                   11632:         }
1.882     albertel 11633:     } elsif ($file =~ m-^/adm/-) {
                   11634: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 11635:     } else {
                   11636:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      11637:         $file=~s:^/(res|priv)/:/:;
                   11638:         my $space=$1;
1.590     banghart 11639:         if ( !( $file =~ m:^/:) ) {
                   11640:             $location = $dir. '/'.$file;
                   11641:         } else {
1.1142    raeburn  11642:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 11643:         }
1.59      albertel 11644:     }
1.590     banghart 11645:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 11646:     while ($location=~m{/\.\./}) {
                   11647: 	if ($location =~ m{/[^/]+/\.\./}) {
                   11648: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   11649: 	} else {
                   11650: 	    $location=~ s{/\.\./}{/}g;
                   11651: 	}
                   11652:     } #remove dir/..
1.590     banghart 11653:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   11654:     return $location;
1.46      www      11655: }
1.36      albertel 11656: 
1.46      www      11657: sub hreflocation {
                   11658:     my ($dir,$file)=@_;
1.980     raeburn  11659:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 11660: 	$file=filelocation($dir,$file);
1.700     albertel 11661:     } elsif ($file=~m-^/adm/-) {
                   11662: 	$file=~s-^/adm/wrapper/-/-;
                   11663: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 11664:     }
                   11665:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   11666: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   11667:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  11668: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   11669: 	        {/uploaded/$1/$2/}x;
1.46      www      11670:     }
1.913     albertel 11671:     if ($file=~ m{^/userfiles/}) {
                   11672: 	$file =~ s{^/userfiles/}{/uploaded/};
                   11673:     }
1.462     albertel 11674:     return $file;
1.465     albertel 11675: }
                   11676: 
1.1139    www      11677: 
                   11678: 
                   11679: 
                   11680: 
1.465     albertel 11681: sub current_machine_domains {
1.853     albertel 11682:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   11683: }
                   11684: 
                   11685: sub machine_domains {
                   11686:     my ($hostname) = @_;
1.465     albertel 11687:     my @domains;
1.838     albertel 11688:     my %hostname = &all_hostnames();
1.465     albertel 11689:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  11690: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 11691: 	if ($hostname eq $name) {
1.844     albertel 11692: 	    push(@domains,&host_domain($id));
1.465     albertel 11693: 	}
                   11694:     }
                   11695:     return @domains;
                   11696: }
                   11697: 
                   11698: sub current_machine_ids {
1.853     albertel 11699:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   11700: }
                   11701: 
                   11702: sub machine_ids {
                   11703:     my ($hostname) = @_;
                   11704:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 11705:     my @ids;
1.888     albertel 11706:     my %name_to_host = &all_names();
1.889     albertel 11707:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   11708: 	return @{ $name_to_host{$hostname} };
                   11709:     }
                   11710:     return;
1.31      www      11711: }
                   11712: 
1.824     raeburn  11713: sub additional_machine_domains {
                   11714:     my @domains;
                   11715:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   11716:     while( my $line = <$fh>) {
                   11717:         $line =~ s/\s//g;
                   11718:         push(@domains,$line);
                   11719:     }
                   11720:     return @domains;
                   11721: }
                   11722: 
                   11723: sub default_login_domain {
                   11724:     my $domain = $perlvar{'lonDefDomain'};
                   11725:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   11726:     foreach my $posdom (&current_machine_domains(),
                   11727:                         &additional_machine_domains()) {
                   11728:         if (lc($posdom) eq lc($testdomain)) {
                   11729:             $domain=$posdom;
                   11730:             last;
                   11731:         }
                   11732:     }
                   11733:     return $domain;
                   11734: }
                   11735: 
1.31      www      11736: # ------------------------------------------------------------- Declutters URLs
                   11737: 
                   11738: sub declutter {
                   11739:     my $thisfn=shift;
1.569     albertel 11740:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 11741:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      11742:     $thisfn=~s/^\///;
1.697     albertel 11743:     $thisfn=~s|^adm/wrapper/||;
                   11744:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      11745:     $thisfn=~s/^res\///;
1.1172    bisitz   11746:     $thisfn=~s/^priv\///;
1.1032    raeburn  11747:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   11748:         $thisfn=~s/\?.+$//;
                   11749:     }
1.268     www      11750:     return $thisfn;
                   11751: }
                   11752: 
                   11753: # ------------------------------------------------------------- Clutter up URLs
                   11754: 
                   11755: sub clutter {
                   11756:     my $thisfn='/'.&declutter(shift);
1.887     albertel 11757:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 11758: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      11759:        $thisfn='/res'.$thisfn; 
                   11760:     }
1.1031    raeburn  11761:     if ($thisfn !~m|^/adm|) {
                   11762: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 11763: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 11764: 	} else {
                   11765: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   11766: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 11767: 	    if ($embstyle eq 'ssi'
                   11768: 		|| ($embstyle eq 'hdn')
                   11769: 		|| ($embstyle eq 'rat')
                   11770: 		|| ($embstyle eq 'prv')
                   11771: 		|| ($embstyle eq 'ign')) {
                   11772: 		#do nothing with these
                   11773: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 11774: 		|| ($embstyle eq 'emb')
                   11775: 		|| ($embstyle eq 'wrp')) {
                   11776: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 11777: 	    } elsif ($embstyle eq 'unk'
                   11778: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 11779: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 11780: 	    } else {
1.718     www      11781: #		&logthis("Got a blank emb style");
1.695     albertel 11782: 	    }
1.694     albertel 11783: 	}
                   11784:     }
1.31      www      11785:     return $thisfn;
1.12      www      11786: }
                   11787: 
1.787     albertel 11788: sub clutter_with_no_wrapper {
                   11789:     my $uri = &clutter(shift);
                   11790:     if ($uri =~ m-^/adm/-) {
                   11791: 	$uri =~ s-^/adm/wrapper/-/-;
                   11792: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   11793:     }
                   11794:     return $uri;
                   11795: }
                   11796: 
1.557     albertel 11797: sub freeze_escape {
                   11798:     my ($value)=@_;
                   11799:     if (ref($value)) {
                   11800: 	$value=&nfreeze($value);
                   11801: 	return '__FROZEN__'.&escape($value);
                   11802:     }
                   11803:     return &escape($value);
                   11804: }
                   11805: 
1.11      www      11806: 
1.557     albertel 11807: sub thaw_unescape {
                   11808:     my ($value)=@_;
                   11809:     if ($value =~ /^__FROZEN__/) {
                   11810: 	substr($value,0,10,undef);
                   11811: 	$value=&unescape($value);
                   11812: 	return &thaw($value);
                   11813:     }
                   11814:     return &unescape($value);
                   11815: }
                   11816: 
1.436     albertel 11817: sub correct_line_ends {
                   11818:     my ($result)=@_;
                   11819:     $$result =~s/\r\n/\n/mg;
                   11820:     $$result =~s/\r/\n/mg;
1.415     albertel 11821: }
1.1       albertel 11822: # ================================================================ Main Program
                   11823: 
1.184     www      11824: sub goodbye {
1.204     albertel 11825:    &logthis("Starting Shut down");
1.443     albertel 11826: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 11827:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 11828: #converted
1.599     albertel 11829: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 11830:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   11831: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   11832: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 11833: #1.1 only
1.870     albertel 11834: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   11835: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   11836: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   11837: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   11838:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 11839:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   11840:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      11841:    &flushcourselogs();
                   11842:    &logthis("Shutting down");
                   11843: }
                   11844: 
1.852     albertel 11845: sub get_dns {
1.1172.2.17  raeburn  11846:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 11847:     if (!$ignore_cache) {
                   11848: 	my ($content,$cached)=
                   11849: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   11850: 	if ($cached) {
1.1172.2.17  raeburn  11851: 	    &$func($content,$hashref);
1.869     albertel 11852: 	    return;
                   11853: 	}
                   11854:     }
                   11855: 
                   11856:     my %alldns;
1.852     albertel 11857:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11858:     foreach my $dns (<$config>) {
                   11859: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  11860:         my $line = $1;
                   11861:         my ($host,$protocol) = split(/:/,$line);
                   11862:         if ($protocol ne 'https') {
                   11863:             $protocol = 'http';
                   11864:         }
                   11865: 	$alldns{$host} = $protocol;
1.869     albertel 11866:     }
                   11867:     while (%alldns) {
                   11868: 	my ($dns) = keys(%alldns);
1.852     albertel 11869: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  11870:         $ua->timeout(30);
1.979     raeburn  11871: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 11872: 	my $response=$ua->request($request);
1.979     raeburn  11873:         delete($alldns{$dns});
1.852     albertel 11874: 	next if ($response->is_error());
                   11875: 	my @content = split("\n",$response->content);
1.1172.2.17  raeburn  11876:         unless ($nocache) {
1.1172.2.23  raeburn  11877: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  11878:         }
                   11879: 	&$func(\@content,$hashref);
1.869     albertel 11880: 	return;
1.852     albertel 11881:     }
                   11882:     close($config);
1.871     albertel 11883:     my $which = (split('/',$url))[3];
                   11884:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   11885:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 11886:     my @content = <$config>;
1.1172.2.17  raeburn  11887:     &$func(\@content,$hashref);
                   11888:     return;
                   11889: }
                   11890: 
                   11891: # ------------------------------------------------------Get DNS checksums file
                   11892: sub parse_dns_checksums_tab {
                   11893:     my ($lines,$hashref) = @_;
                   11894:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
                   11895:     my $loncaparev = &get_server_loncaparev($machine_dom);
                   11896:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   11897:     my (%chksum,%revnum);
                   11898:     if (ref($lines) eq 'ARRAY') {
                   11899:         chomp(@{$lines});
1.1172.2.34  raeburn  11900:         my $version = shift(@{$lines});
                   11901:         if ($version eq $release) {
1.1172.2.17  raeburn  11902:             foreach my $line (@{$lines}) {
1.1172.2.34  raeburn  11903:                 my ($file,$version,$shasum) = split(/,/,$line);
                   11904:                 $chksum{$file} = $shasum;
                   11905:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  11906:             }
                   11907:             if (ref($hashref) eq 'HASH') {
                   11908:                 %{$hashref} = (
                   11909:                                 sums     => \%chksum,
                   11910:                                 versions => \%revnum,
                   11911:                               );
                   11912:             }
                   11913:         }
                   11914:     }
1.869     albertel 11915:     return;
1.852     albertel 11916: }
1.1172.2.17  raeburn  11917: 
                   11918: sub fetch_dns_checksums {
                   11919:     my %checksums;
1.1172.2.34  raeburn  11920:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48! raeburn  11921:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34  raeburn  11922:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   11923:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  11924:              \%checksums);
                   11925:     return \%checksums;
                   11926: }
                   11927: 
1.327     albertel 11928: # ------------------------------------------------------------ Read domain file
                   11929: {
1.852     albertel 11930:     my $loaded;
1.846     albertel 11931:     my %domain;
                   11932: 
1.852     albertel 11933:     sub parse_domain_tab {
                   11934: 	my ($lines) = @_;
                   11935: 	foreach my $line (@$lines) {
                   11936: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      11937: 
1.846     albertel 11938: 	    chomp($line);
1.852     albertel 11939: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 11940: 	    my %this_domain;
                   11941: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   11942: 			       'lang_def', 'city', 'longi', 'lati',
                   11943: 			       'primary') {
                   11944: 		$this_domain{$field} = shift(@elements);
                   11945: 	    }
                   11946: 	    $domain{$name} = \%this_domain;
1.852     albertel 11947: 	}
                   11948:     }
1.864     albertel 11949: 
                   11950:     sub reset_domain_info {
                   11951: 	undef($loaded);
                   11952: 	undef(%domain);
                   11953:     }
                   11954: 
1.852     albertel 11955:     sub load_domain_tab {
1.869     albertel 11956: 	my ($ignore_cache) = @_;
                   11957: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 11958: 	my $fh;
                   11959: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   11960: 	    my @lines = <$fh>;
                   11961: 	    &parse_domain_tab(\@lines);
1.448     albertel 11962: 	}
1.852     albertel 11963: 	close($fh);
                   11964: 	$loaded = 1;
1.327     albertel 11965:     }
1.846     albertel 11966: 
                   11967:     sub domain {
1.852     albertel 11968: 	&load_domain_tab() if (!$loaded);
                   11969: 
1.846     albertel 11970: 	my ($name,$what) = @_;
                   11971: 	return if ( !exists($domain{$name}) );
                   11972: 
                   11973: 	if (!$what) {
                   11974: 	    return $domain{$name}{'description'};
                   11975: 	}
                   11976: 	return $domain{$name}{$what};
                   11977:     }
1.974     raeburn  11978: 
                   11979:     sub domain_info {
                   11980:         &load_domain_tab() if (!$loaded);
                   11981:         return %domain;
                   11982:     }
                   11983: 
1.327     albertel 11984: }
                   11985: 
                   11986: 
1.1       albertel 11987: # ------------------------------------------------------------- Read hosts file
                   11988: {
1.838     albertel 11989:     my %hostname;
1.844     albertel 11990:     my %hostdom;
1.845     albertel 11991:     my %libserv;
1.852     albertel 11992:     my $loaded;
1.888     albertel 11993:     my %name_to_host;
1.1074    raeburn  11994:     my %internetdom;
1.1107    raeburn  11995:     my %LC_dns_serv;
1.852     albertel 11996: 
                   11997:     sub parse_hosts_tab {
                   11998: 	my ($file) = @_;
                   11999: 	foreach my $configline (@$file) {
                   12000: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  12001:             chomp($configline);
                   12002: 	    if ($configline =~ /^\^/) {
                   12003:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   12004:                     $LC_dns_serv{$1} = 1;
                   12005:                 }
                   12006:                 next;
                   12007:             }
1.1074    raeburn  12008: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 12009: 	    $name=~s/\s//g;
                   12010: 	    if ($id && $domain && $role && $name) {
                   12011: 		$hostname{$id}=$name;
1.888     albertel 12012: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 12013: 		$hostdom{$id}=$domain;
                   12014: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  12015:                 if (defined($protocol)) {
                   12016:                     if ($protocol eq 'https') {
                   12017:                         $protocol{$id} = $protocol;
                   12018:                     } else {
                   12019:                         $protocol{$id} = 'http'; 
                   12020:                     }
1.968     raeburn  12021:                 } else {
1.969     raeburn  12022:                     $protocol{$id} = 'http';
1.968     raeburn  12023:                 }
1.1074    raeburn  12024:                 if (defined($intdom)) {
                   12025:                     $internetdom{$id} = $intdom;
                   12026:                 }
1.852     albertel 12027: 	    }
                   12028: 	}
                   12029:     }
1.864     albertel 12030:     
                   12031:     sub reset_hosts_info {
1.897     albertel 12032: 	&purge_remembered();
1.864     albertel 12033: 	&reset_domain_info();
                   12034: 	&reset_hosts_ip_info();
1.892     albertel 12035: 	undef(%name_to_host);
1.864     albertel 12036: 	undef(%hostname);
                   12037: 	undef(%hostdom);
                   12038: 	undef(%libserv);
                   12039: 	undef($loaded);
                   12040:     }
1.1       albertel 12041: 
1.852     albertel 12042:     sub load_hosts_tab {
1.869     albertel 12043: 	my ($ignore_cache) = @_;
                   12044: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 12045: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   12046: 	my @config = <$config>;
                   12047: 	&parse_hosts_tab(\@config);
                   12048: 	close($config);
                   12049: 	$loaded=1;
1.1       albertel 12050:     }
1.852     albertel 12051: 
1.838     albertel 12052:     sub hostname {
1.852     albertel 12053: 	&load_hosts_tab() if (!$loaded);
                   12054: 
1.838     albertel 12055: 	my ($lonid) = @_;
                   12056: 	return $hostname{$lonid};
                   12057:     }
1.845     albertel 12058: 
1.838     albertel 12059:     sub all_hostnames {
1.852     albertel 12060: 	&load_hosts_tab() if (!$loaded);
                   12061: 
1.838     albertel 12062: 	return %hostname;
                   12063:     }
1.845     albertel 12064: 
1.888     albertel 12065:     sub all_names {
                   12066: 	&load_hosts_tab() if (!$loaded);
                   12067: 
                   12068: 	return %name_to_host;
                   12069:     }
                   12070: 
1.974     raeburn  12071:     sub all_host_domain {
                   12072:         &load_hosts_tab() if (!$loaded);
                   12073:         return %hostdom;
                   12074:     }
                   12075: 
1.845     albertel 12076:     sub is_library {
1.852     albertel 12077: 	&load_hosts_tab() if (!$loaded);
                   12078: 
1.845     albertel 12079: 	return exists($libserv{$_[0]});
                   12080:     }
                   12081: 
                   12082:     sub all_library {
1.852     albertel 12083: 	&load_hosts_tab() if (!$loaded);
                   12084: 
1.845     albertel 12085: 	return %libserv;
                   12086:     }
                   12087: 
1.1062    droeschl 12088:     sub unique_library {
                   12089: 	#2x reverse removes all hostnames that appear more than once
                   12090:         my %unique = reverse &all_library();
                   12091:         return reverse %unique;
                   12092:     }
                   12093: 
1.841     albertel 12094:     sub get_servers {
1.852     albertel 12095: 	&load_hosts_tab() if (!$loaded);
                   12096: 
1.841     albertel 12097: 	my ($domain,$type) = @_;
                   12098: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   12099: 	                                          : %hostname;
                   12100: 	my %result;
1.842     albertel 12101: 	if (ref($domain) eq 'ARRAY') {
                   12102: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 12103: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 12104: 		    $result{$host} = $hostname;
                   12105: 		}
                   12106: 	    }
                   12107: 	} else {
                   12108: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   12109: 		if ($hostdom{$host} eq $domain) {
                   12110: 		    $result{$host} = $hostname;
                   12111: 		}
1.841     albertel 12112: 	    }
                   12113: 	}
                   12114: 	return %result;
                   12115:     }
1.845     albertel 12116: 
1.1062    droeschl 12117:     sub get_unique_servers {
                   12118:         my %unique = reverse &get_servers(@_);
                   12119: 	return reverse %unique;
                   12120:     }
                   12121: 
1.844     albertel 12122:     sub host_domain {
1.852     albertel 12123: 	&load_hosts_tab() if (!$loaded);
                   12124: 
1.844     albertel 12125: 	my ($lonid) = @_;
                   12126: 	return $hostdom{$lonid};
                   12127:     }
                   12128: 
1.841     albertel 12129:     sub all_domains {
1.852     albertel 12130: 	&load_hosts_tab() if (!$loaded);
                   12131: 
1.841     albertel 12132: 	my %seen;
                   12133: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   12134: 	return @uniq;
                   12135:     }
1.1074    raeburn  12136: 
                   12137:     sub internet_dom {
                   12138:         &load_hosts_tab() if (!$loaded);
                   12139: 
                   12140:         my ($lonid) = @_;
                   12141:         return $internetdom{$lonid};
                   12142:     }
1.1107    raeburn  12143: 
                   12144:     sub is_LC_dns {
                   12145:         &load_hosts_tab() if (!$loaded);
                   12146: 
                   12147:         my ($hostname) = @_;
                   12148:         return exists($LC_dns_serv{$hostname});
                   12149:     }
                   12150: 
1.1       albertel 12151: }
                   12152: 
1.847     albertel 12153: { 
                   12154:     my %iphost;
1.856     albertel 12155:     my %name_to_ip;
                   12156:     my %lonid_to_ip;
1.869     albertel 12157: 
1.847     albertel 12158:     sub get_hosts_from_ip {
                   12159: 	my ($ip) = @_;
                   12160: 	my %iphosts = &get_iphost();
                   12161: 	if (ref($iphosts{$ip})) {
                   12162: 	    return @{$iphosts{$ip}};
                   12163: 	}
                   12164: 	return;
1.839     albertel 12165:     }
1.864     albertel 12166:     
                   12167:     sub reset_hosts_ip_info {
                   12168: 	undef(%iphost);
                   12169: 	undef(%name_to_ip);
                   12170: 	undef(%lonid_to_ip);
                   12171:     }
1.856     albertel 12172: 
                   12173:     sub get_host_ip {
                   12174: 	my ($lonid) = @_;
                   12175: 	if (exists($lonid_to_ip{$lonid})) {
                   12176: 	    return $lonid_to_ip{$lonid};
                   12177: 	}
                   12178: 	my $name=&hostname($lonid);
                   12179:    	my $ip = gethostbyname($name);
                   12180: 	return if (!$ip || length($ip) ne 4);
                   12181: 	$ip=inet_ntoa($ip);
                   12182: 	$name_to_ip{$name}   = $ip;
                   12183: 	$lonid_to_ip{$lonid} = $ip;
                   12184: 	return $ip;
                   12185:     }
1.847     albertel 12186:     
                   12187:     sub get_iphost {
1.869     albertel 12188: 	my ($ignore_cache) = @_;
1.894     albertel 12189: 
1.869     albertel 12190: 	if (!$ignore_cache) {
                   12191: 	    if (%iphost) {
                   12192: 		return %iphost;
                   12193: 	    }
                   12194: 	    my ($ip_info,$cached)=
                   12195: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   12196: 	    if ($cached) {
                   12197: 		%iphost      = %{$ip_info->[0]};
                   12198: 		%name_to_ip  = %{$ip_info->[1]};
                   12199: 		%lonid_to_ip = %{$ip_info->[2]};
                   12200: 		return %iphost;
                   12201: 	    }
                   12202: 	}
1.894     albertel 12203: 
                   12204: 	# get yesterday's info for fallback
                   12205: 	my %old_name_to_ip;
                   12206: 	my ($ip_info,$cached)=
                   12207: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   12208: 	if ($cached) {
                   12209: 	    %old_name_to_ip = %{$ip_info->[1]};
                   12210: 	}
                   12211: 
1.888     albertel 12212: 	my %name_to_host = &all_names();
                   12213: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 12214: 	    my $ip;
                   12215: 	    if (!exists($name_to_ip{$name})) {
                   12216: 		$ip = gethostbyname($name);
                   12217: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 12218: 		    if (defined($old_name_to_ip{$name})) {
                   12219: 			$ip = $old_name_to_ip{$name};
                   12220: 			&logthis("Can't find $name defaulting to old $ip");
                   12221: 		    } else {
                   12222: 			&logthis("Name $name no IP found");
                   12223: 			next;
                   12224: 		    }
                   12225: 		} else {
                   12226: 		    $ip=inet_ntoa($ip);
1.847     albertel 12227: 		}
                   12228: 		$name_to_ip{$name} = $ip;
                   12229: 	    } else {
                   12230: 		$ip = $name_to_ip{$name};
1.653     albertel 12231: 	    }
1.888     albertel 12232: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   12233: 		$lonid_to_ip{$id} = $ip;
                   12234: 	    }
                   12235: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 12236: 	}
1.1172.2.23  raeburn  12237: 	&do_cache_new('iphost','iphost',
                   12238: 		      [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   12239: 		      48*60*60);
1.869     albertel 12240: 
1.847     albertel 12241: 	return %iphost;
1.598     albertel 12242:     }
                   12243: 
1.992     raeburn  12244:     #
                   12245:     #  Given a DNS returns the loncapa host name for that DNS 
                   12246:     # 
                   12247:     sub host_from_dns {
                   12248:         my ($dns) = @_;
                   12249:         my @hosts;
                   12250:         my $ip;
                   12251: 
1.993     raeburn  12252:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  12253:             $ip = $name_to_ip{$dns};
                   12254:         }
                   12255:         if (!$ip) {
                   12256:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   12257:             if (length($ip) == 4) { 
                   12258: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   12259:             }
                   12260:         }
                   12261:         if ($ip) {
                   12262: 	    @hosts = get_hosts_from_ip($ip);
                   12263: 	    return $hosts[0];
                   12264:         }
                   12265:         return undef;
1.986     foxr     12266:     }
1.992     raeburn  12267: 
1.1074    raeburn  12268:     sub get_internet_names {
                   12269:         my ($lonid) = @_;
                   12270:         return if ($lonid eq '');
                   12271:         my ($idnref,$cached)=
                   12272:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   12273:         if ($cached) {
                   12274:             return $idnref;
                   12275:         }
                   12276:         my $ip = &get_host_ip($lonid);
                   12277:         my @hosts = &get_hosts_from_ip($ip);
                   12278:         my %iphost = &get_iphost();
                   12279:         my (@idns,%seen);
                   12280:         foreach my $id (@hosts) {
                   12281:             my $dom = &host_domain($id);
                   12282:             my $prim_id = &domain($dom,'primary');
                   12283:             my $prim_ip = &get_host_ip($prim_id);
                   12284:             next if ($seen{$prim_ip});
                   12285:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   12286:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   12287:                     my $intdom = &internet_dom($id);
                   12288:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   12289:                         push(@idns,$intdom);
                   12290:                     }
                   12291:                 }
                   12292:             }
                   12293:             $seen{$prim_ip} = 1;
                   12294:         }
1.1172.2.23  raeburn  12295:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  12296:     }
                   12297: 
1.986     foxr     12298: }
                   12299: 
1.1079    raeburn  12300: sub all_loncaparevs {
1.1172.2.39  raeburn  12301:     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  12302: }
                   12303: 
1.1172.2.27  raeburn  12304: # ------------------------------------------------------- Read loncaparev table
                   12305: {
                   12306:     sub load_loncaparevs {
                   12307:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   12308:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   12309:                 while (my $configline=<$config>) {
                   12310:                     chomp($configline);
                   12311:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   12312:                     $loncaparevs{$hostid}=$loncaparev;
                   12313:                 }
                   12314:                 close($config);
                   12315:             }
                   12316:         }
                   12317:     }
                   12318: }
                   12319: 
                   12320: # ----------------------------------------------------- Read serverhostID table
                   12321: {
                   12322:     sub load_serverhomeIDs {
                   12323:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   12324:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   12325:                 while (my $configline=<$config>) {
                   12326:                     chomp($configline);
                   12327:                     my ($name,$id)=split(/:/,$configline);
                   12328:                     $serverhomeIDs{$name}=$id;
                   12329:                 }
                   12330:                 close($config);
                   12331:             }
                   12332:         }
                   12333:     }
                   12334: }
                   12335: 
                   12336: 
1.862     albertel 12337: BEGIN {
                   12338: 
                   12339: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   12340:     unless ($readit) {
                   12341: {
                   12342:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   12343:     %perlvar = (%perlvar,%{$configvars});
                   12344: }
                   12345: 
                   12346: 
1.1       albertel 12347: # ------------------------------------------------------ Read spare server file
                   12348: {
1.448     albertel 12349:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 12350: 
                   12351:     while (my $configline=<$config>) {
                   12352:        chomp($configline);
1.284     matthew  12353:        if ($configline) {
1.784     albertel 12354: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 12355: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 12356: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 12357:        }
                   12358:     }
1.448     albertel 12359:     close($config);
1.1       albertel 12360: }
1.11      www      12361: # ------------------------------------------------------------ Read permissions
                   12362: {
1.448     albertel 12363:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      12364: 
                   12365:     while (my $configline=<$config>) {
1.448     albertel 12366: 	chomp($configline);
                   12367: 	if ($configline) {
                   12368: 	    my ($role,$perm)=split(/ /,$configline);
                   12369: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   12370: 	}
1.11      www      12371:     }
1.448     albertel 12372:     close($config);
1.11      www      12373: }
                   12374: 
                   12375: # -------------------------------------------- Read plain texts for permissions
                   12376: {
1.448     albertel 12377:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      12378: 
                   12379:     while (my $configline=<$config>) {
1.448     albertel 12380: 	chomp($configline);
                   12381: 	if ($configline) {
1.742     raeburn  12382: 	    my ($short,@plain)=split(/:/,$configline);
                   12383:             %{$prp{$short}} = ();
                   12384: 	    if (@plain > 0) {
                   12385:                 $prp{$short}{'std'} = $plain[0];
                   12386:                 for (my $i=1; $i<@plain; $i++) {
                   12387:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   12388:                 }
                   12389:             }
1.448     albertel 12390: 	}
1.135     www      12391:     }
1.448     albertel 12392:     close($config);
1.135     www      12393: }
                   12394: 
                   12395: # ---------------------------------------------------------- Read package table
                   12396: {
1.448     albertel 12397:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      12398: 
                   12399:     while (my $configline=<$config>) {
1.483     albertel 12400: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 12401: 	chomp($configline);
                   12402: 	my ($short,$plain)=split(/:/,$configline);
                   12403: 	my ($pack,$name)=split(/\&/,$short);
                   12404: 	if ($plain ne '') {
                   12405: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   12406: 	    $packagetab{$short}=$plain; 
                   12407: 	}
1.11      www      12408:     }
1.448     albertel 12409:     close($config);
1.329     matthew  12410: }
                   12411: 
1.1172.2.27  raeburn  12412: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  12413: 
1.1172.2.27  raeburn  12414: &load_loncaparevs();
                   12415: 
                   12416: # ------------------------------------------------------- Read serverhostID table
                   12417: 
                   12418: &load_serverhomeIDs();
1.1074    raeburn  12419: 
1.1172.2.27  raeburn  12420: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  12421: {
                   12422:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   12423:     if (-e $file) {
                   12424:         my $parser = HTML::LCParser->new($file);
                   12425:         while (my $token = $parser->get_token()) {
                   12426:             if ($token->[0] eq 'S') {
                   12427:                 my $item = $token->[1];
                   12428:                 my $name = $token->[2]{'name'};
                   12429:                 my $value = $token->[2]{'value'};
                   12430:                 if ($item ne '' && $name ne '' && $value ne '') {
                   12431:                     my $release = $parser->get_text();
                   12432:                     $release =~ s/(^\s*|\s*$ )//gx;
                   12433:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   12434:                 }
                   12435:             }
                   12436:         }
                   12437:     }
1.1073    raeburn  12438: }
                   12439: 
1.1138    raeburn  12440: # ---------------------------------------------------------- Read managers table
                   12441: {
                   12442:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   12443:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   12444:             while (my $configline=<$config>) {
                   12445:                 chomp($configline);
                   12446:                 next if ($configline =~ /^\#/);
                   12447:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   12448:                     $managerstab{$configline} = 1;
                   12449:                 }
                   12450:             }
                   12451:             close($config);
                   12452:         }
                   12453:     }
                   12454: }
                   12455: 
1.329     matthew  12456: # ------------- set up temporary directory
                   12457: {
1.1117    foxr     12458:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  12459: 
1.11      www      12460: }
                   12461: 
1.794     albertel 12462: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   12463: 				'compress_threshold'=> 20_000,
                   12464:  			        });
1.185     www      12465: 
1.281     www      12466: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      12467: $dumpcount=0;
1.958     www      12468: $locknum=0;
1.22      www      12469: 
1.163     harris41 12470: &logtouch();
1.672     albertel 12471: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      12472: $readit=1;
1.564     albertel 12473:     {
                   12474: 	use integer;
                   12475: 	my $test=(2**32)+1;
1.568     albertel 12476: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 12477: 	&logthis(" Detected 64bit platform ($_64bit)");
                   12478:     }
1.195     www      12479: }
1.1       albertel 12480: }
1.179     www      12481: 
1.1       albertel 12482: 1;
1.191     harris41 12483: __END__
                   12484: 
1.243     albertel 12485: =pod
                   12486: 
1.191     harris41 12487: =head1 NAME
                   12488: 
1.243     albertel 12489: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 12490: 
                   12491: =head1 SYNOPSIS
                   12492: 
1.243     albertel 12493: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 12494: 
                   12495:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   12496: 
1.243     albertel 12497: Common parameters:
                   12498: 
                   12499: =over 4
                   12500: 
                   12501: =item *
                   12502: 
                   12503: $uname : an internal username (if $cname expecting a course Id specifically)
                   12504: 
                   12505: =item *
                   12506: 
                   12507: $udom : a domain (if $cdom expecting a course's domain specifically)
                   12508: 
                   12509: =item *
                   12510: 
                   12511: $symb : a resource instance identifier
                   12512: 
                   12513: =item *
                   12514: 
                   12515: $namespace : the name of a .db file that contains the data needed or
                   12516: being set.
                   12517: 
                   12518: =back
                   12519: 
1.394     bowersj2 12520: =head1 OVERVIEW
1.191     harris41 12521: 
1.394     bowersj2 12522: lonnet provides subroutines which interact with the
                   12523: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   12524: about classes, users, and resources.
1.243     albertel 12525: 
                   12526: For many of these objects you can also use this to store data about
                   12527: them or modify them in various ways.
1.191     harris41 12528: 
1.394     bowersj2 12529: =head2 Symbs
1.191     harris41 12530: 
1.394     bowersj2 12531: To identify a specific instance of a resource, LON-CAPA uses symbols
                   12532: or "symbs"X<symb>. These identifiers are built from the URL of the
                   12533: map, the resource number of the resource in the map, and the URL of
                   12534: the resource itself. The latter is somewhat redundant, but might help
                   12535: if maps change.
                   12536: 
                   12537: An example is
                   12538: 
                   12539:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   12540: 
                   12541: The respective map entry is
                   12542: 
                   12543:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   12544:   title="Problem 2">
                   12545:  </resource>
                   12546: 
                   12547: Symbs are used by the random number generator, as well as to store and
                   12548: restore data specific to a certain instance of for example a problem.
                   12549: 
                   12550: =head2 Storing And Retrieving Data
                   12551: 
                   12552: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   12553: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   12554: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   12555: is is the non-critical message twin of cstore. These functions are for
                   12556: handlers to store a perl hash to a user's permanent data space in an
                   12557: easy manner, and to retrieve it again on another call. It is expected
                   12558: that a handler would use this once at the beginning to retrieve data,
                   12559: and then again once at the end to send only the new data back.
                   12560: 
                   12561: The data is stored in the user's data directory on the user's
                   12562: homeserver under the ID of the course.
                   12563: 
                   12564: The hash that is returned by restore will have all of the previous
                   12565: value for all of the elements of the hash.
                   12566: 
                   12567: Example:
                   12568: 
                   12569:  #creating a hash
                   12570:  my %hash;
                   12571:  $hash{'foo'}='bar';
                   12572: 
                   12573:  #storing it
                   12574:  &Apache::lonnet::cstore(\%hash);
                   12575: 
                   12576:  #changing a value
                   12577:  $hash{'foo'}='notbar';
                   12578: 
                   12579:  #adding a new value
                   12580:  $hash{'bar'}='foo';
                   12581:  &Apache::lonnet::cstore(\%hash);
                   12582: 
                   12583:  #retrieving the hash
                   12584:  my %history=&Apache::lonnet::restore();
                   12585: 
                   12586:  #print the hash
                   12587:  foreach my $key (sort(keys(%history))) {
                   12588:    print("\%history{$key} = $history{$key}");
                   12589:  }
                   12590: 
                   12591: Will print out:
1.191     harris41 12592: 
1.394     bowersj2 12593:  %history{1:foo} = bar
                   12594:  %history{1:keys} = foo:timestamp
                   12595:  %history{1:timestamp} = 990455579
                   12596:  %history{2:bar} = foo
                   12597:  %history{2:foo} = notbar
                   12598:  %history{2:keys} = foo:bar:timestamp
                   12599:  %history{2:timestamp} = 990455580
                   12600:  %history{bar} = foo
                   12601:  %history{foo} = notbar
                   12602:  %history{timestamp} = 990455580
                   12603:  %history{version} = 2
                   12604: 
                   12605: Note that the special hash entries C<keys>, C<version> and
                   12606: C<timestamp> were added to the hash. C<version> will be equal to the
                   12607: total number of versions of the data that have been stored. The
                   12608: C<timestamp> attribute will be the UNIX time the hash was
                   12609: stored. C<keys> is available in every historical section to list which
                   12610: keys were added or changed at a specific historical revision of a
                   12611: hash.
                   12612: 
                   12613: B<Warning>: do not store the hash that restore returns directly. This
                   12614: will cause a mess since it will restore the historical keys as if the
                   12615: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 12616: 
1.394     bowersj2 12617: Calling convention:
1.191     harris41 12618: 
1.1172.2.27  raeburn  12619:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
                   12620:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname);
1.191     harris41 12621: 
1.394     bowersj2 12622: For more detailed information, see lonnet specific documentation.
1.191     harris41 12623: 
1.394     bowersj2 12624: =head1 RETURN MESSAGES
1.191     harris41 12625: 
1.394     bowersj2 12626: =over 4
1.191     harris41 12627: 
1.394     bowersj2 12628: =item * B<con_lost>: unable to contact remote host
1.191     harris41 12629: 
1.394     bowersj2 12630: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   12631: when the connection is brought back up
1.191     harris41 12632: 
1.394     bowersj2 12633: =item * B<con_failed>: unable to contact remote host and unable to save message
                   12634: for later delivery
1.191     harris41 12635: 
1.967     bisitz   12636: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 12637: 
1.394     bowersj2 12638: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 12639: that was requested
1.191     harris41 12640: 
1.243     albertel 12641: =back
1.191     harris41 12642: 
1.243     albertel 12643: =head1 PUBLIC SUBROUTINES
1.191     harris41 12644: 
1.243     albertel 12645: =head2 Session Environment Functions
1.191     harris41 12646: 
1.243     albertel 12647: =over 4
1.191     harris41 12648: 
1.394     bowersj2 12649: =item * 
                   12650: X<appenv()>
1.949     raeburn  12651: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 12652: the user envirnoment file, and will be restored for each access this
1.620     albertel 12653: user makes during this session, also modifies the %env for the current
1.949     raeburn  12654: process. Optional rolesarrayref - if defined contains a reference to an array
                   12655: of roles which are exempt from the restriction on modifying user.role entries 
                   12656: in the user's environment.db and in %env.    
1.191     harris41 12657: 
                   12658: =item *
1.394     bowersj2 12659: X<delenv()>
1.987     raeburn  12660: B<delenv($delthis,$regexp)>: removes all items from the session
                   12661: environment file that begin with $delthis. If the 
                   12662: optional second arg - $regexp - is true, $delthis is treated as a 
                   12663: regular expression, otherwise \Q$delthis\E is used. 
                   12664: The values are also deleted from the current processes %env.
1.191     harris41 12665: 
1.795     albertel 12666: =item * get_env_multiple($name) 
                   12667: 
                   12668: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   12669: values may be defined and end up as an array ref.
                   12670: 
                   12671: returns an array of values
                   12672: 
1.243     albertel 12673: =back
                   12674: 
                   12675: =head2 User Information
1.191     harris41 12676: 
1.243     albertel 12677: =over 4
1.191     harris41 12678: 
                   12679: =item *
1.394     bowersj2 12680: X<queryauthenticate()>
                   12681: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 12682: authentication scheme
                   12683: 
                   12684: =item *
1.394     bowersj2 12685: X<authenticate()>
1.1073    raeburn  12686: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 12687: authenticate user from domain's lib servers (first use the current
                   12688: one). C<$upass> should be the users password.
1.1073    raeburn  12689: $checkdefauth is optional (value is 1 if a check should be made to
                   12690:    authenticate user using default authentication method, and allow
                   12691:    account creation if username does not have account in the domain).
                   12692: $clientcancheckhost is optional (value is 1 if checking whether the
                   12693:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 12694: 
                   12695: =item *
1.394     bowersj2 12696: X<homeserver()>
                   12697: B<homeserver($uname,$udom)>: find the server which has
                   12698: the user's directory and files (there must be only one), this caches
                   12699: the answer, and also caches if there is a borken connection.
1.191     harris41 12700: 
                   12701: =item *
1.394     bowersj2 12702: X<idget()>
                   12703: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   12704: (IDs are a unique resource in a domain, there must be only 1 ID per
                   12705: username, and only 1 username per ID in a specific domain) (returns
                   12706: hash: id=>name,id=>name)
1.191     harris41 12707: 
                   12708: =item *
1.394     bowersj2 12709: X<idrget()>
                   12710: B<idrget($udom,@unames)>: find the IDs behind a list of
                   12711: usernames (returns hash: name=>id,name=>id)
1.191     harris41 12712: 
                   12713: =item *
1.394     bowersj2 12714: X<idput()>
                   12715: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 12716: 
                   12717: =item *
1.394     bowersj2 12718: X<rolesinit()>
1.1169    droeschl 12719: B<rolesinit($udom,$username)>: get user privileges.
                   12720: returns user role, first access and timer interval hashes
1.243     albertel 12721: 
                   12722: =item *
1.1171    droeschl 12723: X<privileged()>
                   12724: B<privileged($username,$domain)>: returns a true if user has a
                   12725: privileged and active role (i.e. su or dc), false otherwise.
                   12726: 
                   12727: =item *
1.551     albertel 12728: X<getsection()>
                   12729: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 12730: course $cname, return section name/number or '' for "not in course"
                   12731: and '-1' for "no section"
                   12732: 
                   12733: =item *
1.394     bowersj2 12734: X<userenvironment()>
                   12735: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 12736: passed in @what from the requested user's environment, returns a hash
                   12737: 
1.858     raeburn  12738: =item * 
                   12739: X<userlog_query()>
1.859     albertel 12740: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   12741: activity.log file. %filters defines filters applied when parsing the
                   12742: log file. These can be start or end timestamps, or the type of action
                   12743: - log to look for Login or Logout events, check for Checkin or
                   12744: Checkout, role for role selection. The response is in the form
                   12745: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   12746: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  12747: 
1.243     albertel 12748: =back
                   12749: 
                   12750: =head2 User Roles
                   12751: 
                   12752: =over 4
                   12753: 
                   12754: =item *
                   12755: 
1.810     raeburn  12756: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 12757:  F: full access
                   12758:  U,I,K: authentication modes (cxx only)
                   12759:  '': forbidden
                   12760:  1: user needs to choose course
                   12761:  2: browse allowed
1.766     albertel 12762:  A: passphrase authentication needed
1.243     albertel 12763: 
                   12764: =item *
                   12765: 
1.1172.2.13  raeburn  12766: constructaccess($url,$setpriv) : check for access to construction space URL
                   12767: 
                   12768: See if the owner domain and name in the URL match those in the
                   12769: expected environment.  If so, return three element list
                   12770: ($ownername,$ownerdomain,$ownerhome).
                   12771: 
                   12772: Otherwise return the null string.
                   12773: 
                   12774: If second argument 'setpriv' is true, it assigns the privileges,
                   12775: and returns the same three element list, unless the owner has
                   12776: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   12777: in which case the null string is returned.
                   12778: 
                   12779: =item *
                   12780: 
1.243     albertel 12781: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   12782: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   12783: and course level
                   12784: 
                   12785: =item *
                   12786: 
1.988     raeburn  12787: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   12788: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  12789: $type is Course (default) or Community.
1.988     raeburn  12790: If $forcedefault evaluates to true, text returned will be default 
                   12791: text for $type. Otherwise, if this is a course, the text returned 
                   12792: will be a custom name for the role (if defined in the course's 
                   12793: environment).  If no custom name is defined the default is returned.
                   12794:    
1.832     raeburn  12795: =item *
                   12796: 
1.1172.2.23  raeburn  12797: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  12798: All arguments are optional. Returns a hash of a roles, either for
                   12799: co-author/assistant author roles for a user's Construction Space
1.906     albertel 12800: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  12801: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   12802: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   12803: For each key, value is set to colon-separated start and end times for
                   12804: the role.  If no username and domain are specified, will default to
1.934     raeburn  12805: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  12806: of role statuses (active, future or previous), roles 
                   12807: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   12808: to restrict the list of roles reported. If no array ref is 
                   12809: provided for types, will default to return only active roles.
1.834     albertel 12810: 
1.1172.2.13  raeburn  12811: =item *
                   12812: 
                   12813: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   12814: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   12815: 
                   12816: Additional optional arguments are: $type (if role checking is to be restricted
                   12817: to certain user status types -- previous (expired roles), active (currently
                   12818: available roles) or future (roles available in the future), and
                   12819: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  12820: have active Domain Coordinator role in course's domain or in additional
                   12821: domains (specified in 'Domains to check for privileged users' in course
                   12822: environment -- set via:  Course Settings -> Classlists and staff listing).
                   12823: 
                   12824: =item *
                   12825: 
                   12826: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   12827: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   12828: $possdomains and $possroles are optional array refs -- to domains to check and
                   12829: roles to check.  If $possdomains is not specified, a dump will be done of the
                   12830: users' roles.db to check for a dc or su role in any domain. This can be
                   12831: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   12832: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   12833: this then allows &privileged_by_domain() to be used, which caches the identity
                   12834: of privileged users, eliminating the need for repeated calls to &dump().
                   12835: 
                   12836: =item *
                   12837: 
                   12838: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   12839: where the outer hash keys are domains specified in the $possdomains array ref,
                   12840: next inner hash keys are privileged roles specified in the $roles array ref,
                   12841: and the innermost hash contains key = value pairs for username:domain = end:start
                   12842: for active or future "privileged" users with that role in that domain. To avoid
                   12843: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   12844: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  12845: 
1.243     albertel 12846: =back
                   12847: 
                   12848: =head2 User Modification
                   12849: 
                   12850: =over 4
                   12851: 
                   12852: =item *
                   12853: 
1.957     raeburn  12854: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 12855: user for the level given by URL.  Optional start and end dates (leave empty
                   12856: string or zero for "no date")
1.191     harris41 12857: 
                   12858: =item *
                   12859: 
1.243     albertel 12860: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   12861: change a users, password, possible return values are: ok,
                   12862: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   12863: refused
1.191     harris41 12864: 
                   12865: =item *
                   12866: 
1.243     albertel 12867: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 12868: 
                   12869: =item *
                   12870: 
1.1058    raeburn  12871: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   12872:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   12873: 
                   12874: will update user information (firstname,middlename,lastname,generation,
                   12875: permanentemail), and if forceid is true, student/employee ID also.
                   12876: A user's institutional affiliation(s) can also be updated.
                   12877: User information fields will not be overwritten with empty entries 
                   12878: unless the field is included in the $candelete array reference.
                   12879: This array is included when a single user is modified via "Manage Users",
                   12880: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 12881: 
                   12882: =item *
                   12883: 
1.286     matthew  12884: modifystudent
                   12885: 
1.957     raeburn  12886: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  12887: The course id is resolved based on the current user's environment.  
                   12888: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  12889: associated with a course.
                   12890: 
1.297     matthew  12891: This call is essentially a wrapper for lonnet::modifyuser and
                   12892: lonnet::modify_student_enrollment
1.286     matthew  12893: 
                   12894: Inputs: 
                   12895: 
                   12896: =over 4
                   12897: 
1.957     raeburn  12898: =item B<$udom> Student's loncapa domain
1.286     matthew  12899: 
1.957     raeburn  12900: =item B<$uname> Student's loncapa login name
1.286     matthew  12901: 
1.964     bisitz   12902: =item B<$uid> Student/Employee ID
1.286     matthew  12903: 
1.957     raeburn  12904: =item B<$umode> Student's authentication mode
1.286     matthew  12905: 
1.957     raeburn  12906: =item B<$upass> Student's password
1.286     matthew  12907: 
1.957     raeburn  12908: =item B<$first> Student's first name
1.286     matthew  12909: 
1.957     raeburn  12910: =item B<$middle> Student's middle name
1.286     matthew  12911: 
1.957     raeburn  12912: =item B<$last> Student's last name
1.286     matthew  12913: 
1.957     raeburn  12914: =item B<$gene> Student's generation
1.286     matthew  12915: 
1.957     raeburn  12916: =item B<$usec> Student's section in course
1.286     matthew  12917: 
                   12918: =item B<$end> Unix time of the roles expiration
                   12919: 
                   12920: =item B<$start> Unix time of the roles start date
                   12921: 
                   12922: =item B<$forceid> If defined, allow $uid to be changed
                   12923: 
                   12924: =item B<$desiredhome> server to use as home server for student
                   12925: 
1.957     raeburn  12926: =item B<$email> Student's permanent e-mail address
                   12927: 
                   12928: =item B<$type> Type of enrollment (auto or manual)
                   12929: 
1.963     raeburn  12930: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   12931: 
                   12932: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  12933: 
1.963     raeburn  12934: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  12935: 
1.963     raeburn  12936: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  12937: 
1.1172.2.19  raeburn  12938: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   12939: 
                   12940: =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  12941: 
1.286     matthew  12942: =back
1.297     matthew  12943: 
                   12944: =item *
                   12945: 
                   12946: modify_student_enrollment
                   12947: 
1.1172.2.31  raeburn  12948: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  12949: 'role.request.course' must be defined for this function to proceed.
                   12950: 
                   12951: Inputs:
                   12952: 
                   12953: =over 4
                   12954: 
1.1172.2.31  raeburn  12955: =item $udom, student's domain
1.297     matthew  12956: 
1.1172.2.31  raeburn  12957: =item $uname, student's name
1.297     matthew  12958: 
1.1172.2.31  raeburn  12959: =item $uid, student's user id
1.297     matthew  12960: 
1.1172.2.31  raeburn  12961: =item $first, student's first name
1.297     matthew  12962: 
                   12963: =item $middle
                   12964: 
                   12965: =item $last
                   12966: 
                   12967: =item $gene
                   12968: 
                   12969: =item $usec
                   12970: 
                   12971: =item $end
                   12972: 
                   12973: =item $start
                   12974: 
1.957     raeburn  12975: =item $type
                   12976: 
                   12977: =item $locktype
                   12978: 
                   12979: =item $cid
                   12980: 
                   12981: =item $selfenroll
                   12982: 
                   12983: =item $context
                   12984: 
1.1172.2.19  raeburn  12985: =item $credits, number of credits student will earn from this class
                   12986: 
1.297     matthew  12987: =back
                   12988: 
1.191     harris41 12989: 
                   12990: =item *
                   12991: 
1.243     albertel 12992: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   12993: custom role; give a custom role to a user for the level given by URL.  Specify
                   12994: name and domain of role author, and role name
1.191     harris41 12995: 
                   12996: =item *
                   12997: 
1.243     albertel 12998: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 12999: 
                   13000: =item *
                   13001: 
1.243     albertel 13002: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   13003: 
                   13004: =back
                   13005: 
                   13006: =head2 Course Infomation
                   13007: 
                   13008: =over 4
1.191     harris41 13009: 
                   13010: =item *
                   13011: 
1.1118    foxr     13012: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 13013: specified course id, including all environment settings for the
                   13014: course, the description of the course will be in the hash under the
                   13015: key 'description'
1.191     harris41 13016: 
1.1118    foxr     13017: $options is an optional parameter that if supplied is a hash reference that controls
                   13018: what how this function works.  It has the following key/values:
                   13019: 
                   13020: =over 4
                   13021: 
                   13022: =item freshen_cache
                   13023: 
                   13024: If defined, and the environment cache for the course is valid, it is 
                   13025: returned in the returned hash.
                   13026: 
                   13027: =item one_time
                   13028: 
                   13029: If defined, the last cache time is set to _now_
                   13030: 
                   13031: =item user
                   13032: 
                   13033: If defined, the supplied username is used instead of the current user.
                   13034: 
                   13035: 
                   13036: =back
                   13037: 
1.191     harris41 13038: =item *
                   13039: 
1.624     albertel 13040: resdata($name,$domain,$type,@which) : request for current parameter
                   13041: setting for a specific $type, where $type is either 'course' or 'user',
                   13042: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  13043: answers for 10 minutes.
1.243     albertel 13044: 
1.877     foxr     13045: =item *
                   13046: 
                   13047: get_courseresdata($courseid, $domain) : dump the entire course resource
                   13048: data base, returning a hash that is keyed by the resource name and has
                   13049: values that are the resource value.  I believe that the timestamps and
                   13050: versions are also returned.
                   13051: 
1.1172.2.31  raeburn  13052: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   13053: supplemental content area. This routine caches the number of files for
                   13054: 10 minutes.
                   13055: 
1.243     albertel 13056: =back
                   13057: 
                   13058: =head2 Course Modification
                   13059: 
                   13060: =over 4
1.191     harris41 13061: 
                   13062: =item *
                   13063: 
1.243     albertel 13064: writecoursepref($courseid,%prefs) : write preferences (environment
                   13065: database) for a course
1.191     harris41 13066: 
                   13067: =item *
                   13068: 
1.1011    raeburn  13069: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   13070: 
                   13071: =item *
                   13072: 
1.1038    raeburn  13073: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 13074: 
1.1167    droeschl 13075: =item *
                   13076: 
                   13077: is_course($courseid), is_course($cdom, $cnum)
                   13078: 
                   13079: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   13080: two component version $cdom, $cnum. It checks if the specified course exists.
                   13081: 
                   13082: Returns:
                   13083:     undef if the course doesn't exist, otherwise
                   13084:     in scalar context the combined courseid.
                   13085:     in list context the two components of the course identifier, domain and 
                   13086:     courseid.    
                   13087: 
1.243     albertel 13088: =back
                   13089: 
                   13090: =head2 Resource Subroutines
                   13091: 
                   13092: =over 4
1.191     harris41 13093: 
                   13094: =item *
                   13095: 
1.243     albertel 13096: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 13097: 
                   13098: =item *
                   13099: 
1.243     albertel 13100: repcopy($filename) : subscribes to the requested file, and attempts to
                   13101: replicate from the owning library server, Might return
1.607     raeburn  13102: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   13103: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 13104: resource. Expects the local filesystem pathname
                   13105: (/home/httpd/html/res/....)
                   13106: 
                   13107: =back
                   13108: 
                   13109: =head2 Resource Information
                   13110: 
                   13111: =over 4
1.191     harris41 13112: 
                   13113: =item *
                   13114: 
1.1172.2.28  raeburn  13115: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   13116: and returns the value of a variety of different possible values,
                   13117: $varname should be a request string, and the other parameters can be
                   13118: used to specify who and what one is asking about. Ordinarily, $cid 
                   13119: does not need to be specified, as it is retrived from 
                   13120: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   13121: within lonuserstate::loadmap() when initializing a course, before
                   13122: $env{'request.course.id'} has been set, so it needs to be provided
                   13123: in that one case.
1.243     albertel 13124: 
                   13125: Possible values for $varname are environment.lastname (or other item
                   13126: from the envirnment hash), user.name (or someother aspect about the
                   13127: user), resource.0.maxtries (or some other part and parameter of a
                   13128: resource)
1.204     albertel 13129: 
                   13130: =item *
                   13131: 
1.243     albertel 13132: directcondval($number) : get current value of a condition; reads from a state
                   13133: string
1.204     albertel 13134: 
                   13135: =item *
                   13136: 
1.243     albertel 13137: condval($condidx) : value of condition index based on state
1.204     albertel 13138: 
                   13139: =item *
                   13140: 
1.243     albertel 13141: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   13142: resource's metadata, $what should be either a specific key, or either
                   13143: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   13144: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   13145: 
                   13146: this function automatically caches all requests
1.191     harris41 13147: 
                   13148: =item *
                   13149: 
1.243     albertel 13150: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   13151: network of library servers; returns file handle of where SQL and regex results
                   13152: will be stored for query
1.191     harris41 13153: 
                   13154: =item *
                   13155: 
1.243     albertel 13156: symbread($filename) : return symbolic list entry (filename argument optional);
                   13157: returns the data handle
1.191     harris41 13158: 
                   13159: =item *
                   13160: 
1.1172.2.17  raeburn  13161: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  13162: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 13163: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  13164: on failure, user must be in a course, as it assumes the existence of
                   13165: the course initial hash, and uses $env('request.course.id'}.  The third
                   13166: arg is an optional reference to a scalar.  If this arg is passed in the
                   13167: call to symbverify, it will be set to 1 if the symb has been set to be 
                   13168: encrypted; otherwise it will be null.
1.243     albertel 13169: 
1.191     harris41 13170: =item *
                   13171: 
1.243     albertel 13172: symbclean($symb) : removes versions numbers from a symb, returns the
                   13173: cleaned symb
1.191     harris41 13174: 
                   13175: =item *
                   13176: 
1.243     albertel 13177: is_on_map($uri) : checks if the $uri is somewhere on the current
                   13178: course map, user must be in a course for it to work.
1.191     harris41 13179: 
                   13180: =item *
                   13181: 
1.243     albertel 13182: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 13183: 
                   13184: =item *
                   13185: 
1.243     albertel 13186: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   13187: a random seed, all arguments are optional, if they aren't sent it uses the
                   13188: environment to derive them. Note: if symb isn't sent and it can't get one
                   13189: from &symbread it will use the current time as its return value
1.191     harris41 13190: 
                   13191: =item *
                   13192: 
1.243     albertel 13193: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   13194: unfakeable, receipt
1.191     harris41 13195: 
                   13196: =item *
                   13197: 
1.620     albertel 13198: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 13199: 
                   13200: =item *
                   13201: 
1.243     albertel 13202: countacc($url) : count the number of accesses to a given URL
1.191     harris41 13203: 
                   13204: =item *
                   13205: 
1.243     albertel 13206: 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 13207: 
                   13208: =item *
                   13209: 
1.243     albertel 13210: 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 13211: 
                   13212: =item *
                   13213: 
1.243     albertel 13214: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 13215: 
                   13216: =item *
                   13217: 
1.243     albertel 13218: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   13219: forcing spreadsheet to reevaluate the resource scores next time.
                   13220: 
1.1172.2.13  raeburn  13221: =item *
                   13222: 
                   13223: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   13224: when viewing in course context.
                   13225: 
                   13226:  input: six args -- filename (decluttered), course number, course domain,
                   13227:                     url, symb (if registered) and group (if this is a
                   13228:                     group item -- e.g., bulletin board, group page etc.).
                   13229: 
                   13230:  output: array of five scalars --
                   13231:          $cfile -- url for file editing if editable on current server
                   13232:          $home -- homeserver of resource (i.e., for author if published,
                   13233:                                           or course if uploaded.).
                   13234:          $switchserver --  1 if server switch will be needed.
                   13235:          $forceedit -- 1 if icon/link should be to go to edit mode
                   13236:          $forceview -- 1 if icon/link should be to go to view mode
                   13237: 
                   13238: =item *
                   13239: 
                   13240: is_course_upload($file,$cnum,$cdom)
                   13241: 
                   13242: Used in course context to determine if current file was uploaded to
                   13243: the course (i.e., would be found in /userfiles/docs on the course's
                   13244: homeserver.
                   13245: 
                   13246:   input: 3 args -- filename (decluttered), course number and course domain.
                   13247:   output: boolean -- 1 if file was uploaded.
                   13248: 
1.243     albertel 13249: =back
                   13250: 
                   13251: =head2 Storing/Retreiving Data
                   13252: 
                   13253: =over 4
1.191     harris41 13254: 
                   13255: =item *
                   13256: 
1.243     albertel 13257: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   13258: for this url; hashref needs to be given and should be a \%hashname; the
                   13259: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 13260: be derived from the env
1.191     harris41 13261: 
                   13262: =item *
                   13263: 
1.243     albertel 13264: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   13265: uses critical subroutine
1.191     harris41 13266: 
                   13267: =item *
                   13268: 
1.243     albertel 13269: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   13270: all args are optional
1.191     harris41 13271: 
                   13272: =item *
                   13273: 
1.717     albertel 13274: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   13275: dumps the complete (or key matching regexp) namespace into a hash
                   13276: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   13277: normally &store()ed into
                   13278: 
                   13279: $range should be either an integer '100' (give me the first 100
                   13280:                                            matching records)
                   13281:               or be  two integers sperated by a - with no spaces
                   13282:                  '30-50' (give me the 30th through the 50th matching
                   13283:                           records)
                   13284: 
                   13285: 
                   13286: =item *
                   13287: 
                   13288: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   13289: replaces a &store() version of data with a replacement set of data
                   13290: for a particular resource in a namespace passed in the $storehash hash 
                   13291: reference
                   13292: 
                   13293: =item *
                   13294: 
1.243     albertel 13295: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   13296: works very similar to store/cstore, but all data is stored in a
                   13297: temporary location and can be reset using tmpreset, $storehash should
                   13298: be a hash reference, returns nothing on success
1.191     harris41 13299: 
                   13300: =item *
                   13301: 
1.243     albertel 13302: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   13303: similar to restore, but all data is stored in a temporary location and
                   13304: can be reset using tmpreset. Returns a hash of values on success,
                   13305: error string otherwise.
1.191     harris41 13306: 
                   13307: =item *
                   13308: 
1.243     albertel 13309: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   13310: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 13311: 
                   13312: =item *
                   13313: 
1.243     albertel 13314: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13315: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 13316: 
                   13317: =item *
                   13318: 
1.243     albertel 13319: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   13320: namesp ($udom and $uname are optional)
1.191     harris41 13321: 
                   13322: =item *
                   13323: 
1.702     albertel 13324: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 13325: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 13326: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  13327: 
1.702     albertel 13328: $range should be either an integer '100' (give me the first 100
                   13329:                                            matching records)
                   13330:               or be  two integers sperated by a - with no spaces
                   13331:                  '30-50' (give me the 30th through the 50th matching
                   13332:                           records)
1.449     matthew  13333: =item *
                   13334: 
                   13335: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   13336: $store can be a scalar, an array reference, or if the amount to be 
                   13337: incremented is > 1, a hash reference.
                   13338: 
                   13339: ($udom and $uname are optional)
1.191     harris41 13340: 
                   13341: =item *
                   13342: 
1.243     albertel 13343: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   13344: ($udom and $uname are optional)
1.191     harris41 13345: 
                   13346: =item *
                   13347: 
1.243     albertel 13348: cput($namespace,$storehash,$udom,$uname) : critical put
                   13349: ($udom and $uname are optional)
1.191     harris41 13350: 
                   13351: =item *
                   13352: 
1.748     albertel 13353: newput($namespace,$storehash,$udom,$uname) :
                   13354: 
                   13355: Attempts to store the items in the $storehash, but only if they don't
                   13356: currently exist, if this succeeds you can be certain that you have 
                   13357: successfully created a new key value pair in the $namespace db.
                   13358: 
                   13359: 
                   13360: Args:
                   13361:  $namespace: name of database to store values to
                   13362:  $storehash: hashref to store to the db
                   13363:  $udom: (optional) domain of user containing the db
                   13364:  $uname: (optional) name of user caontaining the db
                   13365: 
                   13366: Returns:
                   13367:  'ok' -> succeeded in storing all keys of $storehash
                   13368:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   13369:                         least <key> already existed in the db (other
                   13370:                         requested keys may also already exist)
1.967     bisitz   13371:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 13372:  'con_lost' -> unable to contact request server
                   13373:  'refused' -> action was not allowed by remote machine
                   13374: 
                   13375: 
                   13376: =item *
                   13377: 
1.243     albertel 13378: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13379: reference filled in from namesp (encrypts the return communication)
                   13380: ($udom and $uname are optional)
1.191     harris41 13381: 
                   13382: =item *
                   13383: 
1.243     albertel 13384: log($udom,$name,$home,$message) : write to permanent log for user; use
                   13385: critical subroutine
                   13386: 
1.806     raeburn  13387: =item *
                   13388: 
1.860     raeburn  13389: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   13390: array reference filled in from namespace found in domain level on either
                   13391: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  13392: 
                   13393: =item *
                   13394: 
1.860     raeburn  13395: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   13396: domain level either on specified domain server ($uhome) or primary domain 
                   13397: server ($udom and $uhome are optional)
1.806     raeburn  13398: 
1.943     raeburn  13399: =item * 
                   13400: 
1.1172.2.35  raeburn  13401: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
                   13402: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   13403: the target domain.
                   13404: 
                   13405: May also include additional key => value pairs for the following groups:
                   13406: 
                   13407: =over
                   13408: 
                   13409: =item
                   13410: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   13411: 
                   13412: =over
                   13413: 
                   13414: =item defaultquota, authorquota
                   13415: 
                   13416: =back
                   13417: 
                   13418: =item
                   13419: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   13420: portfolio for users).
                   13421: 
                   13422: =over
                   13423: 
                   13424: =item
                   13425: aboutme, blog, webdav, portfolio
                   13426: 
                   13427: =back
                   13428: 
                   13429: =item
                   13430: requestcourses: ability to request courses, and how requests are processed.
                   13431: 
                   13432: =over
                   13433: 
                   13434: =item
1.1172.2.37  raeburn  13435: official, unofficial, community, textbook
1.1172.2.35  raeburn  13436: 
                   13437: =back
                   13438: 
                   13439: =item
                   13440: inststatus: types of institutional affiliation, and order in which they are displayed.
                   13441: 
                   13442: =over
                   13443: 
                   13444: =item
1.1172.2.44  raeburn  13445: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35  raeburn  13446: 
                   13447: =back
                   13448: 
                   13449: =item
                   13450: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   13451: for course's uploaded content.
                   13452: 
                   13453: =over
                   13454: 
                   13455: =item
1.1172.2.37  raeburn  13456: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, communityquota, textbookquota
1.1172.2.35  raeburn  13457: 
                   13458: =back
                   13459: 
                   13460: =item
                   13461: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   13462: on your servers.
                   13463: 
                   13464: =over
                   13465: 
                   13466: =item
                   13467: remotesessions, hostedsessions
                   13468: 
                   13469: =back
                   13470: 
                   13471: =back
                   13472: 
                   13473: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   13474: utility to create a configuration.db file on a domain's primary library server
                   13475: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   13476: -- corresponding values are authentication type (internal, krb4, krb5,
                   13477: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
                   13478: will be available. Values are retrieved from cache (if current), unless the
                   13479: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   13480: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   13481: 
                   13482: Typical usage:
1.943     raeburn  13483: 
1.1172.2.35  raeburn  13484: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  13485: 
1.243     albertel 13486: =back
                   13487: 
                   13488: =head2 Network Status Functions
                   13489: 
                   13490: =over 4
1.191     harris41 13491: 
                   13492: =item *
                   13493: 
1.1137    raeburn  13494: dirlist() : return directory list based on URI (first arg).
                   13495: 
                   13496: Inputs: 1 required, 5 optional.
                   13497: 
                   13498: =over
                   13499: 
                   13500: =item 
                   13501: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   13502: 
                   13503: =item
                   13504: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   13505: 
                   13506: =item
                   13507: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   13508: 
                   13509: =item
                   13510: $getpropath - boolean: 1 if prepend path using &propath(). 
                   13511: 
                   13512: =item
                   13513: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   13514: 
                   13515: =item 
                   13516: $alternateRoot - path to prepend in place of path from $uri.
                   13517: 
                   13518: =back
                   13519: 
                   13520: Returns: Array of up to two items.
                   13521: 
                   13522: =over
                   13523: 
                   13524: a reference to an array of files/subdirectories
                   13525: 
                   13526: =over
                   13527: 
                   13528: Each element in the array of files/subdirectories is a & separated list of
                   13529: item name and the result of running stat on the item.  If dirlist was requested
                   13530: for a file instead of a directory, the item name will be ''. For a directory 
                   13531: listing, if the item is a metadata file, the element will end &N&M 
                   13532: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   13533: default copyright set (1).  
                   13534: 
                   13535: =back
                   13536: 
                   13537: a scalar containing error condition (if encountered).
                   13538: 
                   13539: =over
                   13540: 
                   13541: =item 
                   13542: no_host (no homeserver identified for $username:$domain).
                   13543: 
                   13544: =item 
                   13545: no_such_host (server contacted for listing not identified as valid host).
                   13546: 
                   13547: =item 
                   13548: con_lost (connection to remote server failed).
                   13549: 
                   13550: =item 
                   13551: refused (invalid $username:$domain received on lond side).
                   13552: 
                   13553: =item 
                   13554: no_such_dir (directory at specified path on lond side does not exist). 
                   13555: 
                   13556: =item 
                   13557: empty (directory at specified path on lond side is empty).
                   13558: 
                   13559: =over
                   13560: 
                   13561: This is currently not encountered because the &ls3, &ls2, 
                   13562: &ls (_handler) routines on the lond side do not filter out
                   13563: . and .. from a directory listing. 
                   13564: 
                   13565: =back
                   13566: 
                   13567: =back
                   13568: 
                   13569: =back
1.191     harris41 13570: 
                   13571: =item *
                   13572: 
1.243     albertel 13573: spareserver() : find server with least workload from spare.tab
                   13574: 
1.986     foxr     13575: 
                   13576: =item *
                   13577: 
                   13578: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   13579: if there is no corresponding loncapa host.
                   13580: 
1.243     albertel 13581: =back
                   13582: 
1.986     foxr     13583: 
1.243     albertel 13584: =head2 Apache Request
                   13585: 
                   13586: =over 4
1.191     harris41 13587: 
                   13588: =item *
                   13589: 
1.243     albertel 13590: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   13591: localhost, posts hash
                   13592: 
                   13593: =back
                   13594: 
                   13595: =head2 Data to String to Data
                   13596: 
                   13597: =over 4
1.191     harris41 13598: 
                   13599: =item *
                   13600: 
1.243     albertel 13601: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   13602: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 13603: 
                   13604: =item *
                   13605: 
1.243     albertel 13606: hashref2str($hashref) : convert a hashref into a string complete with
                   13607: escaping and '=' and '&' separators, supports elements that are
                   13608: arrayrefs and hashrefs
1.191     harris41 13609: 
                   13610: =item *
                   13611: 
1.243     albertel 13612: arrayref2str($arrayref) : convert an arrayref into a string complete
                   13613: with escaping and '&' separators, supports elements that are arrayrefs
                   13614: and hashrefs
1.191     harris41 13615: 
                   13616: =item *
                   13617: 
1.243     albertel 13618: str2hash($string) : convert string to hash using unescaping and
                   13619: splitting on '=' and '&', supports elements that are arrayrefs and
                   13620: hashrefs
1.191     harris41 13621: 
                   13622: =item *
                   13623: 
1.243     albertel 13624: str2array($string) : convert string to hash using unescaping and
                   13625: splitting on '&', supports elements that are arrayrefs and hashrefs
                   13626: 
                   13627: =back
                   13628: 
                   13629: =head2 Logging Routines
                   13630: 
                   13631: 
                   13632: These routines allow one to make log messages in the lonnet.log and
                   13633: lonnet.perm logfiles.
1.191     harris41 13634: 
1.1119    foxr     13635: =over 4
                   13636: 
1.191     harris41 13637: =item *
                   13638: 
1.243     albertel 13639: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 13640: 
                   13641: =item *
                   13642: 
1.243     albertel 13643: logthis() : append message to the normal lonnet.log file, it gets
                   13644: preiodically rolled over and deleted.
1.191     harris41 13645: 
                   13646: =item *
                   13647: 
1.243     albertel 13648: logperm() : append a permanent message to lonnet.perm.log, this log
                   13649: file never gets deleted by any automated portion of the system, only
                   13650: messages of critical importance should go in here.
                   13651: 
1.1119    foxr     13652: 
1.243     albertel 13653: =back
                   13654: 
                   13655: =head2 General File Helper Routines
                   13656: 
                   13657: =over 4
1.191     harris41 13658: 
                   13659: =item *
                   13660: 
1.481     raeburn  13661: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   13662: (a) files in /uploaded
                   13663:   (i) If a local copy of the file exists - 
                   13664:       compares modification date of local copy with last-modified date for 
                   13665:       definitive version stored on home server for course. If local copy is 
                   13666:       stale, requests a new version from the home server and stores it. 
                   13667:       If the original has been removed from the home server, then local copy 
                   13668:       is unlinked.
                   13669:   (ii) If local copy does not exist -
                   13670:       requests the file from the home server and stores it. 
                   13671:   
                   13672:   If $caller is 'uploadrep':  
                   13673:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   13674:     for request for files originally uploaded via DOCS. 
                   13675:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   13676:   
                   13677:   Otherwise:
                   13678:      This indicates a call from the content generation phase of the request.
                   13679:      -  returns the entire contents of the file or -1.
                   13680:      
                   13681: (b) files in /res
                   13682:    - returns the entire contents of a file or -1; 
                   13683:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 13684: 
1.712     albertel 13685: 
                   13686: =item *
                   13687: 
                   13688: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   13689:                   reference
                   13690: 
                   13691: returns either a stat() list of data about the file or an empty list
                   13692: if the file doesn't exist or couldn't find out about it (connection
                   13693: problems or user unknown)
                   13694: 
1.191     harris41 13695: =item *
                   13696: 
1.243     albertel 13697: filelocation($dir,$file) : returns file system location of a file
                   13698: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   13699: directory that relative $file lookups are to looked in ($dir of /a/dir
                   13700: and a file of ../bob will become /a/bob)
1.191     harris41 13701: 
                   13702: =item *
                   13703: 
                   13704: hreflocation($dir,$file) : returns file system location or a URL; same as
                   13705: filelocation except for hrefs
                   13706: 
                   13707: =item *
                   13708: 
                   13709: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   13710: 
1.243     albertel 13711: =back
                   13712: 
1.608     albertel 13713: =head2 Usererfile file routines (/uploaded*)
                   13714: 
                   13715: =over 4
                   13716: 
                   13717: =item *
                   13718: 
                   13719: userfileupload(): main rotine for putting a file in a user or course's
                   13720:                   filespace, arguments are,
                   13721: 
1.620     albertel 13722:  formname - required - this is the name of the element in $env where the
1.608     albertel 13723:            filename, and the contents of the file to create/modifed exist
1.620     albertel 13724:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   13725:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  13726:  context - if coursedoc, store the file in the course of the active role
                   13727:              of the current user; 
                   13728:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   13729:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 13730:  subdir - required - subdirectory to put the file in under ../userfiles/
                   13731:          if undefined, it will be placed in "unknown"
                   13732: 
                   13733:  (This routine calls clean_filename() to remove any dangerous
                   13734:  characters from the filename, and then calls finuserfileupload() to
                   13735:  complete the transaction)
                   13736: 
                   13737:  returns either the url of the uploaded file (/uploaded/....) if successful
                   13738:  and /adm/notfound.html if unsuccessful
                   13739: 
                   13740: =item *
                   13741: 
                   13742: clean_filename(): routine for cleaing a filename up for storage in
                   13743:                  userfile space, argument is:
                   13744: 
                   13745:  filename - proposed filename
                   13746: 
                   13747: returns: the new clean filename
                   13748: 
                   13749: =item *
                   13750: 
1.1090    raeburn  13751: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 13752: userspace, probably shouldn't be called directly
                   13753: 
                   13754:   docuname: username or courseid of destination for the file
                   13755:   docudom: domain of user/course of destination for the file
                   13756:   formname: same as for userfileupload()
1.1090    raeburn  13757:   fname: filename (including subdirectories) for the file
                   13758:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   13759:   allfiles: reference to hash used to store objects found by parser
                   13760:   codebase: reference to hash used for codebases of java objects found by parser
                   13761:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   13762:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   13763:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   13764:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   13765:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   13766:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  13767:   mimetype: reference to scalar to accommodate mime type determined
                   13768:             from File::MMagic if $parser = parse.
1.608     albertel 13769: 
                   13770:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  13771:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   13772:  was 'overwrite').
                   13773:  
1.608     albertel 13774: 
                   13775: =item *
                   13776: 
                   13777: renameuserfile(): renames an existing userfile to a new name
                   13778: 
                   13779:   Args:
                   13780:    docuname: username or courseid of destination for the file
                   13781:    docudom: domain of user/course of destination for the file
                   13782:    old: current file name (including any subdirs under userfiles)
                   13783:    new: desired file name (including any subdirs under userfiles)
                   13784: 
                   13785: =item *
                   13786: 
                   13787: mkdiruserfile(): creates a directory is a userfiles dir
                   13788: 
                   13789:   Args:
                   13790:    docuname: username or courseid of destination for the file
                   13791:    docudom: domain of user/course of destination for the file
                   13792:    dir: dir to create (including any subdirs under userfiles)
                   13793: 
                   13794: =item *
                   13795: 
                   13796: removeuserfile(): removes a file that exists in userfiles
                   13797: 
                   13798:   Args:
                   13799:    docuname: username or courseid of destination for the file
                   13800:    docudom: domain of user/course of destination for the file
                   13801:    fname: filname to delete (including any subdirs under userfiles)
                   13802: 
                   13803: =item *
                   13804: 
                   13805: removeuploadedurl(): convience function for removeuserfile()
                   13806: 
                   13807:   Args:
                   13808:    url:  a full /uploaded/... url to delete
                   13809: 
1.747     albertel 13810: =item * 
                   13811: 
                   13812: get_portfile_permissions():
                   13813:   Args:
                   13814:     domain: domain of user or course contain the portfolio files
                   13815:     user: name of user or num of course contain the portfolio files
                   13816:   Returns:
                   13817:     hashref of a dump of the proper file_permissions.db
                   13818:    
                   13819: 
                   13820: =item * 
                   13821: 
                   13822: get_access_controls():
                   13823: 
                   13824: Args:
                   13825:   current_permissions: the hash ref returned from get_portfile_permissions()
                   13826:   group: (optional) the group you want the files associated with
                   13827:   file: (optional) the file you want access info on
                   13828: 
                   13829: Returns:
1.749     raeburn  13830:     a hash (keys are file names) of hashes containing
                   13831:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   13832:         values are XML containing access control settings (see below) 
1.747     albertel 13833: 
                   13834: Internal notes:
                   13835: 
1.749     raeburn  13836:  access controls are stored in file_permissions.db as key=value pairs.
                   13837:     key -> path to file/file_name\0uniqueID:scope_end_start
                   13838:         where scope -> public,guest,course,group,domains or users.
                   13839:               end -> UNIX time for end of access (0 -> no end date)
                   13840:               start -> UNIX time for start of access
                   13841: 
                   13842:     value -> XML description of access control
                   13843:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   13844:             <start></start>
                   13845:             <end></end>
                   13846: 
                   13847:             <password></password>  for scope type = guest
                   13848: 
                   13849:             <domain></domain>     for scope type = course or group
                   13850:             <number></number>
                   13851:             <roles id="">
                   13852:              <role></role>
                   13853:              <access></access>
                   13854:              <section></section>
                   13855:              <group></group>
                   13856:             </roles>
                   13857: 
                   13858:             <dom></dom>         for scope type = domains
                   13859: 
                   13860:             <users>             for scope type = users
                   13861:              <user>
                   13862:               <uname></uname>
                   13863:               <udom></udom>
                   13864:              </user>
                   13865:             </users>
                   13866:            </scope> 
                   13867:               
                   13868:  Access data is also aggregated for each file in an additional key=value pair:
                   13869:  key -> path to file/file_name\0accesscontrol 
                   13870:  value -> reference to hash
                   13871:           hash contains key = value pairs
                   13872:           where key = uniqueID:scope_end_start
                   13873:                 value = UNIX time record was last updated
                   13874: 
                   13875:           Used to improve speed of look-ups of access controls for each file.  
                   13876:  
                   13877:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   13878: 
1.1172.2.13  raeburn  13879: =item *
                   13880: 
1.749     raeburn  13881: modify_access_controls():
                   13882: 
                   13883: Modifies access controls for a portfolio file
                   13884: Args
                   13885: 1. file name
                   13886: 2. reference to hash of required changes,
                   13887: 3. domain
                   13888: 4. username
                   13889:   where domain,username are the domain of the portfolio owner 
                   13890:   (either a user or a course) 
                   13891: 
                   13892: Returns:
                   13893: 1. result of additions or updates ('ok' or 'error', with error message). 
                   13894: 2. result of deletions ('ok' or 'error', with error message).
                   13895: 3. reference to hash of any new or updated access controls.
                   13896: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   13897:    key = integer (inbound ID)
1.1172.2.13  raeburn  13898:    value = uniqueID
                   13899: 
                   13900: =item *
                   13901: 
                   13902: get_timebased_id():
                   13903: 
                   13904: Attempts to get a unique timestamp-based suffix for use with items added to a
                   13905: course via the Course Editor (e.g., folders, composite pages,
                   13906: group bulletin boards).
                   13907: 
                   13908: Args: (first three required; six others optional)
                   13909: 
                   13910: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   13911:    docssequence, or name of group
                   13912: 
                   13913: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   13914:    e.g., num, boardids
                   13915: 
                   13916: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   13917:    file will be named nohist_namespace.db
                   13918: 
                   13919: 4. cdom: domain of course; default is current course domain from %env
                   13920: 
                   13921: 5. cnum: course number; default is current course number from %env
                   13922: 
                   13923: 6. idtype: set to concat if an additional digit is to be appended to the
                   13924:    unix timestamp to form the suffix, if the plain timestamp is already
                   13925:    in use.  Default is to not do this, but simply increment the unix
                   13926:    timestamp by 1 until a unique key is obtained.
                   13927: 
                   13928: 7. who: holder of locking key; defaults to user:domain for user.
                   13929: 
                   13930: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   13931:    retrying); default is 3.
                   13932: 
                   13933: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   13934: 
                   13935: Returns:
                   13936: 
                   13937: 1. suffix obtained (numeric)
                   13938: 
                   13939: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   13940: 
                   13941: 3. error: contains (localized) error message if an error occurred.
                   13942: 
1.747     albertel 13943: 
1.608     albertel 13944: =back
                   13945: 
1.243     albertel 13946: =head2 HTTP Helper Routines
                   13947: 
                   13948: =over 4
                   13949: 
1.191     harris41 13950: =item *
                   13951: 
                   13952: escape() : unpack non-word characters into CGI-compatible hex codes
                   13953: 
                   13954: =item *
                   13955: 
                   13956: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   13957: 
1.243     albertel 13958: =back
                   13959: 
                   13960: =head1 PRIVATE SUBROUTINES
                   13961: 
                   13962: =head2 Underlying communication routines (Shouldn't call)
                   13963: 
                   13964: =over 4
                   13965: 
                   13966: =item *
                   13967: 
                   13968: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   13969: 
                   13970: =item *
                   13971: 
                   13972: reply() : uses subreply to send a message to remote machine, logs all failures
                   13973: 
                   13974: =item *
                   13975: 
                   13976: critical() : passes a critical message to another server; if cannot
                   13977: get through then place message in connection buffer directory and
                   13978: returns con_delayed, if incapable of saving message, returns
                   13979: con_failed
                   13980: 
                   13981: =item *
                   13982: 
                   13983: reconlonc() : tries to reconnect lonc client processes.
                   13984: 
                   13985: =back
                   13986: 
                   13987: =head2 Resource Access Logging
                   13988: 
                   13989: =over 4
                   13990: 
                   13991: =item *
                   13992: 
                   13993: flushcourselogs() : flush (save) buffer logs and access logs
                   13994: 
                   13995: =item *
                   13996: 
                   13997: courselog($what) : save message for course in hash
                   13998: 
                   13999: =item *
                   14000: 
                   14001: courseacclog($what) : save message for course using &courselog().  Perform
                   14002: special processing for specific resource types (problems, exams, quizzes, etc).
                   14003: 
1.191     harris41 14004: =item *
                   14005: 
                   14006: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   14007: as a PerlChildExitHandler
1.243     albertel 14008: 
                   14009: =back
                   14010: 
                   14011: =head2 Other
                   14012: 
                   14013: =over 4
                   14014: 
                   14015: =item *
                   14016: 
                   14017: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 14018: 
                   14019: =back
                   14020: 
                   14021: =cut
1.877     foxr     14022: 

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