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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.88! raeburn     4: # $Id: lonnet.pm,v 1.1172.2.87 2016/11/15 20:56: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.1172.2.79  raeburn    92: use Time::HiRes qw( sleep gettimeofday tv_interval );
1.599     albertel   93: use Cache::Memcached;
1.676     albertel   94: use Digest::MD5;
1.790     albertel   95: use Math::Random;
1.1024    raeburn    96: use File::MMagic;
1.807     albertel   97: use LONCAPA qw(:DEFAULT :match);
1.740     www        98: use LONCAPA::Configuration;
1.1160    www        99: use LONCAPA::lonmetadata;
1.1172.2.22  raeburn   100: use LONCAPA::Lond;
1.1117    foxr      101: 
1.1090    raeburn   102: use File::Copy;
1.676     albertel  103: 
1.195     www       104: my $readit;
1.1172.2.79  raeburn   105: my $max_connection_retries = 20;     # Or some such value.
1.1       albertel  106: 
1.619     albertel  107: require Exporter;
                    108: 
                    109: our @ISA = qw (Exporter);
                    110: our @EXPORT = qw(%env);
                    111: 
1.1172.2.9  raeburn   112: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729     www       113: {
                    114:     my $logid;
1.1172.2.9  raeburn   115:     sub write_log {
                    116: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    117:         if ($context eq 'course') {
                    118:             if (($cnum eq '') || ($cdom eq '')) {
                    119:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    120:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    121:             }
1.957     raeburn   122:         }
1.1172.2.13  raeburn   123: 	$logid ++;
1.957     raeburn   124:         my $now = time();
                    125: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.1172.2.9  raeburn   126:         my $logentry = {
                    127:                          $id => {
                    128:                                   'exe_uname' => $env{'user.name'},
                    129:                                   'exe_udom'  => $env{'user.domain'},
                    130:                                   'exe_time'  => $now,
                    131:                                   'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    132:                                   'delflag'   => $delflag,
                    133:                                   'logentry'  => $storehash,
                    134:                                   'uname'     => $uname,
                    135:                                   'udom'      => $udom,
                    136:                                 }
                    137:                        };
                    138:         return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729     www       139:     }
                    140: }
1.1       albertel  141: 
1.163     harris41  142: sub logtouch {
                    143:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  144:     unless (-e "$execdir/logs/lonnet.log") {	
                    145: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  146: 	close $fh;
                    147:     }
                    148:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    149:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    150: }
                    151: 
1.1       albertel  152: sub logthis {
                    153:     my $message=shift;
                    154:     my $execdir=$perlvar{'lonDaemons'};
                    155:     my $now=time;
                    156:     my $local=localtime($now);
1.448     albertel  157:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986     foxr      158: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    159: 	print $fh $logstring;
1.448     albertel  160: 	close($fh);
                    161:     }
1.1       albertel  162:     return 1;
                    163: }
                    164: 
                    165: sub logperm {
                    166:     my $message=shift;
                    167:     my $execdir=$perlvar{'lonDaemons'};
                    168:     my $now=time;
                    169:     my $local=localtime($now);
1.448     albertel  170:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    171: 	print $fh "$now:$message:$local\n";
                    172: 	close($fh);
                    173:     }
1.1       albertel  174:     return 1;
                    175: }
                    176: 
1.850     albertel  177: sub create_connection {
1.853     albertel  178:     my ($hostname,$lonid) = @_;
1.851     albertel  179:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  180: 				     Type    => SOCK_STREAM,
                    181: 				     Timeout => 10);
                    182:     return 0 if (!$client);
1.890     albertel  183:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  184:     my $result = <$client>;
                    185:     chomp($result);
                    186:     return 1 if ($result eq 'done');
                    187:     return 0;
                    188: }
                    189: 
1.983     raeburn   190: sub get_server_timezone {
                    191:     my ($cnum,$cdom) = @_;
                    192:     my $home=&homeserver($cnum,$cdom);
                    193:     if ($home ne 'no_host') {
                    194:         my $cachetime = 24*3600;
                    195:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    196:         if (defined($cached)) {
                    197:             return $timezone;
                    198:         } else {
                    199:             my $timezone = &reply('servertimezone',$home);
                    200:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    201:         }
                    202:     }
                    203: }
1.850     albertel  204: 
1.1106    raeburn   205: sub get_server_distarch {
                    206:     my ($lonhost,$ignore_cache) = @_;
                    207:     if (defined($lonhost)) {
                    208:         if (!defined(&hostname($lonhost))) {
                    209:             return;
                    210:         }
                    211:         my $cachetime = 12*3600;
                    212:         if (!$ignore_cache) {
                    213:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    214:             if (defined($cached)) {
                    215:                 return $distarch;
                    216:             }
                    217:         }
                    218:         my $rep = &reply('serverdistarch',$lonhost);
                    219:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    220:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    221:                 $rep eq '') {
                    222:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    223:         }
                    224:     }
                    225:     return;
                    226: }
                    227: 
1.993     raeburn   228: sub get_server_loncaparev {
1.1073    raeburn   229:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   230:     if (defined($lonhost)) {
                    231:         if (!defined(&hostname($lonhost))) {
                    232:             undef($lonhost);
                    233:         }
                    234:     }
                    235:     if (!defined($lonhost)) {
                    236:         if (defined(&domain($dom,'primary'))) {
                    237:             $lonhost=&domain($dom,'primary');
                    238:             if ($lonhost eq 'no_host') {
                    239:                 undef($lonhost);
                    240:             }
                    241:         }
                    242:     }
                    243:     if (defined($lonhost)) {
1.1073    raeburn   244:         my $cachetime = 12*3600;
                    245:         if (!$ignore_cache) {
                    246:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    247:             if (defined($cached)) {
                    248:                 return $loncaparev;
                    249:             }
                    250:         }
                    251:         my ($answer,$loncaparev);
                    252:         my @ids=&current_machine_ids();
                    253:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    254:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   255:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   256:                 $loncaparev = $1;
                    257:             }
                    258:         } else {
                    259:             $answer = &reply('serverloncaparev',$lonhost);
                    260:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    261:                 if ($caller eq 'loncron') {
                    262:                     my $ua=new LWP::UserAgent;
1.1082    raeburn   263:                     $ua->timeout(4);
1.1073    raeburn   264:                     my $protocol = $protocol{$lonhost};
                    265:                     $protocol = 'http' if ($protocol ne 'https');
                    266:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
                    267:                     my $request=new HTTP::Request('GET',$url);
                    268:                     my $response=$ua->request($request);
                    269:                     unless ($response->is_error()) {
                    270:                         my $content = $response->content;
1.1081    raeburn   271:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   272:                             $loncaparev = $1;
                    273:                         }
                    274:                     }
                    275:                 } else {
                    276:                     $loncaparev = $loncaparevs{$lonhost};
                    277:                 }
1.1081    raeburn   278:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   279:                 $loncaparev = $1;
                    280:             }
1.993     raeburn   281:         }
1.1073    raeburn   282:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   283:     }
                    284: }
                    285: 
1.1074    raeburn   286: sub get_server_homeID {
                    287:     my ($hostname,$ignore_cache,$caller) = @_;
                    288:     unless ($ignore_cache) {
                    289:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    290:         if (defined($cached)) {
                    291:             return $serverhomeID;
                    292:         }
                    293:     }
                    294:     my $cachetime = 12*3600;
                    295:     my $serverhomeID;
                    296:     if ($caller eq 'loncron') { 
                    297:         my @machine_ids = &machine_ids($hostname);
                    298:         foreach my $id (@machine_ids) {
                    299:             my $response = &reply('serverhomeID',$id);
                    300:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    301:                 $serverhomeID = $response;
                    302:                 last;
                    303:             }
                    304:         }
                    305:         if ($serverhomeID eq '') {
                    306:             $serverhomeID = $machine_ids[-1];
                    307:         }
                    308:     } else {
                    309:         $serverhomeID = $serverhomeIDs{$hostname};
                    310:     }
                    311:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    312: }
                    313: 
1.1121    raeburn   314: sub get_remote_globals {
                    315:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   316:     my ($result,%returnhash,%whatneeded);
                    317:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   318:         foreach my $what (sort(keys(%{$whathash}))) {
                    319:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   320:             my ($response,$cached);
1.1121    raeburn   321:             unless ($ignore_cache) {
1.1125    raeburn   322:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   323:             }
                    324:             if (defined($cached)) {
1.1125    raeburn   325:                 $returnhash{$what} = $response;
1.1121    raeburn   326:             } else {
1.1125    raeburn   327:                 $whatneeded{$what} = 1;
1.1121    raeburn   328:             }
                    329:         }
1.1125    raeburn   330:         if (keys(%whatneeded) == 0) {
                    331:             $result = 'ok';
                    332:         } else {
1.1121    raeburn   333:             my $requested = &freeze_escape(\%whatneeded);
                    334:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   335:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    336:                 ($rep eq 'unknown_cmd')) {
                    337:                 $result = $rep;
                    338:             } else {
                    339:                 $result = 'ok';
1.1121    raeburn   340:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   341:                 foreach my $item (@pairs) {
                    342:                     my ($key,$value)=split(/=/,$item,2);
                    343:                     my $what = &unescape($key);
                    344:                     my $hashid = $lonhost.'-'.$what;
                    345:                     $returnhash{$what}=&thaw_unescape($value);
                    346:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   347:                 }
                    348:             }
                    349:         }
                    350:     }
1.1125    raeburn   351:     return ($result,\%returnhash);
1.1121    raeburn   352: }
                    353: 
1.1124    raeburn   354: sub remote_devalidate_cache {
1.1172.2.35  raeburn   355:     my ($lonhost,$cachekeys) = @_;
                    356:     my $items;
                    357:     return unless (ref($cachekeys) eq 'ARRAY');
                    358:     my $cachestr = join('&',@{$cachekeys});
                    359:     return &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124    raeburn   360: }
                    361: 
1.1       albertel  362: # -------------------------------------------------- Non-critical communication
                    363: sub subreply {
                    364:     my ($cmd,$server)=@_;
1.838     albertel  365:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      366:     #
                    367:     #  With loncnew process trimming, there's a timing hole between lonc server
                    368:     #  process exit and the master server picking up the listen on the AF_UNIX
                    369:     #  socket.  In that time interval, a lock file will exist:
                    370: 
                    371:     my $lockfile=$peerfile.".lock";
                    372:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
1.1172.2.79  raeburn   373: 	sleep(0.1);
1.549     foxr      374:     }
                    375:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      376:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      377:     #
1.550     foxr      378:     #   We'll give the connection a few tries before abandoning it.  If
                    379:     #   connection is not possible, we'll con_lost back to the client.
                    380:     #   
                    381:     my $client;
                    382:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    383: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    384: 				      Type    => SOCK_STREAM,
                    385: 				      Timeout => 10);
1.869     albertel  386: 	if ($client) {
1.550     foxr      387: 	    last;		# Connected!
1.850     albertel  388: 	} else {
1.853     albertel  389: 	    &create_connection(&hostname($server),$server);
1.550     foxr      390: 	}
1.1172.2.79  raeburn   391:         sleep(0.1);		# Try again later if failed connection.
1.550     foxr      392:     }
                    393:     my $answer;
                    394:     if ($client) {
1.704     albertel  395: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      396: 	$answer=<$client>;
                    397: 	if (!$answer) { $answer="con_lost"; }
                    398: 	chomp($answer);
                    399:     } else {
                    400: 	$answer = 'con_lost';	# Failed connection.
                    401:     }
1.1       albertel  402:     return $answer;
                    403: }
                    404: 
                    405: sub reply {
                    406:     my ($cmd,$server)=@_;
1.838     albertel  407:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  408:     my $answer=subreply($cmd,$server);
1.65      www       409:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  410:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       411:                 " $cmd to $server returned $answer</font>");
                    412:     }
1.1       albertel  413:     return $answer;
                    414: }
                    415: 
                    416: # ----------------------------------------------------------- Send USR1 to lonc
                    417: 
                    418: sub reconlonc {
1.891     albertel  419:     my ($lonid) = @_;
                    420:     if ($lonid) {
1.1172.2.72  raeburn   421:         my $hostname = &hostname($lonid);
1.891     albertel  422: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    423: 	if ($hostname && -e $peerfile) {
                    424: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    425: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    426: 					     Type    => SOCK_STREAM,
                    427: 					     Timeout => 10);
                    428: 	    if ($client) {
                    429: 		print $client ("reset_retries\n");
                    430: 		my $answer=<$client>;
                    431: 		#reset just this one.
                    432: 	    }
                    433: 	}
                    434: 	return;
                    435:     }
                    436: 
1.836     www       437:     &logthis("Trying to reconnect lonc");
1.1       albertel  438:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  439:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  440: 	my $loncpid=<$fh>;
                    441:         chomp($loncpid);
                    442:         if (kill 0 => $loncpid) {
                    443: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    444:             kill USR1 => $loncpid;
                    445:             sleep 1;
1.836     www       446:          } else {
1.12      www       447: 	    &logthis(
1.672     albertel  448:                "<font color=\"blue\">WARNING:".
1.12      www       449:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  450:         }
                    451:     } else {
1.836     www       452: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  453:     }
                    454: }
                    455: 
                    456: # ------------------------------------------------------ Critical communication
1.12      www       457: 
1.1       albertel  458: sub critical {
                    459:     my ($cmd,$server)=@_;
1.838     albertel  460:     unless (&hostname($server)) {
1.672     albertel  461:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       462:                " Critical message to unknown server ($server)</font>");
                    463:         return 'no_such_host';
                    464:     }
1.1       albertel  465:     my $answer=reply($cmd,$server);
                    466:     if ($answer eq 'con_lost') {
1.1172.2.72  raeburn   467: 	&reconlonc($server);
1.589     albertel  468: 	my $answer=reply($cmd,$server);
1.1       albertel  469:         if ($answer eq 'con_lost') {
                    470:             my $now=time;
                    471:             my $middlename=$cmd;
1.5       www       472:             $middlename=substr($middlename,0,16);
1.1       albertel  473:             $middlename=~s/\W//g;
                    474:             my $dfilename=
1.305     www       475:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    476:             $dumpcount++;
1.1       albertel  477:             {
1.448     albertel  478: 		my $dfh;
                    479: 		if (open($dfh,">$dfilename")) {
                    480: 		    print $dfh "$cmd\n"; 
                    481: 		    close($dfh);
                    482: 		}
1.1       albertel  483:             }
1.1172.2.79  raeburn   484:             sleep 1;
1.1       albertel  485:             my $wcmd='';
                    486:             {
1.448     albertel  487: 		my $dfh;
                    488: 		if (open($dfh,"<$dfilename")) {
                    489: 		    $wcmd=<$dfh>; 
                    490: 		    close($dfh);
                    491: 		}
1.1       albertel  492:             }
                    493:             chomp($wcmd);
1.7       www       494:             if ($wcmd eq $cmd) {
1.672     albertel  495: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       496:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  497:                 &logperm("D:$server:$cmd");
                    498: 	        return 'con_delayed';
                    499:             } else {
1.672     albertel  500:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       501:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  502:                 &logperm("F:$server:$cmd");
                    503:                 return 'con_failed';
                    504:             }
                    505:         }
                    506:     }
                    507:     return $answer;
1.405     albertel  508: }
                    509: 
1.755     albertel  510: # ------------------------------------------- check if return value is an error
                    511: 
                    512: sub error {
                    513:     my ($result) = @_;
1.756     albertel  514:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  515: 	if ($2 == 2) { return undef; }
                    516: 	return $1;
                    517:     }
                    518:     return undef;
                    519: }
                    520: 
1.783     albertel  521: sub convert_and_load_session_env {
                    522:     my ($lonidsdir,$handle)=@_;
                    523:     my @profile;
                    524:     {
1.917     albertel  525: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    526: 	if (!$opened) {
1.915     albertel  527: 	    return 0;
                    528: 	}
1.783     albertel  529: 	flock($idf,LOCK_SH);
                    530: 	@profile=<$idf>;
                    531: 	close($idf);
                    532:     }
                    533:     my %temp_env;
                    534:     foreach my $line (@profile) {
1.786     albertel  535: 	if ($line !~ m/=/) {
                    536: 	    return 0;
                    537: 	}
1.783     albertel  538: 	chomp($line);
                    539: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    540: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    541:     }
                    542:     unlink("$lonidsdir/$handle.id");
                    543:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    544: 	    0640)) {
                    545: 	%disk_env = %temp_env;
                    546: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    547: 	untie(%disk_env);
                    548:     }
1.786     albertel  549:     return 1;
1.783     albertel  550: }
                    551: 
1.374     www       552: # ------------------------------------------- Transfer profile into environment
1.780     albertel  553: my $env_loaded;
                    554: sub transfer_profile_to_env {
1.788     albertel  555:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    556:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       557: 
1.720     albertel  558:     if (!defined($lonidsdir)) {
                    559: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    560:     }
                    561:     if (!defined($handle)) {
                    562:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    563:     }
                    564: 
1.786     albertel  565:     my $convert;
                    566:     {
1.917     albertel  567:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    568: 	if (!$opened) {
1.915     albertel  569: 	    return;
                    570: 	}
1.786     albertel  571: 	flock($idf,LOCK_SH);
                    572: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    573: 		&GDBM_READER(),0640)) {
                    574: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    575: 	    untie(%disk_env);
                    576: 	} else {
                    577: 	    $convert = 1;
                    578: 	}
                    579:     }
                    580:     if ($convert) {
                    581: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    582: 	    &logthis("Failed to load session, or convert session.");
                    583: 	}
1.374     www       584:     }
1.783     albertel  585: 
1.786     albertel  586:     my %remove;
1.783     albertel  587:     while ( my $envname = each(%env) ) {
1.433     matthew   588:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    589:             if ($time < time-300) {
1.783     albertel  590:                 $remove{$key}++;
1.433     matthew   591:             }
                    592:         }
                    593:     }
1.783     albertel  594: 
1.619     albertel  595:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  596:     $env_loaded=1;
1.783     albertel  597:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   598:         &delenv($expired_key);
1.374     www       599:     }
1.1       albertel  600: }
                    601: 
1.916     albertel  602: # ---------------------------------------------------- Check for valid session 
                    603: sub check_for_valid_session {
1.1172.2.36  raeburn   604:     my ($r,$name,$userhashref) = @_;
1.916     albertel  605:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155    raeburn   606:     if ($name eq '') {
                    607:         $name = 'lonID';
                    608:     }
                    609:     my $lonid=$cookies{$name};
1.916     albertel  610:     return undef if (!$lonid);
                    611: 
                    612:     my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155    raeburn   613:     my $lonidsdir;
                    614:     if ($name eq 'lonDAV') {
                    615:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    616:     } else {
                    617:         $lonidsdir=$r->dir_config('lonIDsDir');
                    618:     }
1.916     albertel  619:     return undef if (!-e "$lonidsdir/$handle.id");
                    620: 
1.917     albertel  621:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    622:     return undef if (!$opened);
1.916     albertel  623: 
                    624:     flock($idf,LOCK_SH);
                    625:     my %disk_env;
                    626:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    627: 	    &GDBM_READER(),0640)) {
                    628: 	return undef;	
                    629:     }
                    630: 
                    631:     if (!defined($disk_env{'user.name'})
                    632: 	|| !defined($disk_env{'user.domain'})) {
                    633: 	return undef;
                    634:     }
1.1172.2.18  raeburn   635: 
1.1172.2.36  raeburn   636:     if (ref($userhashref) eq 'HASH') {
                    637:         $userhashref->{'name'} = $disk_env{'user.name'};
                    638:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1172.2.18  raeburn   639:     }
                    640: 
1.916     albertel  641:     return $handle;
                    642: }
                    643: 
1.830     albertel  644: sub timed_flock {
                    645:     my ($file,$lock_type) = @_;
                    646:     my $failed=0;
                    647:     eval {
                    648: 	local $SIG{__DIE__}='DEFAULT';
                    649: 	local $SIG{ALRM}=sub {
                    650: 	    $failed=1;
                    651: 	    die("failed lock");
                    652: 	};
                    653: 	alarm(13);
                    654: 	flock($file,$lock_type);
                    655: 	alarm(0);
                    656:     };
                    657:     if ($failed) {
                    658: 	return undef;
                    659:     } else {
                    660: 	return 1;
                    661:     }
                    662: }
                    663: 
1.5       www       664: # ---------------------------------------------------------- Append Environment
                    665: 
                    666: sub appenv {
1.949     raeburn   667:     my ($newenv,$roles) = @_;
                    668:     if (ref($newenv) eq 'HASH') {
                    669:         foreach my $key (keys(%{$newenv})) {
                    670:             my $refused = 0;
                    671: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    672:                 $refused = 1;
                    673:                 if (ref($roles) eq 'ARRAY') {
1.1172.2.40  raeburn   674:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   675:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    676:                         $refused = 0;
                    677:                     }
                    678:                 }
                    679:             }
                    680:             if ($refused) {
                    681:                 &logthis("<font color=\"blue\">WARNING: ".
                    682:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    683:                          .'</font>');
                    684: 	        delete($newenv->{$key});
                    685:             } else {
                    686:                 $env{$key}=$newenv->{$key};
                    687:             }
                    688:         }
                    689:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    690:         if ($opened
                    691: 	    && &timed_flock($env_file,LOCK_EX)
                    692: 	    &&
                    693: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    694: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    695: 	    while (my ($key,$value) = each(%{$newenv})) {
                    696: 	        $disk_env{$key} = $value;
                    697: 	    }
                    698: 	    untie(%disk_env);
1.35      www       699:         }
1.191     harris41  700:     }
1.56      www       701:     return 'ok';
                    702: }
                    703: # ----------------------------------------------------- Delete from Environment
                    704: 
                    705: sub delenv {
1.1104    raeburn   706:     my ($delthis,$regexp,$roles) = @_;
                    707:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    708:         my $refused = 1;
                    709:         if (ref($roles) eq 'ARRAY') {
                    710:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    711:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    712:                 $refused = 0;
                    713:             }
                    714:         }
                    715:         if ($refused) {
                    716:             &logthis("<font color=\"blue\">WARNING: ".
                    717:                      "Attempt to delete from environment ".$delthis);
                    718:             return 'error';
                    719:         }
1.56      www       720:     }
1.917     albertel  721:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    722:     if ($opened
1.915     albertel  723: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  724: 	&&
                    725: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    726: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  727: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   728: 	    if ($regexp) {
                    729:                 if ($key=~/^$delthis/) {
                    730:                     delete($env{$key});
                    731:                     delete($disk_env{$key});
                    732:                 } 
                    733:             } else {
                    734:                 if ($key=~/^\Q$delthis\E/) {
                    735: 		    delete($env{$key});
                    736: 		    delete($disk_env{$key});
                    737: 	        }
                    738:             }
1.448     albertel  739: 	}
1.783     albertel  740: 	untie(%disk_env);
1.5       www       741:     }
                    742:     return 'ok';
1.369     albertel  743: }
                    744: 
1.790     albertel  745: sub get_env_multiple {
                    746:     my ($name) = @_;
                    747:     my @values;
                    748:     if (defined($env{$name})) {
                    749:         # exists is it an array
                    750:         if (ref($env{$name})) {
                    751:             @values=@{ $env{$name} };
                    752:         } else {
                    753:             $values[0]=$env{$name};
                    754:         }
                    755:     }
                    756:     return(@values);
                    757: }
                    758: 
1.958     www       759: # ------------------------------------------------------------------- Locking
                    760: 
                    761: sub set_lock {
                    762:     my ($text)=@_;
                    763:     $locknum++;
                    764:     my $id=$$.'-'.$locknum;
                    765:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    766:              'session.lock.'.$id => $text});
                    767:     return $id;
                    768: }
                    769: 
                    770: sub get_locks {
                    771:     my $num=0;
                    772:     my %texts=();
                    773:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    774:        if ($lock=~/\w/) {
                    775:           $num++;
                    776:           $texts{$lock}=$env{'session.lock.'.$lock};
                    777:        }
                    778:    }
                    779:    return ($num,%texts);
                    780: }
                    781: 
                    782: sub remove_lock {
                    783:     my ($id)=@_;
                    784:     my $newlocks='';
                    785:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    786:        if (($lock=~/\w/) && ($lock ne $id)) {
                    787:           $newlocks.=','.$lock;
                    788:        }
                    789:     }
                    790:     &appenv({'session.locks' => $newlocks});
                    791:     &delenv('session.lock.'.$id);
                    792: }
                    793: 
                    794: sub remove_all_locks {
                    795:     my $activelocks=$env{'session.locks'};
                    796:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    797:        if ($lock=~/\w/) {
                    798:           &remove_lock($lock);
                    799:        }
                    800:     }
                    801: }
                    802: 
                    803: 
1.369     albertel  804: # ------------------------------------------ Find out current server userload
                    805: sub userload {
                    806:     my $numusers=0;
                    807:     {
                    808: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    809: 	my $filename;
                    810: 	my $curtime=time;
                    811: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  812: 	    next if ($filename eq '.' || $filename eq '..');
                    813: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  814: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  815: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  816: 	}
                    817: 	closedir(LONIDS);
                    818:     }
                    819:     my $userloadpercent=0;
                    820:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    821:     if ($maxuserload) {
1.371     albertel  822: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  823:     }
1.372     albertel  824:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  825:     return $userloadpercent;
1.283     www       826: }
                    827: 
1.1       albertel  828: # ------------------------------ Find server with least workload from spare.tab
1.11      www       829: 
1.1       albertel  830: sub spareserver {
1.1083    raeburn   831:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  832:     my $spare_server;
1.370     albertel  833:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  834:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    835:                                                      :  $userloadpercent;
1.1083    raeburn   836:     my ($uint_dom,$remotesessions);
                    837:     if (($udom ne '') && (&domain($udom) ne '')) {
                    838:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    839:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    840:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    841:         $remotesessions = $udomdefaults{'remotesessions'};
                    842:     }
1.1123    raeburn   843:     my $spareshash = &this_host_spares($udom);
                    844:     if (ref($spareshash) eq 'HASH') {
                    845:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    846:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1172.2.62  raeburn   847:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    848:                                              $try_server));
1.1123    raeburn   849: 	        ($spare_server, $lowest_load) =
                    850: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    851:             }
1.1083    raeburn   852:         }
1.784     albertel  853: 
1.1123    raeburn   854:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    855: 
                    856:         if (!$found_server) {
                    857:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    858: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1172.2.62  raeburn   859:                     next unless (&spare_can_host($udom,$uint_dom,
                    860:                                                  $remotesessions,$try_server));
1.1123    raeburn   861: 	            ($spare_server, $lowest_load) =
                    862: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    863:                 }
                    864: 	    }
                    865:         }
1.784     albertel  866:     }
                    867: 
                    868:     if (!$want_server_name) {
1.968     raeburn   869:         my $protocol = 'http';
                    870:         if ($protocol{$spare_server} eq 'https') {
                    871:             $protocol = $protocol{$spare_server};
                    872:         }
1.1001    raeburn   873:         if (defined($spare_server)) {
                    874:             my $hostname = &hostname($spare_server);
1.1083    raeburn   875:             if (defined($hostname)) {
1.1001    raeburn   876: 	        $spare_server = $protocol.'://'.$hostname;
                    877:             }
                    878:         }
1.784     albertel  879:     }
                    880:     return $spare_server;
                    881: }
                    882: 
                    883: sub compare_server_load {
1.1172.2.41  raeburn   884:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                    885: 
                    886:     if ($required) {
                    887:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                    888:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                    889:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                    890:         if (($major eq '' && $minor eq '') ||
                    891:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                    892:             return ($spare_server,$lowest_load);
                    893:         }
                    894:     }
1.784     albertel  895: 
                    896:     my $loadans     = &reply('load',    $try_server);
                    897:     my $userloadans = &reply('userload',$try_server);
                    898: 
                    899:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   900: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  901:     }
                    902: 
                    903:     my $load;
                    904:     if ($loadans =~ /\d/) {
                    905: 	if ($userloadans =~ /\d/) {
                    906: 	    #both are numbers, pick the bigger one
                    907: 	    $load = ($loadans > $userloadans) ? $loadans 
                    908: 		                              : $userloadans;
1.411     albertel  909: 	} else {
1.784     albertel  910: 	    $load = $loadans;
1.411     albertel  911: 	}
1.784     albertel  912:     } else {
                    913: 	$load = $userloadans;
                    914:     }
                    915: 
                    916:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    917: 	$spare_server = $try_server;
                    918: 	$lowest_load  = $load;
1.370     albertel  919:     }
1.784     albertel  920:     return ($spare_server,$lowest_load);
1.202     matthew   921: }
1.914     albertel  922: 
                    923: # --------------------------- ask offload servers if user already has a session
                    924: sub find_existing_session {
                    925:     my ($udom,$uname) = @_;
1.1123    raeburn   926:     my $spareshash = &this_host_spares($udom);
                    927:     if (ref($spareshash) eq 'HASH') {
                    928:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    929:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    930:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    931:             }
                    932:         }
                    933:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                    934:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                    935:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    936:             }
                    937:         }
1.914     albertel  938:     }
                    939:     return;
                    940: }
                    941: 
                    942: # -------------------------------- ask if server already has a session for user
                    943: sub has_user_session {
                    944:     my ($lonid,$udom,$uname) = @_;
                    945:     my $result = &reply(join(':','userhassession',
                    946: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    947:     return 1 if ($result eq 'ok');
                    948: 
                    949:     return 0;
                    950: }
                    951: 
1.1076    raeburn   952: # --------- determine least loaded server in a user's domain which allows login
                    953: 
                    954: sub choose_server {
1.1172.2.47  raeburn   955:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn   956:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn   957:     my %servers = &get_servers($udom);
1.1076    raeburn   958:     my $lowest_load = 30000;
1.1172.2.47  raeburn   959:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                    960:     if ($skiploadbal) {
                    961:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                    962:         unless (defined($cached)) {
                    963:             my $cachetime = 60*60*24;
                    964:             my %domconfig =
                    965:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                    966:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                    967:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                    968:                                            $cachetime);
                    969:             }
                    970:         }
                    971:     }
1.1076    raeburn   972:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn   973:         my $loginvia;
1.1172.2.47  raeburn   974:         if ($skiploadbal) {
                    975:             if (ref($balancers) eq 'HASH') {
                    976:                 next if (exists($balancers->{$lonhost}));
                    977:             }
                    978:         }
1.1115    raeburn   979:         if ($checkloginvia) {
                    980:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn   981:             if ($loginvia) {
                    982:                 my ($server,$path) = split(/:/,$loginvia);
                    983:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn   984:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn   985:                 if ($login_host eq $server) {
                    986:                     $portal_path = $path;
1.1151    raeburn   987:                     $isredirect = 1;
1.1116    raeburn   988:                 }
                    989:             } else {
                    990:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn   991:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn   992:                 if ($login_host eq $lonhost) {
                    993:                     $portal_path = '';
1.1151    raeburn   994:                     $isredirect = ''; 
1.1116    raeburn   995:                 }
                    996:             }
                    997:         } else {
1.1076    raeburn   998:             ($login_host, $lowest_load) =
1.1172.2.41  raeburn   999:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1000:         }
                   1001:     }
                   1002:     if ($login_host ne '') {
1.1116    raeburn  1003:         $hostname = &hostname($login_host);
1.1076    raeburn  1004:     }
1.1172.2.88! raeburn  1005:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076    raeburn  1006: }
                   1007: 
1.202     matthew  1008: # --------------------------------------------- Try to change a user's password
                   1009: 
                   1010: sub changepass {
1.799     raeburn  1011:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1012:     $currentpass = &escape($currentpass);
                   1013:     $newpass     = &escape($newpass);
1.1030    raeburn  1014:     my $lonhost = $perlvar{'lonHostID'};
                   1015:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1016: 		       $server);
                   1017:     if (! $answer) {
                   1018: 	&logthis("No reply on password change request to $server ".
                   1019: 		 "by $uname in domain $udom.");
                   1020:     } elsif ($answer =~ "^ok") {
                   1021:         &logthis("$uname in $udom successfully changed their password ".
                   1022: 		 "on $server.");
                   1023:     } elsif ($answer =~ "^pwchange_failure") {
                   1024: 	&logthis("$uname in $udom was unable to change their password ".
                   1025: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1026: 		 "or pwchange");
                   1027:     } elsif ($answer =~ "^non_authorized") {
                   1028:         &logthis("$uname in $udom did not get their password correct when ".
                   1029: 		 "attempting to change it on $server.");
                   1030:     } elsif ($answer =~ "^auth_mode_error") {
                   1031:         &logthis("$uname in $udom attempted to change their password despite ".
                   1032: 		 "not being locally or internally authenticated on $server.");
                   1033:     } elsif ($answer =~ "^unknown_user") {
                   1034:         &logthis("$uname in $udom attempted to change their password ".
                   1035: 		 "on $server but were unable to because $server is not ".
                   1036: 		 "their home server.");
                   1037:     } elsif ($answer =~ "^refused") {
                   1038: 	&logthis("$server refused to change $uname in $udom password because ".
                   1039: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1040:     } elsif ($answer =~ "invalid_client") {
                   1041:         &logthis("$server refused to change $uname in $udom password because ".
                   1042:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1043:     }
                   1044:     return $answer;
1.1       albertel 1045: }
                   1046: 
1.169     harris41 1047: # ----------------------- Try to determine user's current authentication scheme
                   1048: 
                   1049: sub queryauthenticate {
                   1050:     my ($uname,$udom)=@_;
1.456     albertel 1051:     my $uhome=&homeserver($uname,$udom);
                   1052:     if (!$uhome) {
                   1053: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1054: 	return 'no_host';
                   1055:     }
                   1056:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1057:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1058: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1059:     }
1.456     albertel 1060:     return $answer;
1.169     harris41 1061: }
                   1062: 
1.1       albertel 1063: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1064: 
1.1       albertel 1065: sub authenticate {
1.1073    raeburn  1066:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1067:     $upass=&escape($upass);
                   1068:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1069:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1070:     my $newhome;
1.836     www      1071:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1072: # Maybe the machine was offline and only re-appeared again recently?
                   1073:         &reconlonc();
                   1074: # One more
1.952     raeburn  1075: 	$uhome=&homeserver($uname,$udom,1);
                   1076:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1077:             if (defined(&domain($udom,'primary'))) {
                   1078:                 $newhome=&domain($udom,'primary');
                   1079:             }
                   1080:             if ($newhome ne '') {
                   1081:                 $uhome = $newhome;
                   1082:             }
                   1083:         }
1.836     www      1084: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1085: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1086: 	    return 'no_host';
                   1087:         }
1.1       albertel 1088:     }
1.1073    raeburn  1089:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1090:     if ($answer eq 'authorized') {
1.952     raeburn  1091:         if ($newhome) {
                   1092:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1093:             return 'no_account_on_host'; 
                   1094:         } else {
                   1095:             &logthis("User $uname at $udom authorized by $uhome");
                   1096:             return $uhome;
                   1097:         }
1.471     albertel 1098:     }
                   1099:     if ($answer eq 'non_authorized') {
                   1100: 	&logthis("User $uname at $udom rejected by $uhome");
                   1101: 	return 'no_host'; 
1.9       www      1102:     }
1.471     albertel 1103:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1104:     return 'no_host';
                   1105: }
                   1106: 
1.1073    raeburn  1107: sub can_host_session {
1.1074    raeburn  1108:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1109:     my $canhost = 1;
1.1074    raeburn  1110:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1111:     if (ref($remotesessions) eq 'HASH') {
                   1112:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1113:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1114:                 $canhost = 0;
                   1115:             } else {
                   1116:                 $canhost = 1;
                   1117:             }
                   1118:         }
                   1119:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1120:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1121:                 $canhost = 1;
                   1122:             } else {
                   1123:                 $canhost = 0;
                   1124:             }
                   1125:         }
                   1126:         if ($canhost) {
                   1127:             if ($remotesessions->{'version'} ne '') {
                   1128:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1129:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1130:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1131:                         my $major = $1;
                   1132:                         my $minor = $2;
                   1133:                         if (($major < $reqmajor ) ||
                   1134:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1135:                             $canhost = 0;
                   1136:                         }
                   1137:                     } else {
                   1138:                         $canhost = 0;
                   1139:                     }
                   1140:                 }
                   1141:             }
                   1142:         }
                   1143:     }
                   1144:     if ($canhost) {
                   1145:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1146:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1147:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1148:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1149:                 if (($uint_dom ne '') && 
                   1150:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1151:                     $canhost = 0;
                   1152:                 } else {
                   1153:                     $canhost = 1;
                   1154:                 }
                   1155:             }
                   1156:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1157:                 if (($uint_dom ne '') && 
                   1158:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1159:                     $canhost = 1;
                   1160:                 } else {
                   1161:                     $canhost = 0;
                   1162:                 }
                   1163:             }
                   1164:         }
                   1165:     }
                   1166:     return $canhost;
                   1167: }
                   1168: 
1.1083    raeburn  1169: sub spare_can_host {
                   1170:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1171:     my $canhost=1;
1.1172.2.62  raeburn  1172:     my $try_server_hostname = &hostname($try_server);
                   1173:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1174:     my $serverhomedom = &host_domain($serverhomeID);
                   1175:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1176:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1177:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1178:             $canhost = 0;
                   1179:         }
                   1180:     }
                   1181:     if (($canhost) && ($uint_dom)) {
                   1182:         my @intdoms;
                   1183:         my $internet_names = &get_internet_names($try_server);
                   1184:         if (ref($internet_names) eq 'ARRAY') {
                   1185:             @intdoms = @{$internet_names};
                   1186:         }
                   1187:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1188:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1189:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1190:                                          $remotesessions,
                   1191:                                          $defdomdefaults{'hostedsessions'});
                   1192:         }
1.1083    raeburn  1193:     }
                   1194:     return $canhost;
                   1195: }
                   1196: 
1.1123    raeburn  1197: sub this_host_spares {
                   1198:     my ($dom) = @_;
1.1126    raeburn  1199:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1200:     my @hosts = &current_machine_ids();
                   1201:     foreach my $lonhost (@hosts) {
                   1202:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1203:             $dom_in_use = $dom;
                   1204:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1205:             last;
                   1206:         }
                   1207:     }
1.1126    raeburn  1208:     if ($dom_in_use ne '') {
                   1209:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1210:     }
                   1211:     if (ref($result) ne 'HASH') {
                   1212:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1213:         $dom_in_use = &host_domain($lonhost_in_use);
                   1214:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1215:         if (ref($result) ne 'HASH') {
                   1216:             $result = \%spareid;
                   1217:         }
                   1218:     }
                   1219:     return $result;
                   1220: }
                   1221: 
                   1222: sub spares_for_offload  {
                   1223:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1224:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1225:     if (defined($cached)) {
                   1226:         return $result;
                   1227:     } else {
1.1126    raeburn  1228:         my $cachetime = 60*60*24;
                   1229:         my %domconfig =
                   1230:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1231:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1232:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1233:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1234:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1235:                 }
                   1236:             }
                   1237:         }
                   1238:     }
1.1126    raeburn  1239:     return;
1.1123    raeburn  1240: }
                   1241: 
1.1129    raeburn  1242: sub get_lonbalancer_config {
                   1243:     my ($servers) = @_;
                   1244:     my ($currbalancer,$currtargets);
                   1245:     if (ref($servers) eq 'HASH') {
                   1246:         foreach my $server (keys(%{$servers})) {
                   1247:             my %what = (
                   1248:                          spareid => 1,
                   1249:                          perlvar => 1,
                   1250:                        );
                   1251:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1252:             if ($result eq 'ok') {
                   1253:                 if (ref($returnhash) eq 'HASH') {
                   1254:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1255:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1256:                             $currbalancer = $server;
                   1257:                             $currtargets = {};
                   1258:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1259:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1260:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1261:                                 }
                   1262:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1263:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1264:                                 }
                   1265:                             }
                   1266:                             last;
                   1267:                         }
                   1268:                     }
                   1269:                 }
                   1270:             }
                   1271:         }
                   1272:     }
                   1273:     return ($currbalancer,$currtargets);
                   1274: }
                   1275: 
                   1276: sub check_loadbalancing {
1.1172.2.88! raeburn  1277:     my ($uname,$udom,$caller) = @_;
1.1172.2.12  raeburn  1278:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
                   1279:         $rule_in_effect,$offloadto,$otherserver);
1.1129    raeburn  1280:     my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4  raeburn  1281:     my @hosts = &current_machine_ids();
1.1129    raeburn  1282:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1283:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1284:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1285:     my $serverhomedom = &host_domain($lonhost);
1.1172.2.75  raeburn  1286:     my $domneedscache; 
1.1129    raeburn  1287:     my $cachetime = 60*60*24;
                   1288: 
                   1289:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1290:         $dom_in_use = $udom;
                   1291:         $homeintdom = 1;
                   1292:     } else {
                   1293:         $dom_in_use = $serverhomedom;
                   1294:     }
                   1295:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1296:     unless (defined($cached)) {
                   1297:         my %domconfig =
                   1298:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1299:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1300:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1172.2.75  raeburn  1301:         } else {
                   1302:             $domneedscache = $dom_in_use;
1.1129    raeburn  1303:         }
                   1304:     }
                   1305:     if (ref($result) eq 'HASH') {
1.1172.2.12  raeburn  1306:         ($is_balancer,$currtargets,$currrules) =
                   1307:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1308:         if ($is_balancer) {
                   1309:             if (ref($currrules) eq 'HASH') {
                   1310:                 if ($homeintdom) {
                   1311:                     if ($uname ne '') {
                   1312:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1313:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1314:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1315:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1316:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1317:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1318:                             }
                   1319:                         }
                   1320:                         if ($rule_in_effect eq '') {
                   1321:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1322:                             if ($userenv{'inststatus'} ne '') {
                   1323:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1324:                                 my ($othertitle,$usertypes,$types) =
                   1325:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1326:                                 if (ref($types) eq 'ARRAY') {
                   1327:                                     foreach my $type (@{$types}) {
                   1328:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1329:                                             if (exists($currrules->{$type})) {
                   1330:                                                 $rule_in_effect = $currrules->{$type};
                   1331:                                             }
                   1332:                                         }
                   1333:                                     }
                   1334:                                 }
                   1335:                             } else {
                   1336:                                 if (exists($currrules->{'default'})) {
                   1337:                                     $rule_in_effect = $currrules->{'default'};
                   1338:                                 }
                   1339:                             }
                   1340:                         }
                   1341:                     } else {
                   1342:                         if (exists($currrules->{'default'})) {
                   1343:                             $rule_in_effect = $currrules->{'default'};
                   1344:                         }
                   1345:                     }
                   1346:                 } else {
                   1347:                     if ($currrules->{'_LC_external'} ne '') {
                   1348:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1349:                     }
                   1350:                 }
                   1351:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1352:                                                        $uname,$udom);
                   1353:             }
                   1354:         }
                   1355:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35  raeburn  1356:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1357:         unless (defined($cached)) {
                   1358:             my %domconfig =
                   1359:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1360:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1172.2.75  raeburn  1361:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1362:             } else {
                   1363:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1364:             }
                   1365:         }
                   1366:         if (ref($result) eq 'HASH') {
1.1172.2.12  raeburn  1367:             ($is_balancer,$currtargets,$currrules) =
                   1368:                 &check_balancer_result($result,@hosts);
                   1369:             if ($is_balancer) {
1.1129    raeburn  1370:                 if (ref($currrules) eq 'HASH') {
                   1371:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1372:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1373:                     }
                   1374:                 }
                   1375:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1376:                                                        $uname,$udom);
                   1377:             }
                   1378:         } else {
                   1379:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1380:                 $is_balancer = 1;
                   1381:                 $offloadto = &this_host_spares($dom_in_use);
                   1382:             }
1.1172.2.75  raeburn  1383:             unless (defined($cached)) {
                   1384:                 $domneedscache = $serverhomedom;
                   1385:             }
1.1129    raeburn  1386:         }
                   1387:     } else {
                   1388:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1389:             $is_balancer = 1;
                   1390:             $offloadto = &this_host_spares($dom_in_use);
                   1391:         }
1.1172.2.75  raeburn  1392:         unless (defined($cached)) {
                   1393:             $domneedscache = $serverhomedom;
                   1394:         }
                   1395:     }
                   1396:     if ($domneedscache) {
                   1397:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1398:     }
1.1172.2.5  raeburn  1399:     if ($is_balancer) {
                   1400:         my $lowest_load = 30000;
                   1401:         if (ref($offloadto) eq 'HASH') {
                   1402:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1403:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1404:                     ($otherserver,$lowest_load) =
                   1405:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1406:                 }
1.1129    raeburn  1407:             }
1.1172.2.5  raeburn  1408:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1409: 
1.1172.2.5  raeburn  1410:             if (!$found_server) {
                   1411:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1412:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1413:                         ($otherserver,$lowest_load) =
                   1414:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1415:                     }
                   1416:                 }
                   1417:             }
                   1418:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1419:             if (@{$offloadto} == 1) {
                   1420:                 $otherserver = $offloadto->[0];
                   1421:             } elsif (@{$offloadto} > 1) {
                   1422:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1423:                     ($otherserver,$lowest_load) =
                   1424:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1425:                 }
                   1426:             }
                   1427:         }
1.1172.2.88! raeburn  1428:         unless ($caller eq 'login') {
        !          1429:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
        !          1430:                 $is_balancer = 0;
        !          1431:                 if ($uname ne '' && $udom ne '') {
        !          1432:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1.1172.2.5  raeburn  1433: 
1.1172.2.88! raeburn  1434:                         &appenv({'user.loadbalexempt'     => $lonhost,
        !          1435:                                  'user.loadbalcheck.time' => time});
        !          1436:                     }
1.1172.2.5  raeburn  1437:                 }
1.1129    raeburn  1438:             }
                   1439:         }
                   1440:     }
                   1441:     return ($is_balancer,$otherserver);
                   1442: }
                   1443: 
1.1172.2.12  raeburn  1444: sub check_balancer_result {
                   1445:     my ($result,@hosts) = @_;
                   1446:     my ($is_balancer,$currtargets,$currrules);
                   1447:     if (ref($result) eq 'HASH') {
                   1448:         if ($result->{'lonhost'} ne '') {
                   1449:             my $currbalancer = $result->{'lonhost'};
                   1450:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1451:                 $is_balancer = 1;
                   1452:                 $currtargets = $result->{'targets'};
                   1453:                 $currrules = $result->{'rules'};
                   1454:             }
                   1455:         } else {
                   1456:             foreach my $key (keys(%{$result})) {
                   1457:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1458:                     (ref($result->{$key}) eq 'HASH')) {
                   1459:                     $is_balancer = 1;
                   1460:                     $currrules = $result->{$key}{'rules'};
                   1461:                     $currtargets = $result->{$key}{'targets'};
                   1462:                     last;
                   1463:                 }
                   1464:             }
                   1465:         }
                   1466:     }
                   1467:     return ($is_balancer,$currtargets,$currrules);
                   1468: }
                   1469: 
1.1129    raeburn  1470: sub get_loadbalancer_targets {
                   1471:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1472:     my $offloadto;
1.1172.2.4  raeburn  1473:     if ($rule_in_effect eq 'none') {
                   1474:         return [$perlvar{'lonHostID'}];
                   1475:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1476:         $offloadto = $currtargets;
                   1477:     } else {
                   1478:         if ($rule_in_effect eq 'homeserver') {
                   1479:             my $homeserver = &homeserver($uname,$udom);
                   1480:             if ($homeserver ne 'no_host') {
                   1481:                 $offloadto = [$homeserver];
                   1482:             }
                   1483:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1484:             my %domconfig =
                   1485:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1486:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1487:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1488:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1489:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1490:                     }
                   1491:                 }
                   1492:             } else {
1.1172.2.7  raeburn  1493:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1494:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1495:                 if (&hostname($remotebalancer) ne '') {
                   1496:                     $offloadto = [$remotebalancer];
                   1497:                 }
                   1498:             }
                   1499:         } elsif (&hostname($rule_in_effect) ne '') {
                   1500:             $offloadto = [$rule_in_effect];
                   1501:         }
                   1502:     }
                   1503:     return $offloadto;
                   1504: }
                   1505: 
1.1127    raeburn  1506: sub internet_dom_servers {
                   1507:     my ($dom) = @_;
                   1508:     my (%uniqservers,%servers);
                   1509:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1510:     my @machinedoms = &machine_domains($primaryserver);
                   1511:     foreach my $mdom (@machinedoms) {
                   1512:         my %currservers = %servers;
                   1513:         my %server = &get_servers($mdom);
                   1514:         %servers = (%currservers,%server);
                   1515:     }
                   1516:     my %by_hostname;
                   1517:     foreach my $id (keys(%servers)) {
                   1518:         push(@{$by_hostname{$servers{$id}}},$id);
                   1519:     }
                   1520:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1521:         if (@{$by_hostname{$hostname}} > 1) {
                   1522:             my $match = 0;
                   1523:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1524:                 if (&host_domain($id) eq $dom) {
                   1525:                     $uniqservers{$id} = $hostname;
                   1526:                     $match = 1;
                   1527:                 }
                   1528:             }
                   1529:             unless ($match) {
                   1530:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1531:             }
                   1532:         } else {
                   1533:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1534:         }
                   1535:     }
                   1536:     return %uniqservers;
                   1537: }
                   1538: 
1.1       albertel 1539: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1540: 
1.599     albertel 1541: my %homecache;
1.1       albertel 1542: sub homeserver {
1.230     stredwic 1543:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1544:     my $index="$uname:$udom";
1.426     albertel 1545: 
1.599     albertel 1546:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1547: 
                   1548:     my %servers = &get_servers($udom,'library');
                   1549:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1550:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1551: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1552: 
                   1553: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1554: 	if ($answer eq 'found') {
                   1555: 	    delete($badServerCache{$tryserver}); 
                   1556: 	    return $homecache{$index}=$tryserver;
                   1557: 	} elsif ($answer eq 'no_host') {
                   1558: 	    $badServerCache{$tryserver}=1;
                   1559: 	}
1.1       albertel 1560:     }    
                   1561:     return 'no_host';
1.70      www      1562: }
                   1563: 
                   1564: # ------------------------------------- Find the usernames behind a list of IDs
                   1565: 
                   1566: sub idget {
                   1567:     my ($udom,@ids)=@_;
                   1568:     my %returnhash=();
                   1569:     
1.841     albertel 1570:     my %servers = &get_servers($udom,'library');
                   1571:     foreach my $tryserver (keys(%servers)) {
1.1172.2.73  raeburn  1572: 	my $idlist=join('&', map { &escape($_); } @ids);
1.841     albertel 1573: 	$idlist=~tr/A-Z/a-z/; 
                   1574: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1575: 	my @answer=();
                   1576: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1577: 	    @answer=split(/\&/,$reply);
                   1578: 	}                    ;
                   1579: 	my $i;
                   1580: 	for ($i=0;$i<=$#ids;$i++) {
                   1581: 	    if ($answer[$i]) {
1.1172.2.73  raeburn  1582: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.841     albertel 1583: 	    } 
                   1584: 	}
                   1585:     } 
1.70      www      1586:     return %returnhash;
                   1587: }
                   1588: 
                   1589: # ------------------------------------- Find the IDs behind a list of usernames
                   1590: 
                   1591: sub idrget {
                   1592:     my ($udom,@unames)=@_;
                   1593:     my %returnhash=();
1.800     albertel 1594:     foreach my $uname (@unames) {
                   1595:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1596:     }
1.70      www      1597:     return %returnhash;
                   1598: }
                   1599: 
                   1600: # ------------------------------- Store away a list of names and associated IDs
                   1601: 
                   1602: sub idput {
                   1603:     my ($udom,%ids)=@_;
                   1604:     my %servers=();
1.800     albertel 1605:     foreach my $uname (keys(%ids)) {
                   1606: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1607:         my $uhom=&homeserver($uname,$udom);
1.70      www      1608:         if ($uhom ne 'no_host') {
1.800     albertel 1609:             my $id=&escape($ids{$uname});
1.70      www      1610:             $id=~tr/A-Z/a-z/;
1.800     albertel 1611:             my $esc_unam=&escape($uname);
1.70      www      1612: 	    if ($servers{$uhom}) {
1.800     albertel 1613: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1614:             } else {
1.800     albertel 1615:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1616:             }
                   1617:         }
1.191     harris41 1618:     }
1.800     albertel 1619:     foreach my $server (keys(%servers)) {
                   1620:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1621:     }
1.344     www      1622: }
                   1623: 
1.1172.2.30  raeburn  1624: # ---------------------------------------- Delete unwanted IDs from ids.db file
                   1625: 
                   1626: sub iddel {
                   1627:     my ($udom,$idshashref,$uhome)=@_;
                   1628:     my %result=();
                   1629:     unless (ref($idshashref) eq 'HASH') {
                   1630:         return %result;
                   1631:     }
                   1632:     my %servers=();
                   1633:     while (my ($id,$uname) = each(%{$idshashref})) {
                   1634:         my $uhom;
                   1635:         if ($uhome) {
                   1636:             $uhom = $uhome;
                   1637:         } else {
                   1638:             $uhom=&homeserver($uname,$udom);
                   1639:         }
                   1640:         if ($uhom ne 'no_host') {
                   1641:             if ($servers{$uhom}) {
                   1642:                 $servers{$uhom}.='&'.&escape($id);
                   1643:             } else {
                   1644:                 $servers{$uhom}=&escape($id);
                   1645:             }
                   1646:         }
                   1647:     }
                   1648:     foreach my $server (keys(%servers)) {
                   1649:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1650:     }
                   1651:     return %result;
                   1652: }
                   1653: 
1.1023    raeburn  1654: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1655: sub dump_dom {
1.1165    droeschl 1656:     my ($namespace, $udom, $regexp) = @_;
                   1657: 
                   1658:     $udom ||= $env{'user.domain'};
                   1659: 
                   1660:     return () unless $udom;
                   1661: 
                   1662:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1663: }
                   1664: 
1.1023    raeburn  1665: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1666: 
                   1667: sub get_dom {
1.860     raeburn  1668:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1172.2.57  raeburn  1669:     return if ($udom eq 'public');
1.806     raeburn  1670:     my $items='';
                   1671:     foreach my $item (@$storearr) {
                   1672:         $items.=&escape($item).'&';
                   1673:     }
                   1674:     $items=~s/\&$//;
1.860     raeburn  1675:     if (!$udom) {
                   1676:         $udom=$env{'user.domain'};
1.1172.2.57  raeburn  1677:         return if ($udom eq 'public');
1.860     raeburn  1678:         if (defined(&domain($udom,'primary'))) {
                   1679:             $uhome=&domain($udom,'primary');
                   1680:         } else {
1.874     albertel 1681:             undef($uhome);
1.860     raeburn  1682:         }
                   1683:     } else {
                   1684:         if (!$uhome) {
                   1685:             if (defined(&domain($udom,'primary'))) {
                   1686:                 $uhome=&domain($udom,'primary');
                   1687:             }
                   1688:         }
                   1689:     }
                   1690:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1691:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1692:         my %returnhash;
1.875     albertel 1693:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1694:             return %returnhash;
                   1695:         }
1.806     raeburn  1696:         my @pairs=split(/\&/,$rep);
                   1697:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1698:             return @pairs;
                   1699:         }
                   1700:         my $i=0;
                   1701:         foreach my $item (@$storearr) {
                   1702:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1703:             $i++;
                   1704:         }
                   1705:         return %returnhash;
                   1706:     } else {
1.880     banghart 1707:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1708:     }
                   1709: }
                   1710: 
                   1711: # -------------------------------------------- put items in domain db files 
                   1712: 
                   1713: sub put_dom {
1.860     raeburn  1714:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1715:     if (!$udom) {
                   1716:         $udom=$env{'user.domain'};
                   1717:         if (defined(&domain($udom,'primary'))) {
                   1718:             $uhome=&domain($udom,'primary');
                   1719:         } else {
1.874     albertel 1720:             undef($uhome);
1.860     raeburn  1721:         }
                   1722:     } else {
                   1723:         if (!$uhome) {
                   1724:             if (defined(&domain($udom,'primary'))) {
                   1725:                 $uhome=&domain($udom,'primary');
                   1726:             }
                   1727:         }
                   1728:     } 
                   1729:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1730:         my $items='';
                   1731:         foreach my $item (keys(%$storehash)) {
                   1732:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1733:         }
                   1734:         $items=~s/\&$//;
                   1735:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1736:     } else {
1.860     raeburn  1737:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1738:     }
                   1739: }
                   1740: 
1.1023    raeburn  1741: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1742: sub newput_dom {
1.1023    raeburn  1743:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1744:     my $result;
                   1745:     if (!$udom) {
                   1746:         $udom=$env{'user.domain'};
                   1747:     }
1.1023    raeburn  1748:     if ($udom) {
                   1749:         my $uname = &get_domainconfiguser($udom);
                   1750:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1751:     }
                   1752:     return $result;
                   1753: }
                   1754: 
1.1023    raeburn  1755: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1756: sub del_dom {
1.1023    raeburn  1757:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1758:     if (ref($storearr) eq 'ARRAY') {
                   1759:         if (!$udom) {
                   1760:             $udom=$env{'user.domain'};
                   1761:         }
1.1023    raeburn  1762:         if ($udom) {
                   1763:             my $uname = &get_domainconfiguser($udom); 
                   1764:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1765:         }
                   1766:     }
                   1767: }
                   1768: 
1.1023    raeburn  1769: # ----------------------------------construct domainconfig user for a domain 
                   1770: sub get_domainconfiguser {
                   1771:     my ($udom) = @_;
                   1772:     return $udom.'-domainconfig';
                   1773: }
                   1774: 
1.837     raeburn  1775: sub retrieve_inst_usertypes {
                   1776:     my ($udom) = @_;
                   1777:     my (%returnhash,@order);
1.989     raeburn  1778:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1779:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1780:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44  raeburn  1781:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  1782:     } else {
                   1783:         if (defined(&domain($udom,'primary'))) {
                   1784:             my $uhome=&domain($udom,'primary');
                   1785:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1786:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44  raeburn  1787:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  1788:                 return (\%returnhash,\@order);
                   1789:             }
                   1790:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1791:             my @pairs=split(/\&/,$hashitems);
                   1792:             foreach my $item (@pairs) {
                   1793:                 my ($key,$value)=split(/=/,$item,2);
                   1794:                 $key = &unescape($key);
                   1795:                 next if ($key =~ /^error: 2 /);
                   1796:                 $returnhash{$key}=&thaw_unescape($value);
                   1797:             }
                   1798:             my @esc_order = split(/\&/,$orderitems);
                   1799:             foreach my $item (@esc_order) {
                   1800:                 push(@order,&unescape($item));
                   1801:             }
                   1802:         } else {
1.1172.2.44  raeburn  1803:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  1804:         }
1.1172.2.44  raeburn  1805:         return (\%returnhash,\@order);
1.837     raeburn  1806:     }
                   1807: }
                   1808: 
1.868     raeburn  1809: sub is_domainimage {
                   1810:     my ($url) = @_;
1.1172.2.74  raeburn  1811:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  1812:         if (&domain($1) ne '') {
                   1813:             return '1';
                   1814:         }
                   1815:     }
                   1816:     return;
                   1817: }
                   1818: 
1.899     raeburn  1819: sub inst_directory_query {
                   1820:     my ($srch) = @_;
                   1821:     my $udom = $srch->{'srchdomain'};
                   1822:     my %results;
                   1823:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1824:     my $outcome;
1.899     raeburn  1825:     if ($homeserver ne '') {
1.904     albertel 1826: 	my $queryid=&reply("querysend:instdirsearch:".
                   1827: 			   &escape($srch->{'srchby'}).':'.
                   1828: 			   &escape($srch->{'srchterm'}).':'.
                   1829: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1830: 	my $host=&hostname($homeserver);
                   1831: 	if ($queryid !~/^\Q$host\E\_/) {
                   1832: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1833: 	    return;
                   1834: 	}
                   1835: 	my $response = &get_query_reply($queryid);
                   1836: 	my $maxtries = 5;
                   1837: 	my $tries = 1;
                   1838: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1839: 	    $response = &get_query_reply($queryid);
                   1840: 	    $tries ++;
                   1841: 	}
                   1842: 
                   1843:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1844:             if ($response eq 'unavailable') {
                   1845:                 $outcome = $response;
                   1846:             } else {
                   1847:                 $outcome = 'ok';
                   1848:                 my @matches = split(/\n/,$response);
                   1849:                 foreach my $match (@matches) {
                   1850:                     my ($key,$value) = split(/=/,$match);
                   1851:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1852:                 }
1.899     raeburn  1853:             }
                   1854:         }
                   1855:     }
1.909     raeburn  1856:     return ($outcome,%results);
1.899     raeburn  1857: }
                   1858: 
                   1859: sub usersearch {
                   1860:     my ($srch) = @_;
                   1861:     my $dom = $srch->{'srchdomain'};
                   1862:     my %results;
                   1863:     my %libserv = &all_library();
                   1864:     my $query = 'usersearch';
                   1865:     foreach my $tryserver (keys(%libserv)) {
                   1866:         if (&host_domain($tryserver) eq $dom) {
                   1867:             my $host=&hostname($tryserver);
                   1868:             my $queryid=
1.911     raeburn  1869:                 &reply("querysend:".&escape($query).':'.
                   1870:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1871:                        &escape($srch->{'srchtype'}).':'.
                   1872:                        &escape($srch->{'srchterm'}),$tryserver);
                   1873:             if ($queryid !~/^\Q$host\E\_/) {
                   1874:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1875:                 next;
1.899     raeburn  1876:             }
                   1877:             my $reply = &get_query_reply($queryid);
                   1878:             my $maxtries = 1;
                   1879:             my $tries = 1;
                   1880:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1881:                 $reply = &get_query_reply($queryid);
                   1882:                 $tries ++;
                   1883:             }
                   1884:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1885:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1886:             } else {
1.911     raeburn  1887:                 my @matches;
                   1888:                 if ($reply =~ /\n/) {
                   1889:                     @matches = split(/\n/,$reply);
                   1890:                 } else {
                   1891:                     @matches = split(/\&/,$reply);
                   1892:                 }
1.899     raeburn  1893:                 foreach my $match (@matches) {
                   1894:                     my ($uname,$udom,%userhash);
1.911     raeburn  1895:                     foreach my $entry (split(/:/,$match)) {
                   1896:                         my ($key,$value) =
                   1897:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1898:                         $userhash{$key} = $value;
                   1899:                         if ($key eq 'username') {
                   1900:                             $uname = $value;
                   1901:                         } elsif ($key eq 'domain') {
                   1902:                             $udom = $value;
1.911     raeburn  1903:                         }
1.899     raeburn  1904:                     }
                   1905:                     $results{$uname.':'.$udom} = \%userhash;
                   1906:                 }
                   1907:             }
                   1908:         }
                   1909:     }
                   1910:     return %results;
                   1911: }
                   1912: 
1.912     raeburn  1913: sub get_instuser {
                   1914:     my ($udom,$uname,$id) = @_;
                   1915:     my $homeserver = &domain($udom,'primary');
                   1916:     my ($outcome,%results);
                   1917:     if ($homeserver ne '') {
                   1918:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1919:                            &escape($id).':'.&escape($udom),$homeserver);
                   1920:         my $host=&hostname($homeserver);
                   1921:         if ($queryid !~/^\Q$host\E\_/) {
                   1922:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1923:             return;
                   1924:         }
                   1925:         my $response = &get_query_reply($queryid);
                   1926:         my $maxtries = 5;
                   1927:         my $tries = 1;
                   1928:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1929:             $response = &get_query_reply($queryid);
                   1930:             $tries ++;
                   1931:         }
                   1932:         if (!&error($response) && $response ne 'refused') {
                   1933:             if ($response eq 'unavailable') {
                   1934:                 $outcome = $response;
                   1935:             } else {
                   1936:                 $outcome = 'ok';
                   1937:                 my @matches = split(/\n/,$response);
                   1938:                 foreach my $match (@matches) {
                   1939:                     my ($key,$value) = split(/=/,$match);
                   1940:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1941:                 }
                   1942:             }
                   1943:         }
                   1944:     }
                   1945:     my %userinfo;
                   1946:     if (ref($results{$uname}) eq 'HASH') {
                   1947:         %userinfo = %{$results{$uname}};
                   1948:     } 
                   1949:     return ($outcome,%userinfo);
                   1950: }
                   1951: 
1.1172.2.69  raeburn  1952: sub get_multiple_instusers {
                   1953:     my ($udom,$users,$caller) = @_;
                   1954:     my ($outcome,$results);
                   1955:     if (ref($users) eq 'HASH') {
                   1956:         my $count = keys(%{$users});
                   1957:         my $requested = &freeze_escape($users);
                   1958:         my $homeserver = &domain($udom,'primary');
                   1959:         if ($homeserver ne '') {
                   1960:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   1961:             my $host=&hostname($homeserver);
                   1962:             if ($queryid !~/^\Q$host\E\_/) {
                   1963:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   1964:                          ' for host: '.$homeserver.'in domain '.$udom);
                   1965:                 return ($outcome,$results);
                   1966:             }
                   1967:             my $response = &get_query_reply($queryid);
                   1968:             my $maxtries = 5;
                   1969:             if ($count > 100) {
                   1970:                 $maxtries = 1+int($count/20);
                   1971:             }
                   1972:             my $tries = 1;
                   1973:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   1974:                 $response = &get_query_reply($queryid);
                   1975:                 $tries ++;
                   1976:             }
                   1977:             if ($response eq '') {
                   1978:                 $results = {};
                   1979:                 foreach my $key (keys(%{$users})) {
                   1980:                     my ($uname,$id);
                   1981:                     if ($caller eq 'id') {
                   1982:                         $id = $key;
                   1983:                     } else {
                   1984:                         $uname = $key;
                   1985:                     }
                   1986:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
                   1987:                     $outcome = $resp;
                   1988:                     if ($resp eq 'ok') {
                   1989:                         %{$results} = (%{$results}, %info);
                   1990:                     } else {
                   1991:                         last;
                   1992:                     }
                   1993:                 }
                   1994:             } elsif(!&error($response) && ($response ne 'refused')) {
                   1995:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   1996:                     $outcome = $response;
                   1997:                 } else {
                   1998:                     ($outcome,my $userdata) = split(/=/,$response,2);
                   1999:                     if ($outcome eq 'ok') {
                   2000:                         $results = &thaw_unescape($userdata);
                   2001:                     }
                   2002:                 }
                   2003:             }
                   2004:         }
                   2005:     }
                   2006:     return ($outcome,$results);
                   2007: }
                   2008: 
1.912     raeburn  2009: sub inst_rulecheck {
1.923     raeburn  2010:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2011:     my %returnhash;
                   2012:     if ($udom ne '') {
                   2013:         if (ref($rules) eq 'ARRAY') {
                   2014:             @{$rules} = map {&escape($_);} (@{$rules});
                   2015:             my $rulestr = join(':',@{$rules});
                   2016:             my $homeserver=&domain($udom,'primary');
                   2017:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2018:                 my $response;
                   2019:                 if ($item eq 'username') {                
                   2020:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2021:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2022:                                               $homeserver));
1.923     raeburn  2023:                 } elsif ($item eq 'id') {
                   2024:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2025:                                               ':'.&escape($id).':'.$rulestr,
                   2026:                                               $homeserver));
1.945     raeburn  2027:                 } elsif ($item eq 'selfcreate') {
                   2028:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2029:                                                &escape($udom).':'.&escape($uname).
                   2030:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2031:                 }
1.912     raeburn  2032:                 if ($response ne 'refused') {
                   2033:                     my @pairs=split(/\&/,$response);
                   2034:                     foreach my $item (@pairs) {
                   2035:                         my ($key,$value)=split(/=/,$item,2);
                   2036:                         $key = &unescape($key);
                   2037:                         next if ($key =~ /^error: 2 /);
                   2038:                         $returnhash{$key}=&thaw_unescape($value);
                   2039:                     }
                   2040:                 }
                   2041:             }
                   2042:         }
                   2043:     }
                   2044:     return %returnhash;
                   2045: }
                   2046: 
                   2047: sub inst_userrules {
1.923     raeburn  2048:     my ($udom,$check) = @_;
1.912     raeburn  2049:     my (%ruleshash,@ruleorder);
                   2050:     if ($udom ne '') {
                   2051:         my $homeserver=&domain($udom,'primary');
                   2052:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2053:             my $response;
                   2054:             if ($check eq 'id') {
                   2055:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2056:                                  $homeserver);
1.943     raeburn  2057:             } elsif ($check eq 'email') {
                   2058:                 $response=&reply('instemailrules:'.&escape($udom),
                   2059:                                  $homeserver);
1.923     raeburn  2060:             } else {
                   2061:                 $response=&reply('instuserrules:'.&escape($udom),
                   2062:                                  $homeserver);
                   2063:             }
1.912     raeburn  2064:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2065:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2066:                 ($response ne 'no_such_host')) {
                   2067:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2068:                 my @pairs=split(/\&/,$hashitems);
                   2069:                 foreach my $item (@pairs) {
                   2070:                     my ($key,$value)=split(/=/,$item,2);
                   2071:                     $key = &unescape($key);
                   2072:                     next if ($key =~ /^error: 2 /);
                   2073:                     $ruleshash{$key}=&thaw_unescape($value);
                   2074:                 }
                   2075:                 my @esc_order = split(/\&/,$orderitems);
                   2076:                 foreach my $item (@esc_order) {
                   2077:                     push(@ruleorder,&unescape($item));
                   2078:                 }
                   2079:             }
                   2080:         }
                   2081:     }
                   2082:     return (\%ruleshash,\@ruleorder);
                   2083: }
                   2084: 
1.976     raeburn  2085: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2086: 
                   2087: sub get_domain_defaults {
1.1172.2.35  raeburn  2088:     my ($domain,$ignore_cache) = @_;
                   2089:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2090:     my $cachetime = 60*60*24;
1.1172.2.35  raeburn  2091:     unless ($ignore_cache) {
                   2092:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2093:         if (defined($cached)) {
                   2094:             if (ref($result) eq 'HASH') {
                   2095:                 return %{$result};
                   2096:             }
1.943     raeburn  2097:         }
                   2098:     }
                   2099:     my %domdefaults;
                   2100:     my %domconfig =
1.989     raeburn  2101:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2102:                                   'requestcourses','inststatus',
1.1172.2.9  raeburn  2103:                                   'coursedefaults','usersessions',
1.1172.2.46  raeburn  2104:                                   'requestauthor','selfenrollment',
1.1172.2.76  raeburn  2105:                                   'coursecategories','autoenroll'],$domain);
1.1172.2.41  raeburn  2106:     my @coursetypes = ('official','unofficial','community','textbook');
1.943     raeburn  2107:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2108:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2109:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2110:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2111:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2112:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2113:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943     raeburn  2114:     } else {
                   2115:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2116:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2117:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2118:     }
1.976     raeburn  2119:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2120:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2121:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2122:         } else {
                   2123:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29  raeburn  2124:         }
1.1172.2.6  raeburn  2125:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2126:         foreach my $item (@usertools) {
                   2127:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2128:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2129:             }
                   2130:         }
1.1172.2.29  raeburn  2131:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2132:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2133:         }
1.976     raeburn  2134:     }
1.985     raeburn  2135:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37  raeburn  2136:         foreach my $item ('official','unofficial','community','textbook') {
1.985     raeburn  2137:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2138:         }
                   2139:     }
1.1172.2.9  raeburn  2140:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2141:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2142:     }
1.989     raeburn  2143:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44  raeburn  2144:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2145:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2146:         }
                   2147:     }
1.1047    raeburn  2148:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60  raeburn  2149:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2150:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2151:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2152:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2153:         }
1.1172.2.41  raeburn  2154:         foreach my $type (@coursetypes) {
                   2155:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2156:                 unless ($type eq 'community') {
                   2157:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2158:                 }
                   2159:             }
                   2160:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2161:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2162:             }
1.1172.2.60  raeburn  2163:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2164:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2165:                     $domdefaults{$type.'postsubtimeout'} =
                   2166:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
                   2167:                 }
                   2168:             }
1.1172.2.30  raeburn  2169:         }
1.1172.2.67  raeburn  2170:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2171:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2172:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2173:                 if (@clonecodes) {
                   2174:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2175:                 }
                   2176:             }
                   2177:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2178:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2179:         }
1.1047    raeburn  2180:     }
1.1073    raeburn  2181:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2182:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2183:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2184:         }
                   2185:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2186:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2187:         }
1.1172.2.62  raeburn  2188:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2189:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2190:         }
1.1073    raeburn  2191:     }
1.1172.2.41  raeburn  2192:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2193:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2194:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2195:                             'approval','limit');
                   2196:             foreach my $type (@coursetypes) {
                   2197:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2198:                     my @mgrdc = ();
                   2199:                     foreach my $item (@settings) {
                   2200:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2201:                             push(@mgrdc,$item);
                   2202:                         }
                   2203:                     }
                   2204:                     if (@mgrdc) {
                   2205:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2206:                     }
                   2207:                 }
                   2208:             }
                   2209:         }
                   2210:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2211:             foreach my $type (@coursetypes) {
                   2212:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2213:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2214:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2215:                     }
                   2216:                 }
                   2217:             }
                   2218:         }
                   2219:     }
1.1172.2.46  raeburn  2220:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2221:         $domdefaults{'catauth'} = 'std';
                   2222:         $domdefaults{'catunauth'} = 'std';
                   2223:         if ($domconfig{'coursecategories'}{'auth'}) {
                   2224:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2225:         }
                   2226:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2227:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2228:         }
                   2229:     }
1.1172.2.76  raeburn  2230:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2231:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2232:     }
1.1172.2.23  raeburn  2233:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2234:     return %domdefaults;
                   2235: }
                   2236: 
1.344     www      2237: # --------------------------------------------------- Assign a key to a student
                   2238: 
                   2239: sub assign_access_key {
1.364     www      2240: #
                   2241: # a valid key looks like uname:udom#comments
                   2242: # comments are being appended
                   2243: #
1.498     www      2244:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2245:     $kdom=
1.620     albertel 2246:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2247:     $knum=
1.620     albertel 2248:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2249:     $cdom=
1.620     albertel 2250:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2251:     $cnum=
1.620     albertel 2252:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2253:     $udom=$env{'user.name'} unless (defined($udom));
                   2254:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2255:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2256:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2257:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2258:                                                   # assigned to this person
                   2259:                                                   # - this should not happen,
1.345     www      2260:                                                   # unless something went wrong
                   2261:                                                   # the first time around
                   2262: # ready to assign
1.364     www      2263:         $logentry=$1.'; '.$logentry;
1.496     www      2264:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2265:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2266: # key now belongs to user
1.346     www      2267: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2268:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2269:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2270:                 return 'ok';
                   2271:             } else {
                   2272:                 return 
                   2273:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2274: 	    }
                   2275:         } else {
                   2276:             return 'error: Could not assign key, try again later.';
                   2277:         }
1.364     www      2278:     } elsif (!$existing{$ckey}) {
1.345     www      2279: # the key does not exist
                   2280: 	return 'error: The key does not exist';
                   2281:     } else {
                   2282: # the key is somebody else's
                   2283: 	return 'error: The key is already in use';
                   2284:     }
1.344     www      2285: }
                   2286: 
1.364     www      2287: # ------------------------------------------ put an additional comment on a key
                   2288: 
                   2289: sub comment_access_key {
                   2290: #
                   2291: # a valid key looks like uname:udom#comments
                   2292: # comments are being appended
                   2293: #
                   2294:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2295:     $cdom=
1.620     albertel 2296:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2297:     $cnum=
1.620     albertel 2298:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2299:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2300:     if ($existing{$ckey}) {
                   2301:         $existing{$ckey}.='; '.$logentry;
                   2302: # ready to assign
1.367     www      2303:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2304:                                                  $cdom,$cnum) eq 'ok') {
                   2305: 	    return 'ok';
                   2306:         } else {
                   2307: 	    return 'error: Count not store comment.';
                   2308:         }
                   2309:     } else {
                   2310: # the key does not exist
                   2311: 	return 'error: The key does not exist';
                   2312:     }
                   2313: }
                   2314: 
1.344     www      2315: # ------------------------------------------------------ Generate a set of keys
                   2316: 
                   2317: sub generate_access_keys {
1.364     www      2318:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2319:     $cdom=
1.620     albertel 2320:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2321:     $cnum=
1.620     albertel 2322:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2323:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2324:     unless (($cdom) && ($cnum)) { return 0; }
                   2325:     if ($number>10000) { return 0; }
                   2326:     sleep(2); # make sure don't get same seed twice
                   2327:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2328:     my $total=0;
                   2329:     for (my $i=1;$i<=$number;$i++) {
                   2330:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2331:                   sprintf("%lx",int(100000*rand)).'-'.
                   2332:                   sprintf("%lx",int(100000*rand));
                   2333:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2334:        $newkey=~s/0/h/g; # and also 0 and O
                   2335:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2336:        if ($existing{$newkey}) {
                   2337:            $i--;
                   2338:        } else {
1.364     www      2339: 	  if (&put('accesskeys',
                   2340:               { $newkey => '# generated '.localtime().
1.620     albertel 2341:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2342:                            '; '.$logentry },
                   2343: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2344:               $total++;
                   2345: 	  }
                   2346:        }
                   2347:     }
1.620     albertel 2348:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2349:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2350:     return $total;
                   2351: }
                   2352: 
                   2353: # ------------------------------------------------------- Validate an accesskey
                   2354: 
                   2355: sub validate_access_key {
                   2356:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2357:     $cdom=
1.620     albertel 2358:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2359:     $cnum=
1.620     albertel 2360:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2361:     $udom=$env{'user.domain'} unless (defined($udom));
                   2362:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2363:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2364:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2365: }
                   2366: 
                   2367: # ------------------------------------- Find the section of student in a course
1.652     albertel 2368: sub devalidate_getsection_cache {
                   2369:     my ($udom,$unam,$courseid)=@_;
                   2370:     my $hashid="$udom:$unam:$courseid";
                   2371:     &devalidate_cache_new('getsection',$hashid);
                   2372: }
1.298     matthew  2373: 
1.815     albertel 2374: sub courseid_to_courseurl {
                   2375:     my ($courseid) = @_;
                   2376:     #already url style courseid
                   2377:     return $courseid if ($courseid =~ m{^/});
                   2378: 
                   2379:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2380: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2381: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2382: 	return "/$cdom/$cnum";
                   2383:     }
                   2384: 
                   2385:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2386:     if (exists($courseinfo{'num'})) {
                   2387: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2388:     }
                   2389: 
                   2390:     return undef;
                   2391: }
                   2392: 
1.298     matthew  2393: sub getsection {
                   2394:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2395:     my $cachetime=1800;
1.551     albertel 2396: 
                   2397:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2398:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2399:     if (defined($cached)) { return $result; }
                   2400: 
1.298     matthew  2401:     my %Pending; 
                   2402:     my %Expired;
                   2403:     #
                   2404:     # Each role can either have not started yet (pending), be active, 
                   2405:     #    or have expired.
                   2406:     #
                   2407:     # If there is an active role, we are done.
                   2408:     #
                   2409:     # If there is more than one role which has not started yet, 
                   2410:     #     choose the one which will start sooner
                   2411:     # If there is one role which has not started yet, return it.
                   2412:     #
                   2413:     # If there is more than one expired role, choose the one which ended last.
                   2414:     # If there is a role which has expired, return it.
                   2415:     #
1.815     albertel 2416:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2417:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2418:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2419:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2420:         my $section=$1;
                   2421:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2422:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2423:         my $now=time;
1.548     albertel 2424:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2425:             $Expired{$end}=$section;
                   2426:             next;
                   2427:         }
1.548     albertel 2428:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2429:             $Pending{$start}=$section;
                   2430:             next;
                   2431:         }
1.599     albertel 2432:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2433:     }
                   2434:     #
                   2435:     # Presumedly there will be few matching roles from the above
                   2436:     # loop and the sorting time will be negligible.
                   2437:     if (scalar(keys(%Pending))) {
                   2438:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2439:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2440:     } 
                   2441:     if (scalar(keys(%Expired))) {
                   2442:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2443:         my $time = pop(@sorted);
1.599     albertel 2444:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2445:     }
1.599     albertel 2446:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2447: }
1.70      www      2448: 
1.599     albertel 2449: sub save_cache {
                   2450:     &purge_remembered();
1.722     albertel 2451:     #&Apache::loncommon::validate_page();
1.620     albertel 2452:     undef(%env);
1.780     albertel 2453:     undef($env_loaded);
1.599     albertel 2454: }
1.452     albertel 2455: 
1.599     albertel 2456: my $to_remember=-1;
                   2457: my %remembered;
                   2458: my %accessed;
                   2459: my $kicks=0;
                   2460: my $hits=0;
1.849     albertel 2461: sub make_key {
                   2462:     my ($name,$id) = @_;
1.872     albertel 2463:     if (length($id) > 65 
                   2464: 	&& length(&escape($id)) > 200) {
                   2465: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2466:     }
1.849     albertel 2467:     return &escape($name.':'.$id);
                   2468: }
                   2469: 
1.599     albertel 2470: sub devalidate_cache_new {
                   2471:     my ($name,$id,$debug) = @_;
                   2472:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81  raeburn  2473:     my $remembered_id=$name.':'.$id;
1.849     albertel 2474:     $id=&make_key($name,$id);
1.599     albertel 2475:     $memcache->delete($id);
1.1172.2.81  raeburn  2476:     delete($remembered{$remembered_id});
                   2477:     delete($accessed{$remembered_id});
1.599     albertel 2478: }
                   2479: 
                   2480: sub is_cached_new {
                   2481:     my ($name,$id,$debug) = @_;
1.1172.2.81  raeburn  2482:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for 
                   2483:                                      # keys in %remembered hash, which persists for
                   2484:                                      # duration of request (no restriction on key length).
                   2485:     if (exists($remembered{$remembered_id})) {
                   2486: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2487: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2488: 	$hits++;
1.1172.2.81  raeburn  2489: 	return ($remembered{$remembered_id},1);
1.599     albertel 2490:     }
1.1172.2.81  raeburn  2491:     $id=&make_key($name,$id);
1.599     albertel 2492:     my $value = $memcache->get($id);
                   2493:     if (!(defined($value))) {
                   2494: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2495: 	return (undef,undef);
1.416     albertel 2496:     }
1.599     albertel 2497:     if ($value eq '__undef__') {
                   2498: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2499: 	$value=undef;
                   2500:     }
1.1172.2.81  raeburn  2501:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2502:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2503:     return ($value,1);
                   2504: }
                   2505: 
                   2506: sub do_cache_new {
                   2507:     my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81  raeburn  2508:     my $remembered_id=$name.':'.$id;
1.849     albertel 2509:     $id=&make_key($name,$id);
1.599     albertel 2510:     my $setvalue=$value;
                   2511:     if (!defined($setvalue)) {
                   2512: 	$setvalue='__undef__';
                   2513:     }
1.623     albertel 2514:     if (!defined($time) ) {
                   2515: 	$time=600;
                   2516:     }
1.599     albertel 2517:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2518:     my $result = $memcache->set($id,$setvalue,$time);
                   2519:     if (! $result) {
1.872     albertel 2520: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2521: 	$memcache->disconnect_all();
1.872     albertel 2522:     }
1.600     albertel 2523:     # need to make a copy of $value
1.1172.2.81  raeburn  2524:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2525:     return $value;
                   2526: }
                   2527: 
                   2528: sub make_room {
1.1172.2.81  raeburn  2529:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 2530: 
1.1172.2.81  raeburn  2531:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 2532:                                     : $value;
1.599     albertel 2533:     if ($to_remember<0) { return; }
1.1172.2.81  raeburn  2534:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2535:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2536:     my $to_kick;
                   2537:     my $max_time=0;
                   2538:     foreach my $other (keys(%accessed)) {
                   2539: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2540: 	    $to_kick=$other;
                   2541: 	    $max_time=&tv_interval($accessed{$other});
                   2542: 	}
                   2543:     }
                   2544:     delete($remembered{$to_kick});
                   2545:     delete($accessed{$to_kick});
                   2546:     $kicks++;
                   2547:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2548:     return;
                   2549: }
                   2550: 
1.599     albertel 2551: sub purge_remembered {
1.604     albertel 2552:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2553:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2554:     undef(%remembered);
                   2555:     undef(%accessed);
1.428     albertel 2556: }
1.70      www      2557: # ------------------------------------- Read an entry from a user's environment
                   2558: 
                   2559: sub userenvironment {
                   2560:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2561:     my $items;
                   2562:     foreach my $item (@what) {
                   2563:         $items.=&escape($item).'&';
                   2564:     }
                   2565:     $items=~s/\&$//;
1.70      www      2566:     my %returnhash=();
1.1009    raeburn  2567:     my $uhome = &homeserver($unam,$udom);
                   2568:     unless ($uhome eq 'no_host') {
                   2569:         my @answer=split(/\&/, 
                   2570:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2571:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2572:             return %returnhash;
                   2573:         }
1.1009    raeburn  2574:         my $i;
                   2575:         for ($i=0;$i<=$#what;$i++) {
                   2576: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2577:         }
1.70      www      2578:     }
                   2579:     return %returnhash;
1.1       albertel 2580: }
                   2581: 
1.617     albertel 2582: # ---------------------------------------------------------- Get a studentphoto
                   2583: sub studentphoto {
                   2584:     my ($udom,$unam,$ext) = @_;
                   2585:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2586:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2587:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2588:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2589:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2590:             } else {
                   2591:                 my ($result,$perm_reqd)=
1.707     albertel 2592: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2593:                 if ($result eq 'ok') {
                   2594:                     if (!($perm_reqd eq 'yes')) {
                   2595:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2596:                     }
                   2597:                 }
                   2598:             }
                   2599:         }
                   2600:     } else {
                   2601:         my ($result,$perm_reqd) = 
1.707     albertel 2602: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2603:         if ($result eq 'ok') {
                   2604:             if (!($perm_reqd eq 'yes')) {
                   2605:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2606:             }
                   2607:         }
                   2608:     }
                   2609:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2610: }
                   2611: 
                   2612: sub retrievestudentphoto {
                   2613:     my ($udom,$unam,$ext,$type) = @_;
                   2614:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2615:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2616:     if ($ret eq 'ok') {
                   2617:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2618:         if ($type eq 'thumbnail') {
                   2619:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2620:         }
                   2621:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2622:         return $tokenurl;
                   2623:     } else {
                   2624:         if ($type eq 'thumbnail') {
                   2625:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2626:         } else { 
                   2627:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2628:         }
1.617     albertel 2629:     }
                   2630: }
                   2631: 
1.263     www      2632: # -------------------------------------------------------------------- New chat
                   2633: 
                   2634: sub chatsend {
1.724     raeburn  2635:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2636:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2637:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2638:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2639:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2640: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2641: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2642: }
                   2643: 
                   2644: # ------------------------------------------ Find current version of a resource
                   2645: 
                   2646: sub getversion {
                   2647:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  2648:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2649:     return &currentversion(&filelocation('',$fname));
                   2650: }
                   2651: 
                   2652: sub currentversion {
                   2653:     my $fname=shift;
                   2654:     my $author=$fname;
                   2655:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2656:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2657:     my $home=&homeserver($uname,$udom);
1.292     www      2658:     if ($home eq 'no_host') { 
                   2659:         return -1; 
                   2660:     }
1.1112    www      2661:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2662:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2663: 	return -1;
                   2664:     }
1.1112    www      2665:     return $answer;
1.263     www      2666: }
                   2667: 
1.1111    www      2668: #
                   2669: # Return special version number of resource if set by override, empty otherwise
                   2670: #
                   2671: sub usedversion {
                   2672:     my $fname=shift;
                   2673:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2674:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2675:     if ($urlversion) { return $urlversion; }
                   2676:     return '';
                   2677: }
                   2678: 
1.1       albertel 2679: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2680: 
1.1       albertel 2681: sub subscribe {
                   2682:     my $fname=shift;
1.761     raeburn  2683:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2684:     $fname=~s/[\n\r]//g;
1.1       albertel 2685:     my $author=$fname;
                   2686:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2687:     my ($udom,$uname)=split(/\//,$author);
                   2688:     my $home=homeserver($uname,$udom);
1.335     albertel 2689:     if ($home eq 'no_host') {
                   2690:         return 'not_found';
1.1       albertel 2691:     }
                   2692:     my $answer=reply("sub:$fname",$home);
1.64      www      2693:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2694: 	$answer.=' by '.$home;
                   2695:     }
1.1       albertel 2696:     return $answer;
                   2697: }
                   2698:     
1.8       www      2699: # -------------------------------------------------------------- Replicate file
                   2700: 
                   2701: sub repcopy {
                   2702:     my $filename=shift;
1.23      www      2703:     $filename=~s/\/+/\//g;
1.1142    raeburn  2704:     my $londocroot = $perlvar{'lonDocRoot'};
                   2705:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2706:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2707:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2708: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2709: 	return &repcopy_userfile($filename);
                   2710:     }
1.532     albertel 2711:     $filename=~s/[\n\r]//g;
1.8       www      2712:     my $transname="$filename.in.transfer";
1.828     www      2713: # FIXME: this should flock
1.607     raeburn  2714:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2715:     my $remoteurl=subscribe($filename);
1.64      www      2716:     if ($remoteurl =~ /^con_lost by/) {
                   2717: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2718:            return 'unavailable';
1.8       www      2719:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2720: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2721: 	   return 'not_found';
1.64      www      2722:     } elsif ($remoteurl =~ /^rejected by/) {
                   2723: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2724:            return 'forbidden';
1.20      www      2725:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2726:            return 'ok';
1.8       www      2727:     } else {
1.290     www      2728:         my $author=$filename;
                   2729:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2730:         my ($udom,$uname)=split(/\//,$author);
                   2731:         my $home=homeserver($uname,$udom);
                   2732:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2733:            my @parts=split(/\//,$filename);
                   2734:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2735:            if ($path ne "$londocroot/res") {
1.8       www      2736:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2737: 	       return 'bad_request';
1.8       www      2738:            }
                   2739:            my $count;
                   2740:            for ($count=5;$count<$#parts;$count++) {
                   2741:                $path.="/$parts[$count]";
                   2742:                if ((-e $path)!=1) {
                   2743: 		   mkdir($path,0777);
                   2744:                }
                   2745:            }
                   2746:            my $ua=new LWP::UserAgent;
                   2747:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2748:            my $response=$ua->request($request,$transname);
                   2749:            if ($response->is_error()) {
                   2750: 	       unlink($transname);
                   2751:                my $message=$response->status_line;
1.672     albertel 2752:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2753:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2754:                return 'unavailable';
1.8       www      2755:            } else {
1.16      www      2756: 	       if ($remoteurl!~/\.meta$/) {
                   2757:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2758:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2759:                   if ($mresponse->is_error()) {
                   2760: 		      unlink($filename.'.meta');
                   2761:                       &logthis(
1.672     albertel 2762:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2763:                   }
                   2764: 	       }
1.8       www      2765:                rename($transname,$filename);
1.607     raeburn  2766:                return 'ok';
1.8       www      2767:            }
1.290     www      2768:        }
1.8       www      2769:     }
1.330     www      2770: }
                   2771: 
                   2772: # ------------------------------------------------ Get server side include body
                   2773: sub ssi_body {
1.381     albertel 2774:     my ($filelink,%form)=@_;
1.606     matthew  2775:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2776:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2777:     }
1.953     www      2778:     my $output='';
                   2779:     my $response;
1.980     raeburn  2780:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2781:        ($output,$response)=&externalssi($filelink);
1.953     www      2782:     } else {
1.1004    droeschl 2783:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2784:        $filelink .= 'inhibitmenu=yes';
1.953     www      2785:        ($output,$response)=&ssi($filelink,%form);
                   2786:     }
1.778     albertel 2787:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2788:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2789:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2790:     if (wantarray) {
                   2791:         return ($output, $response);
                   2792:     } else {
                   2793:         return $output;
                   2794:     }
1.8       www      2795: }
                   2796: 
1.15      www      2797: # --------------------------------------------------------- Server Side Include
                   2798: 
1.782     albertel 2799: sub absolute_url {
                   2800:     my ($host_name) = @_;
                   2801:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2802:     if ($host_name eq '') {
                   2803: 	$host_name = $ENV{'SERVER_NAME'};
                   2804:     }
                   2805:     return $protocol.$host_name;
                   2806: }
                   2807: 
1.942     foxr     2808: #
                   2809: #   Server side include.
                   2810: # Parameters:
                   2811: #  fn     Possibly encrypted resource name/id.
                   2812: #  form   Hash that describes how the rendering should be done
                   2813: #         and other things.
1.944     foxr     2814: # Returns:
1.950     raeburn  2815: #   Scalar context: The content of the response.
                   2816: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2817: #     
1.15      www      2818: sub ssi {
                   2819: 
1.944     foxr     2820:     my ($fn,%form)=@_;
1.15      www      2821:     my $ua=new LWP::UserAgent;
1.23      www      2822:     my $request;
1.711     albertel 2823: 
                   2824:     $form{'no_update_last_known'}=1;
1.895     albertel 2825:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2826:     if (%form) {
1.782     albertel 2827:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1172.2.58  raeburn  2828:       $request->content(join('&',map {
                   2829:             my $name = escape($_);
                   2830:             "$name=" . ( ref($form{$_}) eq 'ARRAY'
                   2831:             ? join("&$name=", map {escape($_) } @{$form{$_}})
                   2832:             : &escape($form{$_}) );
                   2833:         } keys(%form)));
1.23      www      2834:     } else {
1.782     albertel 2835:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2836:     }
                   2837: 
1.15      www      2838:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.2  raeburn  2839:     my $response= $ua->request($request);
1.944     foxr     2840:     if (wantarray) {
1.1172.2.3  raeburn  2841: 	return ($response->content, $response);
1.944     foxr     2842:     } else {
1.1172.2.3  raeburn  2843: 	return $response->content;
1.942     foxr     2844:     }
1.324     www      2845: }
                   2846: 
                   2847: sub externalssi {
                   2848:     my ($url)=@_;
                   2849:     my $ua=new LWP::UserAgent;
                   2850:     my $request=new HTTP::Request('GET',$url);
                   2851:     my $response=$ua->request($request);
1.954     raeburn  2852:     if (wantarray) {
                   2853:         return ($response->content, $response);
                   2854:     } else {
                   2855:         return $response->content;
                   2856:     }
1.15      www      2857: }
1.254     www      2858: 
1.492     albertel 2859: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2860: 
                   2861: sub allowuploaded {
                   2862:     my ($srcurl,$url)=@_;
                   2863:     $url=&clutter(&declutter($url));
                   2864:     my $dir=$url;
                   2865:     $dir=~s/\/[^\/]+$//;
                   2866:     my %httpref=();
                   2867:     my $httpurl=&hreflocation('',$url);
                   2868:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2869:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2870: }
1.477     raeburn  2871: 
1.1172.2.13  raeburn  2872: #
                   2873: # Determine if the current user should be able to edit a particular resource,
                   2874: # when viewing in course context.
                   2875: # (a) When viewing resource used to determine if "Edit" item is included in
                   2876: #     Functions.
                   2877: # (b) When displaying folder contents in course editor, used to determine if
                   2878: #     "Edit" link will be displayed alongside resource.
                   2879: #
                   2880: #  input: six args -- filename (decluttered), course number, course domain,
                   2881: #                   url, symb (if registered) and group (if this is a group
                   2882: #                   item -- e.g., bulletin board, group page etc.).
                   2883: #  output: array of five scalars --
                   2884: #          $cfile -- url for file editing if editable on current server
                   2885: #          $home -- homeserver of resource (i.e., for author if published,
                   2886: #                                           or course if uploaded.).
                   2887: #          $switchserver --  1 if server switch will be needed.
                   2888: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   2889: #          $forceview -- 1 if icon/link should be to go to view mode
                   2890: #
                   2891: 
                   2892: sub can_edit_resource {
                   2893:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   2894:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   2895: #
                   2896: # For aboutme pages user can only edit his/her own.
                   2897: #
                   2898:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   2899:         my ($sdom,$sname) = ($1,$2);
                   2900:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   2901:             $home = $env{'user.home'};
                   2902:             $cfile = $resurl;
                   2903:             if ($env{'form.forceedit'}) {
                   2904:                 $forceview = 1;
                   2905:             } else {
                   2906:                 $forceedit = 1;
                   2907:             }
                   2908:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   2909:         } else {
                   2910:             return;
                   2911:         }
                   2912:     }
                   2913: 
                   2914:     if ($env{'request.course.id'}) {
                   2915:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   2916:         if ($group ne '') {
                   2917: # if this is a group homepage or group bulletin board, check group privs
                   2918:             my $allowed = 0;
                   2919:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   2920:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   2921:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   2922:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   2923:                     $allowed = 1;
                   2924:                 }
                   2925:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   2926:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   2927:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   2928:                     $allowed = 1;
                   2929:                 }
                   2930:             }
                   2931:             if ($allowed) {
                   2932:                 $home=&homeserver($cnum,$cdom);
                   2933:                 if ($env{'form.forceedit'}) {
                   2934:                     $forceview = 1;
                   2935:                 } else {
                   2936:                     $forceedit = 1;
                   2937:                 }
                   2938:                 $cfile = $resurl;
                   2939:             } else {
                   2940:                 return;
                   2941:             }
                   2942:         } else {
1.1172.2.15  raeburn  2943:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2944:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   2945:                     return;
                   2946:                 }
                   2947:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  2948: #
                   2949: # No edit allowed where CC has switched to student role.
                   2950: #
                   2951:                 return;
                   2952:             }
                   2953:         }
                   2954:     }
                   2955: 
                   2956:     if ($file ne '') {
                   2957:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   2958:             if (&is_course_upload($file,$cnum,$cdom)) {
                   2959:                 $uploaded = 1;
                   2960:                 $incourse = 1;
                   2961:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   2962:                     $cfile = &hreflocation('',$file);
                   2963:                     if ($env{'form.forceedit'}) {
                   2964:                         $forceview = 1;
                   2965:                     } else {
                   2966:                         $forceedit = 1;
                   2967:                     }
                   2968:                 }
                   2969:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   2970:                 $incourse = 1;
                   2971:                 if ($env{'form.forceedit'}) {
                   2972:                     $forceview = 1;
                   2973:                 } else {
                   2974:                     $forceedit = 1;
                   2975:                 }
                   2976:                 $cfile = $resurl;
                   2977:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   2978:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   2979:                     $incourse = 1;
                   2980:                     if ($env{'form.forceedit'}) {
                   2981:                         $forceview = 1;
                   2982:                     } else {
                   2983:                         $forceedit = 1;
                   2984:                     }
                   2985:                     $cfile = $resurl;
                   2986:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   2987:                     $incourse = 1;
                   2988:                     $cfile = $resurl.'/smpedit';
                   2989:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   2990:                     $incourse = 1;
                   2991:                     if ($env{'form.forceedit'}) {
                   2992:                         $forceview = 1;
                   2993:                     } else {
                   2994:                         $forceedit = 1;
                   2995:                     }
                   2996:                     $cfile = $resurl;
1.1172.2.15  raeburn  2997:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2998:                     $incourse = 1;
                   2999:                     if ($env{'form.forceedit'}) {
                   3000:                         $forceview = 1;
                   3001:                     } else {
                   3002:                         $forceedit = 1;
                   3003:                     }
                   3004:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3005:                 }
                   3006:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3007:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3008:                 if (&is_on_map($template)) {
                   3009:                     $incourse = 1;
                   3010:                     $forceview = 1;
                   3011:                     $cfile = $template;
                   3012:                 }
                   3013:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3014:                     $incourse = 1;
                   3015:                     if ($env{'form.forceedit'}) {
                   3016:                         $forceview = 1;
                   3017:                     } else {
                   3018:                         $forceedit = 1;
                   3019:                     }
                   3020:                     $cfile = $resurl;
                   3021:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3022:                 $incourse = 1;
                   3023:                 $forceview = 1;
                   3024:                 if ($symb) {
                   3025:                     my ($map,$id,$res)=&decode_symb($symb);
                   3026:                     $env{'request.symb'} = $symb;
                   3027:                     $cfile = &clutter($res);
                   3028:                 } else {
                   3029:                     $cfile = $env{'form.suppurl'};
                   3030:                     $cfile =~ s{^http://}{};
                   3031:                     $cfile = '/adm/wrapper/ext/'.$cfile;
                   3032:                 }
1.1172.2.31  raeburn  3033:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3034:                 if ($env{'form.forceedit'}) {
                   3035:                     $forceview = 1;
                   3036:                 } else {
                   3037:                     $forceedit = 1;
                   3038:                 }
                   3039:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3040:             }
                   3041:         }
                   3042:         if ($uploaded || $incourse) {
                   3043:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  3044:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  3045:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3046:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3047:             # Check that the user has permission to edit this resource
                   3048:             my $setpriv = 1;
                   3049:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3050:             if (defined($cfudom)) {
                   3051:                 $home=&homeserver($cfuname,$cfudom);
                   3052:                 $cfile=$file;
                   3053:             }
                   3054:         }
                   3055:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   3056:             (($home ne '') && ($home ne 'no_host'))) {
                   3057:             my @ids=&current_machine_ids();
                   3058:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3059:                 $switchserver=1;
                   3060:             }
                   3061:         }
                   3062:     }
                   3063:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3064: }
                   3065: 
                   3066: sub is_course_upload {
                   3067:     my ($file,$cnum,$cdom) = @_;
                   3068:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3069:     $uploadpath =~ s{^\/}{};
                   3070:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3071:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   3072:         return 1;
                   3073:     }
                   3074:     return;
                   3075: }
                   3076: 
                   3077: sub in_course {
                   3078:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3079:     if ($hideprivileged) {
                   3080:         my $skipuser;
1.1172.2.23  raeburn  3081:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3082:         my @possdoms = ($cdom);
                   3083:         if ($coursehash{'checkforpriv'}) {
                   3084:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   3085:         }
                   3086:         if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13  raeburn  3087:             $skipuser = 1;
                   3088:             if ($coursehash{'nothideprivileged'}) {
                   3089:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3090:                     my $user;
                   3091:                     if ($item =~ /:/) {
                   3092:                         $user = $item;
                   3093:                     } else {
                   3094:                         $user = join(':',split(/[\@]/,$item));
                   3095:                     }
                   3096:                     if ($user eq $uname.':'.$udom) {
                   3097:                         undef($skipuser);
                   3098:                         last;
                   3099:                     }
                   3100:                 }
                   3101:             }
                   3102:             if ($skipuser) {
                   3103:                 return 0;
                   3104:             }
                   3105:         }
                   3106:     }
                   3107:     $type ||= 'any';
                   3108:     if (!defined($cdom) || !defined($cnum)) {
                   3109:         my $cid  = $env{'request.course.id'};
                   3110:         $cdom = $env{'course.'.$cid.'.domain'};
                   3111:         $cnum = $env{'course.'.$cid.'.num'};
                   3112:     }
                   3113:     my $typesref;
                   3114:     if (($type eq 'any') || ($type eq 'all')) {
                   3115:         $typesref = ['active','previous','future'];
                   3116:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3117:         $typesref = [$type];
                   3118:     }
                   3119:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3120:                               $typesref,undef,[$cdom]);
                   3121:     my ($tmp) = keys(%roles);
                   3122:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3123:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3124:     if (@course_roles > 0) {
                   3125:         return 1;
                   3126:     }
                   3127:     return 0;
                   3128: }
                   3129: 
1.478     albertel 3130: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3131: # input: action, courseID, current domain, intended
1.637     raeburn  3132: #        path to file, source of file, instruction to parse file for objects,
                   3133: #        ref to hash for embedded objects,
                   3134: #        ref to hash for codebase of java objects.
1.1095    raeburn  3135: #        reference to scalar to accommodate mime type determined
                   3136: #          from File::MMagic if $parser = parse.
1.637     raeburn  3137: #
1.485     raeburn  3138: # output: url to file (if action was uploaddoc), 
                   3139: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3140: #
1.478     albertel 3141: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3142: # course.
1.477     raeburn  3143: #
1.478     albertel 3144: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3145: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3146: #          course's home server.
1.477     raeburn  3147: #
1.478     albertel 3148: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3149: #          be copied from $source (current location) to 
                   3150: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3151: #         and will then be copied to
                   3152: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3153: #         course's home server.
1.485     raeburn  3154: #
1.481     raeburn  3155: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3156: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3157: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3158: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3159: #         in course's home server.
1.637     raeburn  3160: #
1.477     raeburn  3161: 
                   3162: sub process_coursefile {
1.1095    raeburn  3163:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3164:         $mimetype)=@_;
1.477     raeburn  3165:     my $fetchresult;
1.638     albertel 3166:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3167:     if ($action eq 'propagate') {
1.638     albertel 3168:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3169: 			     $home);
1.481     raeburn  3170:     } else {
1.477     raeburn  3171:         my $fpath = '';
                   3172:         my $fname = $file;
1.478     albertel 3173:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3174:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3175:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3176:         if ($action eq 'copy') {
                   3177:             if ($source eq '') {
                   3178:                 $fetchresult = 'no source file';
                   3179:                 return $fetchresult;
                   3180:             } else {
                   3181:                 my $destination = $filepath.'/'.$fname;
                   3182:                 rename($source,$destination);
                   3183:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3184:                                  $home);
1.481     raeburn  3185:             }
                   3186:         } elsif ($action eq 'uploaddoc') {
                   3187:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 3188:             print $fh $env{'form.'.$source};
1.481     raeburn  3189:             close($fh);
1.637     raeburn  3190:             if ($parser eq 'parse') {
1.1024    raeburn  3191:                 my $mm = new File::MMagic;
1.1095    raeburn  3192:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3193:                 if ($type eq 'text/html') {
1.1024    raeburn  3194:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3195:                     unless ($parse_result eq 'ok') {
                   3196:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3197:                     }
1.637     raeburn  3198:                 }
1.1095    raeburn  3199:                 if (ref($mimetype)) {
                   3200:                     $$mimetype = $type;
                   3201:                 } 
1.637     raeburn  3202:             }
1.477     raeburn  3203:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3204:                                  $home);
1.481     raeburn  3205:             if ($fetchresult eq 'ok') {
                   3206:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3207:             } else {
                   3208:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3209:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3210:                 return '/adm/notfound.html';
                   3211:             }
1.477     raeburn  3212:         }
                   3213:     }
1.485     raeburn  3214:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3215:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3216:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3217:     }
                   3218:     return $fetchresult;
                   3219: }
                   3220: 
1.637     raeburn  3221: sub build_filepath {
                   3222:     my ($fpath) = @_;
                   3223:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3224:     unless ($fpath eq '') {
                   3225:         my @parts=split('/',$fpath);
                   3226:         foreach my $part (@parts) {
                   3227:             $filepath.= '/'.$part;
                   3228:             if ((-e $filepath)!=1) {
                   3229:                 mkdir($filepath,0777);
                   3230:             }
                   3231:         }
                   3232:     }
                   3233:     return $filepath;
                   3234: }
                   3235: 
                   3236: sub store_edited_file {
1.638     albertel 3237:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3238:     my $file = $primary_url;
                   3239:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3240:     my $fpath = '';
                   3241:     my $fname = $file;
                   3242:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3243:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3244:     my $filepath = &build_filepath($fpath);
                   3245:     open(my $fh,'>'.$filepath.'/'.$fname);
                   3246:     print $fh $content;
                   3247:     close($fh);
1.638     albertel 3248:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3249:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3250: 			  $home);
1.637     raeburn  3251:     if ($$fetchresult eq 'ok') {
                   3252:         return '/uploaded/'.$fpath.'/'.$fname;
                   3253:     } else {
1.638     albertel 3254:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3255: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3256:         return '/adm/notfound.html';
                   3257:     }
                   3258: }
                   3259: 
1.531     albertel 3260: sub clean_filename {
1.831     albertel 3261:     my ($fname,$args)=@_;
1.315     www      3262: # Replace Windows backslashes by forward slashes
1.257     www      3263:     $fname=~s/\\/\//g;
1.831     albertel 3264:     if (!$args->{'keep_path'}) {
                   3265:         # Get rid of everything but the actual filename
                   3266: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3267:     }
1.315     www      3268: # Replace spaces by underscores
                   3269:     $fname=~s/\s+/\_/g;
                   3270: # Replace all other weird characters by nothing
1.831     albertel 3271:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3272: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3273: # numbers
                   3274:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3275:     return $fname;
                   3276: }
1.1051    raeburn  3277: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3278: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3279: # image with the same aspect ratio as the original, but with dimensions which do 
                   3280: # not exceed $resizewidth and $resizeheight.
                   3281:  
1.984     neumanie 3282: sub resizeImage {
1.1051    raeburn  3283:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3284:     my $ima = Image::Magick->new;
                   3285:     my $resized;
                   3286:     if (-e $img_path) {
                   3287:         $ima->Read($img_path);
                   3288:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3289:             my $width = $ima->Get('width');
                   3290:             my $height = $ima->Get('height');
                   3291:             if ($width > $resizewidth) {
                   3292: 	        my $factor = $width/$resizewidth;
                   3293:                 my $newheight = $height/$factor;
                   3294:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3295:                 $resized = 1;
                   3296:             }
                   3297:         }
                   3298:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3299:             my $width = $ima->Get('width');
                   3300:             my $height = $ima->Get('height');
                   3301:             if ($height > $resizeheight) {
                   3302:                 my $factor = $height/$resizeheight;
                   3303:                 my $newwidth = $width/$factor;
                   3304:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3305:                 $resized = 1;
                   3306:             }
                   3307:         }
                   3308:         if ($resized) {
                   3309:             $ima->Write($img_path);
                   3310:         }
                   3311:     }
                   3312:     return;
1.977     amueller 3313: }
                   3314: 
1.608     albertel 3315: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3316: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3317: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3318: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3319: #                                    canceloverwrite, or ''. 
                   3320: #                   if 'coursedoc': upload to the current course
                   3321: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3322: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3323: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3324: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3325: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3326: #        $allfiles - reference to hash for embedded objects
                   3327: #        $codebase - reference to hash for codebase of java objects
                   3328: #        $desuname - username for permanent storage of uploaded file
                   3329: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3330: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3331: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3332: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3333: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3334: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3335: #                    from File::MMagic.
1.858     raeburn  3336: # 
1.686     albertel 3337: # output: url of file in userspace, or error: <message> 
                   3338: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3339: 
1.531     albertel 3340: sub userfileupload {
1.1090    raeburn  3341:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3342:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3343:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3344:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3345:     $fname=&clean_filename($fname);
1.1090    raeburn  3346:     # See if there is anything left
1.257     www      3347:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3348:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3349:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3350:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3351:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3352:         my $now = time;
1.1090    raeburn  3353:         my $filepath;
1.1095    raeburn  3354:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3355:              $filepath = 'tmp/helprequests/'.$now;
                   3356:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3357:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3358:                          '_'.$env{'user.domain'}.'/pending';
                   3359:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3360:             my ($docuname,$docudom);
                   3361:             if ($destudom) {
                   3362:                 $docudom = $destudom;
                   3363:             } else {
                   3364:                 $docudom = $env{'user.domain'};
                   3365:             }
                   3366:             if ($destuname) {
                   3367:                 $docuname = $destuname;
                   3368:             } else {
                   3369:                 $docuname = $env{'user.name'};
                   3370:             }
                   3371:             if (exists($env{'form.group'})) {
                   3372:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3373:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3374:             }
                   3375:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3376:             if ($context eq 'canceloverwrite') {
                   3377:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3378:                 if (-e  $tempfile) {
                   3379:                     my @info = stat($tempfile);
                   3380:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3381:                         unlink($tempfile);
                   3382:                     }
                   3383:                 }
                   3384:                 return;
1.523     raeburn  3385:             }
                   3386:         }
1.1090    raeburn  3387:         # Create the directory if not present
1.741     raeburn  3388:         my @parts=split(/\//,$filepath);
                   3389:         my $fullpath = $perlvar{'lonDaemons'};
                   3390:         for (my $i=0;$i<@parts;$i++) {
                   3391:             $fullpath .= '/'.$parts[$i];
                   3392:             if ((-e $fullpath)!=1) {
                   3393:                 mkdir($fullpath,0777);
                   3394:             }
                   3395:         }
                   3396:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   3397:         print $fh $env{'form.'.$formname};
                   3398:         close($fh);
1.1090    raeburn  3399:         if ($context eq 'existingfile') {
                   3400:             my @info = stat($fullpath.'/'.$fname);
                   3401:             return ($fullpath.'/'.$fname,$info[9]);
                   3402:         } else {
                   3403:             return $fullpath.'/'.$fname;
                   3404:         }
1.523     raeburn  3405:     }
1.995     raeburn  3406:     if ($subdir eq 'scantron') {
                   3407:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3408:     } else {
1.995     raeburn  3409:         $fname="$subdir/$fname";
                   3410:     }
1.1090    raeburn  3411:     if ($context eq 'coursedoc') {
1.638     albertel 3412: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3413: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3414:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3415:             return &finishuserfileupload($docuname,$docudom,
                   3416: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3417: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3418:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3419:         } else {
1.1172.2.21  raeburn  3420:             if ($env{'form.folder'}) {
                   3421:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3422:             }
1.638     albertel 3423:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3424: 				       $fname,$formname,$parser,
1.1095    raeburn  3425: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3426:         }
1.719     banghart 3427:     } elsif (defined($destuname)) {
                   3428:         my $docuname=$destuname;
                   3429:         my $docudom=$destudom;
1.860     raeburn  3430: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3431: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3432:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3433:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3434:     } else {
1.638     albertel 3435:         my $docuname=$env{'user.name'};
                   3436:         my $docudom=$env{'user.domain'};
1.1172.2.23  raeburn  3437:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3438:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3439:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3440:         }
1.860     raeburn  3441: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3442: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3443:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3444:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3445:     }
1.271     www      3446: }
                   3447: 
                   3448: sub finishuserfileupload {
1.860     raeburn  3449:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3450:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3451:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3452:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3453:   
1.860     raeburn  3454:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3455:     $file=$fname;
                   3456:     if ($fname=~m|/|) {
                   3457:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3458: 	$path.=$fnamepath.'/';
                   3459:     }
1.259     www      3460:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3461:     my $count;
                   3462:     for ($count=4;$count<=$#parts;$count++) {
                   3463:         $filepath.="/$parts[$count]";
                   3464:         if ((-e $filepath)!=1) {
                   3465: 	    mkdir($filepath,0777);
                   3466:         }
                   3467:     }
1.984     neumanie 3468: 
1.258     www      3469: # Save the file
                   3470:     {
1.701     albertel 3471: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   3472: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3473: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3474: 	    return '/adm/notfound.html';
                   3475: 	}
1.1090    raeburn  3476:         if ($context eq 'overwrite') {
1.1117    foxr     3477:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3478:             my $target = $filepath.'/'.$file;
                   3479:             if (-e $source) {
                   3480:                 my @info = stat($source);
                   3481:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3482:                     unless (&File::Copy::move($source,$target)) {
                   3483:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3484:                         return "Moving from $source failed";
                   3485:                     }
                   3486:                 } else {
                   3487:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3488:                 }
                   3489:             } else {
                   3490:                 return "Temporary file: $source missing";
                   3491:             }
                   3492:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3493: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3494: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3495: 	    return '/adm/notfound.html';
                   3496: 	}
1.570     albertel 3497: 	close(FH);
1.1051    raeburn  3498:         if ($resizewidth && $resizeheight) {
                   3499:             my $mm = new File::MMagic;
                   3500:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3501:             if ($mime_type =~ m{^image/}) {
                   3502: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3503:             }  
1.977     amueller 3504: 	}
1.258     www      3505:     }
1.1152    raeburn  3506:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3507:         if (ref($mimetype)) {
                   3508:             if ($$mimetype eq '') {
                   3509:                 my $mm = new File::MMagic;
                   3510:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3511:                 $$mimetype = $type;
                   3512:             }
                   3513:         }
                   3514:     }
1.637     raeburn  3515:     if ($parser eq 'parse') {
1.1152    raeburn  3516:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3517:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3518:                                                        $allfiles,$codebase);
                   3519:             unless ($parse_result eq 'ok') {
                   3520:                 &logthis('Failed to parse '.$filepath.$file.
                   3521: 	   	         ' for embedded media: '.$parse_result); 
                   3522:             }
1.637     raeburn  3523:         }
                   3524:     }
1.860     raeburn  3525:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3526:         my $input = $filepath.'/'.$file;
                   3527:         my $output = $filepath.'/'.'tn-'.$file;
                   3528:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3529:         system("convert -sample $thumbsize $input $output");
                   3530:         if (-e $filepath.'/'.'tn-'.$file) {
                   3531:             $fetchthumb  = 1; 
                   3532:         }
                   3533:     }
1.858     raeburn  3534:  
1.259     www      3535: # Notify homeserver to grep it
                   3536: #
1.984     neumanie 3537:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3538:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3539:     if ($fetchresult eq 'ok') {
1.860     raeburn  3540:         if ($fetchthumb) {
                   3541:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3542:             if ($thumbresult ne 'ok') {
                   3543:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3544:                          $docuhome.': '.$thumbresult);
                   3545:             }
                   3546:         }
1.259     www      3547: #
1.258     www      3548: # Return the URL to it
1.494     albertel 3549:         return '/uploaded/'.$path.$file;
1.263     www      3550:     } else {
1.494     albertel 3551:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3552: 		 ': '.$fetchresult);
1.263     www      3553:         return '/adm/notfound.html';
1.858     raeburn  3554:     }
1.493     albertel 3555: }
                   3556: 
1.637     raeburn  3557: sub extract_embedded_items {
1.961     raeburn  3558:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3559:     my @state = ();
1.1164    raeburn  3560:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3561:     my %javafiles = (
                   3562:                       codebase => '',
                   3563:                       code => '',
                   3564:                       archive => ''
                   3565:                     );
                   3566:     my %mediafiles = (
                   3567:                       src => '',
                   3568:                       movie => '',
                   3569:                      );
1.648     raeburn  3570:     my $p;
                   3571:     if ($content) {
                   3572:         $p = HTML::LCParser->new($content);
                   3573:     } else {
1.961     raeburn  3574:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3575:     }
1.641     albertel 3576:     while (my $t=$p->get_token()) {
1.640     albertel 3577: 	if ($t->[0] eq 'S') {
                   3578: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3579: 	    push(@state, $tagname);
1.648     raeburn  3580:             if (lc($tagname) eq 'allow') {
                   3581:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3582:             }
1.640     albertel 3583: 	    if (lc($tagname) eq 'img') {
                   3584: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3585: 	    }
1.886     albertel 3586: 	    if (lc($tagname) eq 'a') {
1.1172.2.24  raeburn  3587:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
                   3588: 		    &add_filetype($allfiles,$attr->{'href'},'href');
                   3589:                 }
1.886     albertel 3590: 	    }
1.645     raeburn  3591:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3592:                 my $src;
1.645     raeburn  3593:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3594:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3595:                 } else {
1.1164    raeburn  3596:                     if ($attr->{'src'} ne '') {
                   3597:                         $src = $attr->{'src'};
                   3598:                         &add_filetype($allfiles,$src,'src');
                   3599:                     }
                   3600:                 }
                   3601:                 my $text = $p->get_trimmed_text();
                   3602:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3603:                     my @swfargs = split(/,/,$1);
                   3604:                     foreach my $item (@swfargs) {
                   3605:                         $item =~ s/["']//g;
                   3606:                         $item =~ s/^\s+//;
                   3607:                         $item =~ s/\s+$//;
                   3608:                     }
                   3609:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3610:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3611:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3612:                         } else {
                   3613:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3614:                         }
                   3615:                     }
1.645     raeburn  3616:                 }
                   3617:             }
                   3618:             if (lc($tagname) eq 'link') {
                   3619:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3620:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3621:                 }
                   3622:             }
1.640     albertel 3623: 	    if (lc($tagname) eq 'object' ||
                   3624: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3625: 		foreach my $item (keys(%javafiles)) {
                   3626: 		    $javafiles{$item} = '';
                   3627: 		}
1.1164    raeburn  3628:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3629:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3630:                 }
1.640     albertel 3631: 	    }
                   3632: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3633: 		my $name = lc($attr->{'name'});
                   3634: 		foreach my $item (keys(%javafiles)) {
                   3635: 		    if ($name eq $item) {
                   3636: 			$javafiles{$item} = $attr->{'value'};
                   3637: 			last;
                   3638: 		    }
                   3639: 		}
1.1164    raeburn  3640:                 my $pathfrom;
1.640     albertel 3641: 		foreach my $item (keys(%mediafiles)) {
                   3642: 		    if ($name eq $item) {
1.1164    raeburn  3643:                         $pathfrom = $attr->{'value'};
                   3644:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3645: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3646: 			last;
                   3647: 		    }
                   3648: 		}
1.1164    raeburn  3649:                 if ($name eq 'flashvars') {
                   3650:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3651:                 }
                   3652:                 if ($pathfrom ne '') {
                   3653:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3654:                                          $pathfrom);
                   3655:                 }
1.640     albertel 3656: 	    }
                   3657: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3658: 		foreach my $item (keys(%javafiles)) {
                   3659: 		    if ($attr->{$item}) {
                   3660: 			$javafiles{$item} = $attr->{$item};
                   3661: 			last;
                   3662: 		    }
                   3663: 		}
                   3664: 		foreach my $item (keys(%mediafiles)) {
                   3665: 		    if ($attr->{$item}) {
                   3666: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3667: 			last;
                   3668: 		    }
                   3669: 		}
1.1164    raeburn  3670:                 if (lc($tagname) eq 'embed') {
                   3671:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3672:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3673:                                              $attr->{'src'});
                   3674:                     }
                   3675:                 }
1.640     albertel 3676: 	    }
1.1172.2.35  raeburn  3677:             if (lc($tagname) eq 'iframe') {
                   3678:                 my $src = $attr->{'src'} ;
                   3679:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   3680:                     &add_filetype($allfiles,$src,'src');
                   3681:                 } elsif ($src =~ m{^/}) {
                   3682:                     if ($env{'request.course.id'}) {
                   3683:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3684:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3685:                         my $url = &hreflocation('',$fullpath);
                   3686:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   3687:                             my $relpath = $1;
                   3688:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   3689:                                 &add_filetype($allfiles,$1,'src');
                   3690:                             }
                   3691:                         }
                   3692:                     }
                   3693:                 }
                   3694:             }
1.1164    raeburn  3695:             if ($t->[4] =~ m{/>$}) {
1.1172.2.35  raeburn  3696:                 pop(@state);
1.1164    raeburn  3697:             }
1.640     albertel 3698: 	} elsif ($t->[0] eq 'E') {
                   3699: 	    my ($tagname) = ($t->[1]);
                   3700: 	    if ($javafiles{'codebase'} ne '') {
                   3701: 		$javafiles{'codebase'} .= '/';
                   3702: 	    }  
                   3703: 	    if (lc($tagname) eq 'applet' ||
                   3704: 		lc($tagname) eq 'object' ||
                   3705: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3706: 		) {
                   3707: 		foreach my $item (keys(%javafiles)) {
                   3708: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3709: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3710: 			&add_filetype($allfiles,$file,$item);
                   3711: 		    }
                   3712: 		}
                   3713: 	    } 
                   3714: 	    pop @state;
                   3715: 	}
                   3716:     }
1.1164    raeburn  3717:     foreach my $id (sort(keys(%flashvars))) {
                   3718:         if ($shockwave{$id} ne '') {
                   3719:             my @pairs = split(/\&/,$flashvars{$id});
                   3720:             foreach my $pair (@pairs) {
                   3721:                 my ($key,$value) = split(/\=/,$pair);
                   3722:                 if ($key eq 'thumb') {
                   3723:                     &add_filetype($allfiles,$value,$key);
                   3724:                 } elsif ($key eq 'content') {
                   3725:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3726:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3727:                     if ($ext ne '') {
                   3728:                         &add_filetype($allfiles,$path.$value,$ext);
                   3729:                     }
                   3730:                 }
                   3731:             }
                   3732:         }
                   3733:     }
1.637     raeburn  3734:     return 'ok';
                   3735: }
                   3736: 
1.639     albertel 3737: sub add_filetype {
                   3738:     my ($allfiles,$file,$type)=@_;
                   3739:     if (exists($allfiles->{$file})) {
                   3740: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3741: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3742: 	}
                   3743:     } else {
                   3744: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3745:     }
                   3746: }
                   3747: 
1.1164    raeburn  3748: sub embedded_dependency {
                   3749:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3750:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3751:         if (($identifier ne '') &&
                   3752:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3753:             ($pathfrom ne '')) {
                   3754:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3755:             foreach my $dep (@{$related->{$identifier}}) {
                   3756:                 &add_filetype($allfiles,$path.$dep,'object');
                   3757:             }
                   3758:         }
                   3759:     }
                   3760:     return;
                   3761: }
                   3762: 
1.493     albertel 3763: sub removeuploadedurl {
1.984     neumanie 3764:     my ($url)=@_;	
                   3765:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3766:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3767: }
                   3768: 
                   3769: sub removeuserfile {
                   3770:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3771:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3772:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3773:     if ($result eq 'ok') {	
1.798     raeburn  3774:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3775:             my $metafile = $fname.'.meta';
                   3776:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3777: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3778:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3779:             my $sqlresult = 
1.823     albertel 3780:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3781:                                         'portfolio_metadata',$group,
                   3782:                                         'delete');
1.798     raeburn  3783:         }
                   3784:     }
                   3785:     return $result;
1.257     www      3786: }
1.15      www      3787: 
1.530     albertel 3788: sub mkdiruserfile {
                   3789:     my ($docuname,$docudom,$dir)=@_;
                   3790:     my $home=&homeserver($docuname,$docudom);
                   3791:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3792: }
                   3793: 
1.531     albertel 3794: sub renameuserfile {
                   3795:     my ($docuname,$docudom,$old,$new)=@_;
                   3796:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3797:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3798:                         &escape("$old").':'.&escape("$new"),$home);
                   3799:     if ($result eq 'ok') {
                   3800:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3801:             my $oldmeta = $old.'.meta';
                   3802:             my $newmeta = $new.'.meta';
                   3803:             my $metaresult = 
                   3804:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3805: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3806:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3807:             my $sqlresult = 
1.823     albertel 3808:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3809:                                         'portfolio_metadata',$group,
                   3810:                                         'delete');
1.798     raeburn  3811:         }
                   3812:     }
                   3813:     return $result;
1.531     albertel 3814: }
                   3815: 
1.14      www      3816: # ------------------------------------------------------------------------- Log
                   3817: 
                   3818: sub log {
                   3819:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3820:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3821: }
                   3822: 
                   3823: # ------------------------------------------------------------------ Course Log
1.352     www      3824: #
                   3825: # This routine flushes several buffers of non-mission-critical nature
                   3826: #
1.157     www      3827: 
                   3828: sub flushcourselogs {
1.352     www      3829:     &logthis('Flushing log buffers');
                   3830: #
                   3831: # course logs
                   3832: # This is a log of all transactions in a course, which can be used
                   3833: # for data mining purposes
                   3834: #
                   3835: # It also collects the courseid database, which lists last transaction
                   3836: # times and course titles for all courseids
                   3837: #
                   3838:     my %courseidbuffer=();
1.921     raeburn  3839:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3840:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3841: 		          &escape($courselogs{$crsid}),
                   3842: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3843: 	    delete $courselogs{$crsid};
                   3844:         } else {
                   3845:             &logthis('Failed to flush log buffer for '.$crsid);
                   3846:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3847:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3848:                         " exceeded maximum size, deleting.</font>");
                   3849:                delete $courselogs{$crsid};
                   3850:             }
1.352     www      3851:         }
1.920     raeburn  3852:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3853:             'description' => $coursedescrbuf{$crsid},
                   3854:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3855:             'type'        => $coursetypebuf{$crsid},
                   3856:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3857:         };
1.191     harris41 3858:     }
1.352     www      3859: #
                   3860: # Write course id database (reverse lookup) to homeserver of courses 
                   3861: # Is used in pickcourse
                   3862: #
1.840     albertel 3863:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3864:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3865:                                     $courseidbuffer{$crs_home},
                   3866:                                     $crs_home,'timeonly');
1.352     www      3867:     }
                   3868: #
                   3869: # File accesses
                   3870: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3871: #
1.449     matthew  3872:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3873:         if ($entry =~ /___count$/) {
                   3874:             my ($dom,$name);
1.807     albertel 3875:             ($dom,$name,undef)=
1.811     albertel 3876: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3877:             if (! defined($dom) || $dom eq '' || 
                   3878:                 ! defined($name) || $name eq '') {
1.620     albertel 3879:                 my $cid = $env{'request.course.id'};
                   3880:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3881:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3882:             }
1.450     matthew  3883:             my $value = $accesshash{$entry};
                   3884:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   3885:             my %temphash=($url => $value);
1.449     matthew  3886:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   3887:             if ($result eq 'ok') {
                   3888:                 delete $accesshash{$entry};
                   3889:             }
                   3890:         } else {
1.811     albertel 3891:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      3892:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  3893:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3894:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3895:                 delete $accesshash{$entry};
                   3896:             }
1.185     www      3897:         }
1.191     harris41 3898:     }
1.352     www      3899: #
                   3900: # Roles
                   3901: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   3902: #
1.800     albertel 3903:     foreach my $entry (keys(%userrolehash)) {
1.351     www      3904:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      3905: 	    split(/\:/,$entry);
                   3906:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      3907:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      3908:                 $rudom,$runame) eq 'ok') {
                   3909: 	    delete $userrolehash{$entry};
                   3910:         }
                   3911:     }
1.662     raeburn  3912: #
1.1172.2.84  raeburn  3913: # Reverse lookup of domain roles (dc, ad, li, sc, dh, au)
1.662     raeburn  3914: #
                   3915:     my %domrolebuffer = ();
1.1000    raeburn  3916:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 3917:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  3918:         if ($domrolebuffer{$rudom}) {
                   3919:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   3920:                       '='.&escape($domainrolehash{$entry});
                   3921:         } else {
                   3922:             $domrolebuffer{$rudom}.=&escape($entry).
                   3923:                       '='.&escape($domainrolehash{$entry});
                   3924:         }
                   3925:         delete $domainrolehash{$entry};
                   3926:     }
                   3927:     foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82  raeburn  3928:         my %servers;
                   3929:         if (defined(&domain($dom,'primary'))) {
                   3930:             my $primary=&domain($dom,'primary');
                   3931:             my $hostname=&hostname($primary);
                   3932:             $servers{$primary} = $hostname;
                   3933:         } else {
                   3934:             %servers = &get_servers($dom,'library');
                   3935:         }
1.841     albertel 3936: 	foreach my $tryserver (keys(%servers)) {
1.1172.2.82  raeburn  3937: 	    if (&reply('domroleput:'.$dom.':'.
                   3938: 	               $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   3939: 	        last;
                   3940: 	    } else {
1.841     albertel 3941: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   3942: 	    }
1.662     raeburn  3943:         }
                   3944:     }
1.186     www      3945:     $dumpcount++;
1.157     www      3946: }
                   3947: 
                   3948: sub courselog {
                   3949:     my $what=shift;
1.158     www      3950:     $what=time.':'.$what;
1.620     albertel 3951:     unless ($env{'request.course.id'}) { return ''; }
                   3952:     $coursedombuf{$env{'request.course.id'}}=
                   3953:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3954:     $coursenumbuf{$env{'request.course.id'}}=
                   3955:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   3956:     $coursehombuf{$env{'request.course.id'}}=
                   3957:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   3958:     $coursedescrbuf{$env{'request.course.id'}}=
                   3959:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   3960:     $courseinstcodebuf{$env{'request.course.id'}}=
                   3961:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   3962:     $courseownerbuf{$env{'request.course.id'}}=
                   3963:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  3964:     $coursetypebuf{$env{'request.course.id'}}=
                   3965:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 3966:     if (defined $courselogs{$env{'request.course.id'}}) {
                   3967: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      3968:     } else {
1.620     albertel 3969: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      3970:     }
1.620     albertel 3971:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      3972: 	&flushcourselogs();
                   3973:     }
1.158     www      3974: }
                   3975: 
                   3976: sub courseacclog {
                   3977:     my $fnsymb=shift;
1.620     albertel 3978:     unless ($env{'request.course.id'}) { return ''; }
                   3979:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      3980:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      3981:         $what.=':POST';
1.583     matthew  3982:         # FIXME: Probably ought to escape things....
1.800     albertel 3983: 	foreach my $key (keys(%env)) {
                   3984:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  3985:                 my $formitem = $1;
                   3986:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   3987:                     $what.=':'.$formitem.'='.$env{$key};
                   3988:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   3989:                     $what.=':'.$formitem.'='.$env{$key};
                   3990:                 }
1.158     www      3991:             }
1.191     harris41 3992:         }
1.583     matthew  3993:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   3994:         # FIXME: We should not be depending on a form parameter that someone
                   3995:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 3996:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  3997:             $what.= ':POST';
                   3998:             # FIXME: Probably ought to escape things....
                   3999:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4000:                                  'crsdiscuss') {
1.620     albertel 4001:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4002:             }
                   4003:         }
1.158     www      4004:     }
                   4005:     &courselog($what);
1.149     www      4006: }
                   4007: 
1.185     www      4008: sub countacc {
                   4009:     my $url=&declutter(shift);
1.458     matthew  4010:     return if (! defined($url) || $url eq '');
1.620     albertel 4011:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4012: #
                   4013: # Mark that this url was used in this course
                   4014: #
1.620     albertel 4015:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4016: #
                   4017: # Increase the access count for this resource in this child process
                   4018: #
1.281     www      4019:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4020:     $accesshash{$key}++;
1.185     www      4021: }
1.349     www      4022: 
1.361     www      4023: sub linklog {
                   4024:     my ($from,$to)=@_;
                   4025:     $from=&declutter($from);
                   4026:     $to=&declutter($to);
                   4027:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4028:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4029: }
1.1160    www      4030: 
                   4031: sub statslog {
                   4032:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4033:     if ($users<2) { return; }
                   4034:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4035:             'course'       => $env{'request.course.id'},
                   4036:             'sections'     => '"all"',
                   4037:             'num_students' => $users,
                   4038:             'part'         => $part,
                   4039:             'symb'         => $symb,
                   4040:             'mean_tries'   => $av_attempts,
                   4041:             'deg_of_diff'  => $degdiff});
                   4042:     foreach my $key (keys(%dynstore)) {
                   4043:         $accesshash{$key}=$dynstore{$key};
                   4044:     }
                   4045: }
1.361     www      4046:   
1.349     www      4047: sub userrolelog {
                   4048:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4049:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4050:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4051:        $userrolehash
                   4052:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4053:                     =$tend.':'.$tstart;
1.662     raeburn  4054:     }
1.1169    droeschl 4055:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4056:        $userrolehash
                   4057:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4058:                     =$tend.':'.$tstart;
                   4059:     }
1.1172.2.84  raeburn  4060:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh)/ ) {
1.662     raeburn  4061:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4062:        $domainrolehash
                   4063:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4064:                     = $tend.':'.$tstart;
                   4065:     }
1.351     www      4066: }
                   4067: 
1.957     raeburn  4068: sub courserolelog {
                   4069:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  4070:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4071:         my $cdom = $1;
                   4072:         my $cnum = $2;
                   4073:         my $sec = $3;
                   4074:         my $namespace = 'rolelog';
                   4075:         my %storehash = (
                   4076:                            role    => $trole,
                   4077:                            start   => $tstart,
                   4078:                            end     => $tend,
                   4079:                            selfenroll => $selfenroll,
                   4080:                            context    => $context,
                   4081:                         );
                   4082:         if ($trole eq 'gr') {
                   4083:             $namespace = 'groupslog';
                   4084:             $storehash{'group'} = $sec;
                   4085:         } else {
                   4086:             $storehash{'section'} = $sec;
                   4087:         }
                   4088:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4089:                    $domain,$cnum,$cdom);
                   4090:         if (($trole ne 'st') || ($sec ne '')) {
                   4091:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4092:         }
                   4093:     }
                   4094:     return;
                   4095: }
                   4096: 
1.1172.2.9  raeburn  4097: sub domainrolelog {
                   4098:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4099:     if ($area =~ m{^/($match_domain)/$}) {
                   4100:         my $cdom = $1;
                   4101:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4102:         my $namespace = 'rolelog';
                   4103:         my %storehash = (
                   4104:                            role    => $trole,
                   4105:                            start   => $tstart,
                   4106:                            end     => $tend,
                   4107:                            context => $context,
                   4108:                         );
                   4109:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4110:                    $domain,$domconfiguser,$cdom);
                   4111:     }
                   4112:     return;
                   4113: 
                   4114: }
                   4115: 
                   4116: sub coauthorrolelog {
                   4117:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4118:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4119:         my $audom = $1;
                   4120:         my $auname = $2;
                   4121:         my $namespace = 'rolelog';
                   4122:         my %storehash = (
                   4123:                            role    => $trole,
                   4124:                            start   => $tstart,
                   4125:                            end     => $tend,
                   4126:                            context => $context,
                   4127:                         );
                   4128:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4129:                    $domain,$auname,$audom);
                   4130:     }
                   4131:     return;
                   4132: }
                   4133: 
1.351     www      4134: sub get_course_adv_roles {
1.948     raeburn  4135:     my ($cid,$codes) = @_;
1.620     albertel 4136:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4137:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4138:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4139:     my %nothide=();
1.800     albertel 4140:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4141:         if ($user !~ /:/) {
                   4142: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4143:         } else {
                   4144:             $nothide{$user}=1;
                   4145:         }
1.470     www      4146:     }
1.1172.2.23  raeburn  4147:     my @possdoms = ($coursehash{'domain'});
                   4148:     if ($coursehash{'checkforpriv'}) {
                   4149:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4150:     }
1.351     www      4151:     my %returnhash=();
                   4152:     my %dumphash=
                   4153:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4154:     my $now=time;
1.997     raeburn  4155:     my %privileged;
1.1000    raeburn  4156:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4157: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4158:         if (($tstart) && ($tstart<0)) { next; }
                   4159:         if (($tend) && ($tend<$now)) { next; }
                   4160:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4161:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4162: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  4163:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4164:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4165: 	if ($role eq 'cr') { next; }
1.948     raeburn  4166:         if ($codes) {
                   4167:             if ($section) { $role .= ':'.$section; }
                   4168:             if ($returnhash{$role}) {
                   4169:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4170:             } else {
                   4171:                 $returnhash{$role}=$username.':'.$domain;
                   4172:             }
1.351     www      4173:         } else {
1.988     raeburn  4174:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4175:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4176:             if ($returnhash{$key}) {
                   4177: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4178:             } else {
                   4179:                 $returnhash{$key}=$username.':'.$domain;
                   4180:             }
1.351     www      4181:         }
1.948     raeburn  4182:     }
1.400     www      4183:     return %returnhash;
                   4184: }
                   4185: 
                   4186: sub get_my_roles {
1.937     raeburn  4187:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4188:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4189:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4190:     my (%dumphash,%nothide);
1.1086    raeburn  4191:     if ($context eq 'userroles') {
1.1166    raeburn  4192:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4193:     } else {
1.1172.2.23  raeburn  4194:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4195:         if ($hidepriv) {
                   4196:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4197:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4198:                 if ($user !~ /:/) {
                   4199:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4200:                 } else {
                   4201:                     $nothide{$user} = 1;
                   4202:                 }
                   4203:             }
                   4204:         }
1.858     raeburn  4205:     }
1.400     www      4206:     my %returnhash=();
                   4207:     my $now=time;
1.999     raeburn  4208:     my %privileged;
1.800     albertel 4209:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4210:         my ($role,$tend,$tstart);
                   4211:         if ($context eq 'userroles') {
1.1149    raeburn  4212:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4213: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4214:         } else {
                   4215:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4216:         }
1.400     www      4217:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4218:         my $status = 'active';
1.939     raeburn  4219:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4220:             $status = 'previous';
                   4221:         } 
                   4222:         if (($tstart) && ($now<$tstart)) {
                   4223:             $status = 'future';
                   4224:         }
                   4225:         if (ref($types) eq 'ARRAY') {
                   4226:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4227:                 next;
                   4228:             } 
                   4229:         } else {
                   4230:             if ($status ne 'active') {
                   4231:                 next;
                   4232:             }
                   4233:         }
1.867     raeburn  4234:         my ($rolecode,$username,$domain,$section,$area);
                   4235:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  4236:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4237:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4238:         } else {
                   4239:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4240:         }
1.832     raeburn  4241:         if (ref($roledoms) eq 'ARRAY') {
                   4242:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4243:                 next;
                   4244:             }
                   4245:         }
                   4246:         if (ref($roles) eq 'ARRAY') {
                   4247:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4248:                 if ($role =~ /^cr\//) {
                   4249:                     if (!grep(/^cr$/,@{$roles})) {
                   4250:                         next;
                   4251:                     }
1.1104    raeburn  4252:                 } elsif ($role =~ /^gr\//) {
                   4253:                     if (!grep(/^gr$/,@{$roles})) {
                   4254:                         next;
                   4255:                     }
1.922     raeburn  4256:                 } else {
                   4257:                     next;
                   4258:                 }
1.832     raeburn  4259:             }
1.867     raeburn  4260:         }
1.937     raeburn  4261:         if ($hidepriv) {
1.1172.2.23  raeburn  4262:             my @privroles = ('dc','su');
1.999     raeburn  4263:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  4264:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4265:             } else {
1.1172.2.23  raeburn  4266:                 my $possdoms = [$domain];
                   4267:                 if (ref($roledoms) eq 'ARRAY') {
                   4268:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  4269:                 }
1.1172.2.23  raeburn  4270:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4271:                     if (!$nothide{$username.':'.$domain}) {
                   4272:                         next;
                   4273:                     }
                   4274:                 }
1.937     raeburn  4275:             }
                   4276:         }
1.933     raeburn  4277:         if ($withsec) {
                   4278:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4279:                 $tstart.':'.$tend;
                   4280:         } else {
                   4281:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4282:         }
1.832     raeburn  4283:     }
1.373     www      4284:     return %returnhash;
1.399     www      4285: }
                   4286: 
                   4287: # ----------------------------------------------------- Frontpage Announcements
                   4288: #
                   4289: #
                   4290: 
                   4291: sub postannounce {
                   4292:     my ($server,$text)=@_;
1.844     albertel 4293:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4294:     unless ($text=~/\w/) { $text=''; }
                   4295:     return &reply('setannounce:'.&escape($text),$server);
                   4296: }
                   4297: 
                   4298: sub getannounce {
1.448     albertel 4299: 
                   4300:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4301: 	my $announcement='';
1.800     albertel 4302: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4303: 	close($fh);
1.399     www      4304: 	if ($announcement=~/\w/) { 
                   4305: 	    return 
                   4306:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4307:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4308: 	} else {
                   4309: 	    return '';
                   4310: 	}
                   4311:     } else {
                   4312: 	return '';
                   4313:     }
1.351     www      4314: }
1.353     www      4315: 
                   4316: # ---------------------------------------------------------- Course ID routines
                   4317: # Deal with domain's nohist_courseid.db files
                   4318: #
                   4319: 
                   4320: sub courseidput {
1.921     raeburn  4321:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4322:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4323:     my $outcome;
                   4324:     if ($caller eq 'timeonly') {
                   4325:         my $cids = '';
                   4326:         foreach my $item (keys(%$storehash)) {
                   4327:             $cids.=&escape($item).'&';
                   4328:         }
                   4329:         $cids=~s/\&$//;
                   4330:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4331:                           $coursehome);       
                   4332:     } else {
                   4333:         my $items = '';
                   4334:         foreach my $item (keys(%$storehash)) {
                   4335:             $items.= &escape($item).'='.
                   4336:                      &freeze_escape($$storehash{$item}).'&';
                   4337:         }
                   4338:         $items=~s/\&$//;
                   4339:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4340:                           $coursehome);
1.918     raeburn  4341:     }
                   4342:     if ($outcome eq 'unknown_cmd') {
                   4343:         my $what;
                   4344:         foreach my $cid (keys(%$storehash)) {
                   4345:             $what .= &escape($cid).'=';
1.921     raeburn  4346:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4347:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4348:             }
                   4349:             $what =~ s/\:$/&/;
                   4350:         }
                   4351:         $what =~ s/\&$//;  
                   4352:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4353:     } else {
                   4354:         return $outcome;
                   4355:     }
1.353     www      4356: }
                   4357: 
                   4358: sub courseiddump {
1.921     raeburn  4359:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4360:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4361:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38  raeburn  4362:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68  raeburn  4363:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  4364:     my $as_hash = 1;
                   4365:     my %returnhash;
                   4366:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4367:     my %libserv = &all_library();
                   4368:     foreach my $tryserver (keys(%libserv)) {
                   4369:         if ( (  $hostidflag == 1 
                   4370: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4371: 	     || (!defined($hostidflag)) ) {
                   4372: 
1.918     raeburn  4373: 	    if (($domfilter eq '') ||
                   4374: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  4375:                 my $rep;
                   4376:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   4377:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   4378:                         join(":", (&host_domain($tryserver), $sincefilter,
                   4379:                                 &escape($descfilter), &escape($instcodefilter),
                   4380:                                 &escape($ownerfilter), &escape($coursefilter),
                   4381:                                 &escape($typefilter), &escape($regexp_ok),
                   4382:                                 $as_hash, &escape($selfenrollonly),
                   4383:                                 &escape($catfilter), $showhidden, $caller,
                   4384:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   4385:                                 &escape($createdbefore), &escape($createdafter),
1.1172.2.68  raeburn  4386:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   4387:                                 $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22  raeburn  4388:                 } else {
                   4389:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4390:                              $sincefilter.':'.&escape($descfilter).':'.
                   4391:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   4392:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   4393:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   4394:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   4395:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   4396:                              &escape($cc_clone).':'.$cloneonly.':'.
                   4397:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68  raeburn  4398:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   4399:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22  raeburn  4400:                 }
                   4401: 
1.918     raeburn  4402:                 my @pairs=split(/\&/,$rep);
                   4403:                 foreach my $item (@pairs) {
                   4404:                     my ($key,$value)=split(/\=/,$item,2);
                   4405:                     $key = &unescape($key);
                   4406:                     next if ($key =~ /^error: 2 /);
                   4407:                     my $result = &thaw_unescape($value);
                   4408:                     if (ref($result) eq 'HASH') {
                   4409:                         $returnhash{$key}=$result;
                   4410:                     } else {
1.921     raeburn  4411:                         my @responses = split(/:/,$value);
                   4412:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4413:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4414:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4415:                         }
1.1008    raeburn  4416:                     }
1.353     www      4417:                 }
                   4418:             }
                   4419:         }
                   4420:     }
                   4421:     return %returnhash;
                   4422: }
                   4423: 
1.1055    raeburn  4424: sub courselastaccess {
                   4425:     my ($cdom,$cnum,$hostidref) = @_;
                   4426:     my %returnhash;
                   4427:     if ($cdom && $cnum) {
                   4428:         my $chome = &homeserver($cnum,$cdom);
                   4429:         if ($chome ne 'no_host') {
                   4430:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4431:             &extract_lastaccess(\%returnhash,$rep);
                   4432:         }
                   4433:     } else {
                   4434:         if (!$cdom) { $cdom=''; }
                   4435:         my %libserv = &all_library();
                   4436:         foreach my $tryserver (keys(%libserv)) {
                   4437:             if (ref($hostidref) eq 'ARRAY') {
                   4438:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4439:             } 
                   4440:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4441:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4442:                 &extract_lastaccess(\%returnhash,$rep);
                   4443:             }
                   4444:         }
                   4445:     }
                   4446:     return %returnhash;
                   4447: }
                   4448: 
                   4449: sub extract_lastaccess {
                   4450:     my ($returnhash,$rep) = @_;
                   4451:     if (ref($returnhash) eq 'HASH') {
                   4452:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4453:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4454:                  $rep eq '') {
                   4455:             my @pairs=split(/\&/,$rep);
                   4456:             foreach my $item (@pairs) {
                   4457:                 my ($key,$value)=split(/\=/,$item,2);
                   4458:                 $key = &unescape($key);
                   4459:                 next if ($key =~ /^error: 2 /);
                   4460:                 $returnhash->{$key} = &thaw_unescape($value);
                   4461:             }
                   4462:         }
                   4463:     }
                   4464:     return;
                   4465: }
                   4466: 
1.658     raeburn  4467: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4468: 
                   4469: sub dcmailput {
1.685     raeburn  4470:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4471:     my $status = &Apache::lonnet::critical(
1.740     www      4472:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4473:        &escape($message),$server);
1.662     raeburn  4474:     return $status;
                   4475: }
                   4476: 
1.658     raeburn  4477: sub dcmaildump {
                   4478:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4479:     my %returnhash=();
1.846     albertel 4480: 
                   4481:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4482:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4483:                                                          &escape($enddate).':';
                   4484: 	my @esc_senders=map { &escape($_)} @$senders;
                   4485: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4486: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4487:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4488:             if (($key) && ($value)) {
                   4489:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4490:             }
                   4491:         }
                   4492:     }
                   4493:     return %returnhash;
                   4494: }
1.662     raeburn  4495: # ---------------------------------------------------------- Domain roles
                   4496: 
                   4497: sub get_domain_roles {
                   4498:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4499:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4500:         $startdate = '.';
                   4501:     }
1.1018    raeburn  4502:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4503:         $enddate = '.';
                   4504:     }
1.922     raeburn  4505:     my $rolelist;
                   4506:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  4507:         $rolelist = join('&',@{$roles});
1.922     raeburn  4508:     }
1.662     raeburn  4509:     my %personnel = ();
1.841     albertel 4510: 
                   4511:     my %servers = &get_servers($dom,'library');
                   4512:     foreach my $tryserver (keys(%servers)) {
                   4513: 	%{$personnel{$tryserver}}=();
                   4514: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4515: 					    &escape($startdate).':'.
                   4516: 					    &escape($enddate).':'.
                   4517: 					    &escape($rolelist), $tryserver))) {
                   4518: 	    my ($key,$value) = split(/\=/,$line,2);
                   4519: 	    if (($key) && ($value)) {
                   4520: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4521: 	    }
                   4522: 	}
1.662     raeburn  4523:     }
                   4524:     return %personnel;
                   4525: }
1.658     raeburn  4526: 
1.1057    www      4527: # ----------------------------------------------------------- Interval timing 
1.149     www      4528: 
1.1153    www      4529: {
                   4530: # Caches needed for speedup of navmaps
                   4531: # We don't want to cache this for very long at all (5 seconds at most)
                   4532: # 
                   4533: # The user for whom we cache
                   4534: my $cachedkey='';
                   4535: # The cached times for this user
                   4536: my %cachedtimes=();
                   4537: # When this was last done
1.1172.2.66  raeburn  4538: my $cachedtime='';
1.1153    www      4539: 
                   4540: sub load_all_first_access {
1.1154    raeburn  4541:     my ($uname,$udom)=@_;
1.1156    www      4542:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2  raeburn  4543:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  4544:         return;
                   4545:     }
                   4546:     $cachedtime=time;
                   4547:     $cachedkey=$uname.':'.$udom;
                   4548:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4549: }
                   4550: 
1.504     albertel 4551: sub get_first_access {
1.1162    raeburn  4552:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 4553:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4554:     if ($argsymb) { $symb=$argsymb; }
                   4555:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4556:     if ($argmap) { $map = $argmap; }
1.926     albertel 4557:     if ($type eq 'course') {
                   4558: 	$res='course';
                   4559:     } elsif ($type eq 'map') {
1.588     albertel 4560: 	$res=&symbread($map);
                   4561:     } else {
                   4562: 	$res=$symb;
                   4563:     }
1.1153    www      4564:     &load_all_first_access($uname,$udom);
                   4565:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4566: }
                   4567: 
                   4568: sub set_first_access {
1.1162    raeburn  4569:     my ($type,$interval)=@_;
1.790     albertel 4570:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4571:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4572:     if ($type eq 'course') {
                   4573: 	$res='course';
                   4574:     } elsif ($type eq 'map') {
1.588     albertel 4575: 	$res=&symbread($map);
                   4576:     } else {
                   4577: 	$res=$symb;
                   4578:     }
1.1153    www      4579:     $cachedkey='';
1.1162    raeburn  4580:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4581:     if (!$firstaccess) {
1.1162    raeburn  4582:         my $start = time;
                   4583: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4584:                           $udom,$uname);
                   4585:         if ($putres eq 'ok') {
                   4586:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4587:                  $udom,$uname); 
                   4588:             &appenv(
                   4589:                      {
                   4590:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4591:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4592:                      }
                   4593:                   );
                   4594:         }
                   4595:         return $putres;
1.505     albertel 4596:     }
                   4597:     return 'already_set';
1.504     albertel 4598: }
1.1153    www      4599: }
1.1172.2.32  raeburn  4600: 
                   4601: sub checkout {
                   4602:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   4603:     my $now=time;
                   4604:     my $lonhost=$perlvar{'lonHostID'};
                   4605:     my $infostr=&escape(
                   4606:                  'CHECKOUTTOKEN&'.
                   4607:                  $tuname.'&'.
                   4608:                  $tudom.'&'.
                   4609:                  $tcrsid.'&'.
                   4610:                  $symb.'&'.
                   4611:                  $now.'&'.$ENV{'REMOTE_ADDR'});
                   4612:     my $token=&reply('tmpput:'.$infostr,$lonhost);
                   4613:     if ($token=~/^error\:/) {
                   4614:         &logthis("<font color=\"blue\">WARNING: ".
                   4615:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   4616:                  "</font>");
                   4617:         return '';
                   4618:     }
                   4619: 
                   4620:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   4621:     $token=~tr/a-z/A-Z/;
                   4622: 
                   4623:     my %infohash=('resource.0.outtoken' => $token,
                   4624:                   'resource.0.checkouttime' => $now,
                   4625:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
                   4626: 
                   4627:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   4628:        return '';
                   4629:     } else {
                   4630:         &logthis("<font color=\"blue\">WARNING: ".
                   4631:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   4632:                  "</font>");
                   4633:     }
                   4634: 
                   4635:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   4636:                          &escape('Checkout '.$infostr.' - '.
                   4637:                                                  $token)) ne 'ok') {
                   4638:         return '';
                   4639:     } else {
                   4640:         &logthis("<font color=\"blue\">WARNING: ".
                   4641:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   4642:                  "</font>");
                   4643:     }
                   4644:     return $token;
                   4645: }
                   4646: 
                   4647: # ------------------------------------------------------------ Check in an item
                   4648: 
                   4649: sub checkin {
                   4650:     my $token=shift;
                   4651:     my $now=time;
                   4652:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   4653:     $lonhost=~tr/A-Z/a-z/;
                   4654:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
                   4655:     $dtoken=~s/\W/\_/g;
                   4656:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                   4657:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   4658: 
                   4659:     unless (($tuname) && ($tudom)) {
                   4660:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   4661:         return '';
                   4662:     }
                   4663: 
                   4664:     unless (&allowed('mgr',$tcrsid)) {
                   4665:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   4666:                  $env{'user.name'}.' - '.$env{'user.domain'});
                   4667:         return '';
                   4668:     }
                   4669: 
                   4670:     my %infohash=('resource.0.intoken' => $token,
                   4671:                   'resource.0.checkintime' => $now,
                   4672:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
                   4673: 
                   4674:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   4675:        return '';
                   4676:     }
                   4677: 
                   4678:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   4679:                          &escape('Checkin - '.$token)) ne 'ok') {
                   4680:         return '';
                   4681:     }
                   4682: 
                   4683:     return ($symb,$tuname,$tudom,$tcrsid);
                   4684: }
                   4685: 
1.110     www      4686: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4687: 
                   4688: sub expirespread {
                   4689:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4690:     my $cid=$env{'request.course.id'}; 
1.110     www      4691:     if ($cid) {
                   4692:        my $now=time;
                   4693:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4694:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4695:                             $env{'course.'.$cid.'.num'}.
1.110     www      4696: 	        	    ':nohist_expirationdates:'.
                   4697:                             &escape($key).'='.$now,
1.620     albertel 4698:                             $env{'course.'.$cid.'.home'})
1.110     www      4699:     }
                   4700:     return 'ok';
1.14      www      4701: }
                   4702: 
1.109     www      4703: # ----------------------------------------------------- Devalidate Spreadsheets
                   4704: 
                   4705: sub devalidate {
1.325     www      4706:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4707:     my $cid=$env{'request.course.id'}; 
1.109     www      4708:     if ($cid) {
1.391     matthew  4709:         # delete the stored spreadsheets for
                   4710:         # - the student level sheet of this user in course's homespace
                   4711:         # - the assessment level sheet for this resource 
                   4712:         #   for this user in user's homespace
1.553     albertel 4713: 	# - current conditional state info
1.325     www      4714: 	my $key=$uname.':'.$udom.':';
1.109     www      4715:         my $status=
1.299     matthew  4716: 	    &del('nohist_calculatedsheets',
1.391     matthew  4717: 		 [$key.'studentcalc:'],
1.620     albertel 4718: 		 $env{'course.'.$cid.'.domain'},
                   4719: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4720: 		.' '.
                   4721: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4722: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4723:         unless ($status eq 'ok ok') {
                   4724:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4725:                     $uname.' at '.$udom.' for '.
1.109     www      4726: 		    $symb.': '.$status);
1.133     albertel 4727:         }
1.553     albertel 4728: 	&delenv('user.state.'.$cid);
1.109     www      4729:     }
                   4730: }
                   4731: 
1.265     albertel 4732: sub get_scalar {
                   4733:     my ($string,$end) = @_;
                   4734:     my $value;
                   4735:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4736: 	$value = $1;
                   4737:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4738: 	$value = $1;
                   4739:     }
                   4740:     return &unescape($value);
                   4741: }
                   4742: 
                   4743: sub array2str {
                   4744:   my (@array) = @_;
                   4745:   my $result=&arrayref2str(\@array);
                   4746:   $result=~s/^__ARRAY_REF__//;
                   4747:   $result=~s/__END_ARRAY_REF__$//;
                   4748:   return $result;
                   4749: }
                   4750: 
1.204     albertel 4751: sub arrayref2str {
                   4752:   my ($arrayref) = @_;
1.265     albertel 4753:   my $result='__ARRAY_REF__';
1.204     albertel 4754:   foreach my $elem (@$arrayref) {
1.265     albertel 4755:     if(ref($elem) eq 'ARRAY') {
                   4756:       $result.=&arrayref2str($elem).'&';
                   4757:     } elsif(ref($elem) eq 'HASH') {
                   4758:       $result.=&hashref2str($elem).'&';
                   4759:     } elsif(ref($elem)) {
                   4760:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4761:     } else {
                   4762:       $result.=&escape($elem).'&';
                   4763:     }
                   4764:   }
                   4765:   $result=~s/\&$//;
1.265     albertel 4766:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4767:   return $result;
                   4768: }
                   4769: 
1.168     albertel 4770: sub hash2str {
1.204     albertel 4771:   my (%hash) = @_;
                   4772:   my $result=&hashref2str(\%hash);
1.265     albertel 4773:   $result=~s/^__HASH_REF__//;
                   4774:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4775:   return $result;
                   4776: }
                   4777: 
                   4778: sub hashref2str {
                   4779:   my ($hashref)=@_;
1.265     albertel 4780:   my $result='__HASH_REF__';
1.800     albertel 4781:   foreach my $key (sort(keys(%$hashref))) {
                   4782:     if (ref($key) eq 'ARRAY') {
                   4783:       $result.=&arrayref2str($key).'=';
                   4784:     } elsif (ref($key) eq 'HASH') {
                   4785:       $result.=&hashref2str($key).'=';
                   4786:     } elsif (ref($key)) {
1.265     albertel 4787:       $result.='=';
1.800     albertel 4788:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 4789:     } else {
1.1132    raeburn  4790: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 4791:     }
                   4792: 
1.800     albertel 4793:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   4794:       $result.=&arrayref2str($hashref->{$key}).'&';
                   4795:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   4796:       $result.=&hashref2str($hashref->{$key}).'&';
                   4797:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4798:        $result.='&';
1.800     albertel 4799:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4800:     } else {
1.800     albertel 4801:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4802:     }
                   4803:   }
1.168     albertel 4804:   $result=~s/\&$//;
1.265     albertel 4805:   $result .= '__END_HASH_REF__';
1.168     albertel 4806:   return $result;
                   4807: }
                   4808: 
                   4809: sub str2hash {
1.265     albertel 4810:     my ($string)=@_;
                   4811:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4812:     return %$hash;
                   4813: }
                   4814: 
                   4815: sub str2hashref {
1.168     albertel 4816:   my ($string) = @_;
1.265     albertel 4817: 
                   4818:   my %hash;
                   4819: 
                   4820:   if($string !~ /^__HASH_REF__/) {
                   4821:       if (! ($string eq '' || !defined($string))) {
                   4822: 	  $hash{'error'}='Not hash reference';
                   4823:       }
                   4824:       return (\%hash, $string);
                   4825:   }
                   4826: 
                   4827:   $string =~ s/^__HASH_REF__//;
                   4828: 
                   4829:   while($string !~ /^__END_HASH_REF__/) {
                   4830:       #key
                   4831:       my $key='';
                   4832:       if($string =~ /^__HASH_REF__/) {
                   4833:           ($key, $string)=&str2hashref($string);
                   4834:           if(defined($key->{'error'})) {
                   4835:               $hash{'error'}='Bad data';
                   4836:               return (\%hash, $string);
                   4837:           }
                   4838:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4839:           ($key, $string)=&str2arrayref($string);
                   4840:           if($key->[0] eq 'Array reference error') {
                   4841:               $hash{'error'}='Bad data';
                   4842:               return (\%hash, $string);
                   4843:           }
                   4844:       } else {
                   4845:           $string =~ s/^(.*?)=//;
1.267     albertel 4846: 	  $key=&unescape($1);
1.265     albertel 4847:       }
                   4848:       $string =~ s/^=//;
                   4849: 
                   4850:       #value
                   4851:       my $value='';
                   4852:       if($string =~ /^__HASH_REF__/) {
                   4853:           ($value, $string)=&str2hashref($string);
                   4854:           if(defined($value->{'error'})) {
                   4855:               $hash{'error'}='Bad data';
                   4856:               return (\%hash, $string);
                   4857:           }
                   4858:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4859:           ($value, $string)=&str2arrayref($string);
                   4860:           if($value->[0] eq 'Array reference error') {
                   4861:               $hash{'error'}='Bad data';
                   4862:               return (\%hash, $string);
                   4863:           }
                   4864:       } else {
                   4865: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4866:       }
                   4867:       $string =~ s/^&//;
                   4868: 
                   4869:       $hash{$key}=$value;
1.204     albertel 4870:   }
1.265     albertel 4871: 
                   4872:   $string =~ s/^__END_HASH_REF__//;
                   4873: 
                   4874:   return (\%hash, $string);
1.204     albertel 4875: }
                   4876: 
                   4877: sub str2array {
1.265     albertel 4878:     my ($string)=@_;
                   4879:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4880:     return @$array;
                   4881: }
                   4882: 
                   4883: sub str2arrayref {
1.204     albertel 4884:   my ($string) = @_;
1.265     albertel 4885:   my @array;
                   4886: 
                   4887:   if($string !~ /^__ARRAY_REF__/) {
                   4888:       if (! ($string eq '' || !defined($string))) {
                   4889: 	  $array[0]='Array reference error';
                   4890:       }
                   4891:       return (\@array, $string);
                   4892:   }
                   4893: 
                   4894:   $string =~ s/^__ARRAY_REF__//;
                   4895: 
                   4896:   while($string !~ /^__END_ARRAY_REF__/) {
                   4897:       my $value='';
                   4898:       if($string =~ /^__HASH_REF__/) {
                   4899:           ($value, $string)=&str2hashref($string);
                   4900:           if(defined($value->{'error'})) {
                   4901:               $array[0] ='Array reference error';
                   4902:               return (\@array, $string);
                   4903:           }
                   4904:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4905:           ($value, $string)=&str2arrayref($string);
                   4906:           if($value->[0] eq 'Array reference error') {
                   4907:               $array[0] ='Array reference error';
                   4908:               return (\@array, $string);
                   4909:           }
                   4910:       } else {
                   4911: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   4912:       }
                   4913:       $string =~ s/^&//;
                   4914: 
                   4915:       push(@array, $value);
1.191     harris41 4916:   }
1.265     albertel 4917: 
                   4918:   $string =~ s/^__END_ARRAY_REF__//;
                   4919: 
                   4920:   return (\@array, $string);
1.168     albertel 4921: }
                   4922: 
1.167     albertel 4923: # -------------------------------------------------------------------Temp Store
                   4924: 
1.168     albertel 4925: sub tmpreset {
                   4926:   my ($symb,$namespace,$domain,$stuname) = @_;
                   4927:   if (!$symb) {
                   4928:     $symb=&symbread();
1.620     albertel 4929:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4930:   }
                   4931:   $symb=escape($symb);
                   4932: 
1.620     albertel 4933:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 4934:   $namespace=~s/\//\_/g;
                   4935:   $namespace=~s/\W//g;
                   4936: 
1.620     albertel 4937:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4938:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4939:   if ($domain eq 'public' && $stuname eq 'public') {
                   4940:       $stuname=$ENV{'REMOTE_ADDR'};
                   4941:   }
1.1117    foxr     4942:   my $path=LONCAPA::tempdir();
1.168     albertel 4943:   my %hash;
                   4944:   if (tie(%hash,'GDBM_File',
                   4945: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4946: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  4947:     foreach my $key (keys(%hash)) {
1.180     albertel 4948:       if ($key=~ /:$symb/) {
1.168     albertel 4949: 	delete($hash{$key});
                   4950:       }
                   4951:     }
                   4952:   }
                   4953: }
                   4954: 
1.167     albertel 4955: sub tmpstore {
1.168     albertel 4956:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4957: 
                   4958:   if (!$symb) {
                   4959:     $symb=&symbread();
1.620     albertel 4960:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4961:   }
                   4962:   $symb=escape($symb);
                   4963: 
                   4964:   if (!$namespace) {
                   4965:     # I don't think we would ever want to store this for a course.
                   4966:     # it seems this will only be used if we don't have a course.
1.620     albertel 4967:     #$namespace=$env{'request.course.id'};
1.168     albertel 4968:     #if (!$namespace) {
1.620     albertel 4969:       $namespace=$env{'request.state'};
1.168     albertel 4970:     #}
                   4971:   }
                   4972:   $namespace=~s/\//\_/g;
                   4973:   $namespace=~s/\W//g;
1.620     albertel 4974:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4975:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4976:   if ($domain eq 'public' && $stuname eq 'public') {
                   4977:       $stuname=$ENV{'REMOTE_ADDR'};
                   4978:   }
1.168     albertel 4979:   my $now=time;
                   4980:   my %hash;
1.1117    foxr     4981:   my $path=LONCAPA::tempdir();
1.168     albertel 4982:   if (tie(%hash,'GDBM_File',
                   4983: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4984: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 4985:     $hash{"version:$symb"}++;
                   4986:     my $version=$hash{"version:$symb"};
                   4987:     my $allkeys=''; 
                   4988:     foreach my $key (keys(%$storehash)) {
                   4989:       $allkeys.=$key.':';
1.591     albertel 4990:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 4991:     }
                   4992:     $hash{"$version:$symb:timestamp"}=$now;
                   4993:     $allkeys.='timestamp';
                   4994:     $hash{"$version:keys:$symb"}=$allkeys;
                   4995:     if (untie(%hash)) {
                   4996:       return 'ok';
                   4997:     } else {
                   4998:       return "error:$!";
                   4999:     }
                   5000:   } else {
                   5001:     return "error:$!";
                   5002:   }
                   5003: }
1.167     albertel 5004: 
1.168     albertel 5005: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5006: 
1.168     albertel 5007: sub tmprestore {
                   5008:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5009: 
1.168     albertel 5010:   if (!$symb) {
                   5011:     $symb=&symbread();
1.620     albertel 5012:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5013:   }
                   5014:   $symb=escape($symb);
                   5015: 
1.620     albertel 5016:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5017: 
1.620     albertel 5018:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5019:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5020:   if ($domain eq 'public' && $stuname eq 'public') {
                   5021:       $stuname=$ENV{'REMOTE_ADDR'};
                   5022:   }
1.168     albertel 5023:   my %returnhash;
                   5024:   $namespace=~s/\//\_/g;
                   5025:   $namespace=~s/\W//g;
                   5026:   my %hash;
1.1117    foxr     5027:   my $path=LONCAPA::tempdir();
1.168     albertel 5028:   if (tie(%hash,'GDBM_File',
                   5029: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5030: 	  &GDBM_READER(),0640)) {
1.168     albertel 5031:     my $version=$hash{"version:$symb"};
                   5032:     $returnhash{'version'}=$version;
                   5033:     my $scope;
                   5034:     for ($scope=1;$scope<=$version;$scope++) {
                   5035:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5036:       my @keys=split(/:/,$vkeys);
                   5037:       my $key;
                   5038:       $returnhash{"$scope:keys"}=$vkeys;
                   5039:       foreach $key (@keys) {
1.591     albertel 5040: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   5041: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 5042:       }
                   5043:     }
1.168     albertel 5044:     if (!(untie(%hash))) {
                   5045:       return "error:$!";
                   5046:     }
                   5047:   } else {
                   5048:     return "error:$!";
                   5049:   }
                   5050:   return %returnhash;
1.167     albertel 5051: }
                   5052: 
1.9       www      5053: # ----------------------------------------------------------------------- Store
                   5054: 
                   5055: sub store {
1.1172.2.64  raeburn  5056:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5057:     my $home='';
                   5058: 
1.168     albertel 5059:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5060: 
1.213     www      5061:     $symb=&symbclean($symb);
1.122     albertel 5062:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5063: 
1.620     albertel 5064:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5065:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5066: 
                   5067:     &devalidate($symb,$stuname,$domain);
1.109     www      5068: 
                   5069:     $symb=escape($symb);
1.187     www      5070:     if (!$namespace) { 
1.620     albertel 5071:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5072:           return ''; 
                   5073:        } 
                   5074:     }
1.620     albertel 5075:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5076: 
                   5077:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5078:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   5079: 
1.12      www      5080:     my $namevalue='';
1.800     albertel 5081:     foreach my $key (keys(%$storehash)) {
                   5082:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5083:     }
1.12      www      5084:     $namevalue=~s/\&$//;
1.187     www      5085:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64  raeburn  5086:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      5087: }
                   5088: 
1.47      www      5089: # -------------------------------------------------------------- Critical Store
                   5090: 
                   5091: sub cstore {
1.1172.2.64  raeburn  5092:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5093:     my $home='';
                   5094: 
1.168     albertel 5095:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5096: 
1.213     www      5097:     $symb=&symbclean($symb);
1.122     albertel 5098:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5099: 
1.620     albertel 5100:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5101:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5102: 
                   5103:     &devalidate($symb,$stuname,$domain);
1.109     www      5104: 
                   5105:     $symb=escape($symb);
1.187     www      5106:     if (!$namespace) { 
1.620     albertel 5107:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5108:           return ''; 
                   5109:        } 
                   5110:     }
1.620     albertel 5111:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5112: 
                   5113:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5114:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 5115: 
1.47      www      5116:     my $namevalue='';
1.800     albertel 5117:     foreach my $key (keys(%$storehash)) {
                   5118:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5119:     }
1.47      www      5120:     $namevalue=~s/\&$//;
1.187     www      5121:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      5122:     return critical
1.1172.2.64  raeburn  5123:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      5124: }
                   5125: 
1.9       www      5126: # --------------------------------------------------------------------- Restore
                   5127: 
                   5128: sub restore {
1.124     www      5129:     my ($symb,$namespace,$domain,$stuname) = @_;
                   5130:     my $home='';
                   5131: 
1.168     albertel 5132:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5133: 
1.122     albertel 5134:     if (!$symb) {
1.1172.2.26  raeburn  5135:         return if ($namespace eq 'courserequests');
                   5136:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 5137:     } else {
1.1172.2.26  raeburn  5138:         unless ($namespace eq 'courserequests') {
                   5139:             $symb=&escape(&symbclean($symb));
                   5140:         }
1.122     albertel 5141:     }
1.188     www      5142:     if (!$namespace) { 
1.620     albertel 5143:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      5144:           return ''; 
                   5145:        } 
                   5146:     }
1.620     albertel 5147:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5148:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   5149:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 5150:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   5151: 
1.12      www      5152:     my %returnhash=();
1.800     albertel 5153:     foreach my $line (split(/\&/,$answer)) {
                   5154: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 5155:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 5156:     }
1.75      www      5157:     my $version;
                   5158:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 5159:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   5160:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 5161:        }
1.75      www      5162:     }
1.13      www      5163:     return %returnhash;
1.34      www      5164: }
                   5165: 
                   5166: # ---------------------------------------------------------- Course Description
1.1118    foxr     5167: #
                   5168: #  
1.34      www      5169: 
                   5170: sub coursedescription {
1.731     albertel 5171:     my ($courseid,$args)=@_;
1.34      www      5172:     $courseid=~s/^\///;
1.49      www      5173:     $courseid=~s/\_/\//g;
1.34      www      5174:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 5175:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 5176:     my $normalid=$cdomain.'_'.$cnum;
                   5177:     # need to always cache even if we get errors otherwise we keep 
                   5178:     # trying and trying and trying to get the course description.
                   5179:     my %envhash=();
                   5180:     my %returnhash=();
1.731     albertel 5181:     
                   5182:     my $expiretime=600;
                   5183:     if ($env{'request.course.id'} eq $normalid) {
                   5184: 	$expiretime=120;
                   5185:     }
                   5186: 
                   5187:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   5188:     if (!$args->{'freshen_cache'}
                   5189: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   5190: 	foreach my $key (keys(%env)) {
                   5191: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   5192: 	    my ($setting) = $1;
                   5193: 	    $returnhash{$setting} = $env{$key};
                   5194: 	}
                   5195: 	return %returnhash;
                   5196:     }
                   5197: 
1.1118    foxr     5198:     # get the data again
                   5199: 
1.731     albertel 5200:     if (!$args->{'one_time'}) {
                   5201: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   5202:     }
1.811     albertel 5203: 
1.34      www      5204:     if ($chome ne 'no_host') {
1.302     albertel 5205:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 5206:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     5207: 	   my $username = $env{'user.name'}; # Defult username
                   5208: 	   if(defined $args->{'user'}) {
                   5209: 	       $username = $args->{'user'};
                   5210: 	   }
1.129     albertel 5211:            $returnhash{'home'}= $chome;
                   5212: 	   $returnhash{'domain'} = $cdomain;
                   5213: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  5214:            if (!defined($returnhash{'type'})) {
                   5215:                $returnhash{'type'} = 'Course';
                   5216:            }
1.130     albertel 5217:            while (my ($name,$value) = each %returnhash) {
1.53      www      5218:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 5219:            }
1.270     www      5220:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     5221:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     5222: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      5223:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   5224:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   5225:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      5226:        }
                   5227:     }
1.731     albertel 5228:     if (!$args->{'one_time'}) {
1.949     raeburn  5229: 	&appenv(\%envhash);
1.731     albertel 5230:     }
1.302     albertel 5231:     return %returnhash;
1.461     www      5232: }
                   5233: 
1.1080    raeburn  5234: sub update_released_required {
                   5235:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   5236:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   5237:         $cid = $env{'request.course.id'};
                   5238:         $cdom = $env{'course.'.$cid.'.domain'};
                   5239:         $cnum = $env{'course.'.$cid.'.num'};
                   5240:         $chome = $env{'course.'.$cid.'.home'};
                   5241:     }
                   5242:     if ($needsrelease) {
                   5243:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   5244:         my $needsupdate;
                   5245:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   5246:             $needsupdate = 1;
                   5247:         } else {
                   5248:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   5249:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   5250:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   5251:                 $needsupdate = 1;
                   5252:             }
                   5253:         }
                   5254:         if ($needsupdate) {
                   5255:             my %needshash = (
                   5256:                              'internal.releaserequired' => $needsrelease,
                   5257:                             );
                   5258:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   5259:             if ($putresult eq 'ok') {
                   5260:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   5261:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   5262:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   5263:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   5264:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   5265:                 }
                   5266:             }
                   5267:         }
                   5268:     }
                   5269:     return;
                   5270: }
                   5271: 
1.461     www      5272: # -------------------------------------------------See if a user is privileged
                   5273: 
                   5274: sub privileged {
1.1172.2.23  raeburn  5275:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5276:     my $now = time;
1.1172.2.23  raeburn  5277:     my $roles;
                   5278:     if (ref($possroles) eq 'ARRAY') {
                   5279:         $roles = $possroles;
                   5280:     } else {
                   5281:         $roles = ['dc','su'];
                   5282:     }
                   5283:     if (ref($possdomains) eq 'ARRAY') {
                   5284:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   5285:         foreach my $dom (@{$possdomains}) {
                   5286:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   5287:                 (ref($privileged{$dom}) eq 'HASH')) {
                   5288:                 foreach my $role (@{$roles}) {
                   5289:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5290:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5291:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5292:                             return 1 unless (($end && $end < $now) ||
                   5293:                                              ($start && $start > $now));
                   5294:                         }
                   5295:                     }
                   5296:                 }
                   5297:             }
                   5298:         }
                   5299:     } else {
                   5300:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   5301:         my $now = time;
1.1170    droeschl 5302: 
1.1172.2.58  raeburn  5303:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 5304:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  5305:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   5306:                 return 1 unless ($tend && $tend < $now)
                   5307:                         or ($tstart && $tstart > $now);
1.1170    droeschl 5308:             }
1.1172.2.23  raeburn  5309:         }
                   5310:     }
1.461     www      5311:     return 0;
1.9       www      5312: }
1.1       albertel 5313: 
1.1172.2.23  raeburn  5314: sub privileged_by_domain {
                   5315:     my ($domains,$roles) = @_;
                   5316:     my %privileged = ();
                   5317:     my $cachetime = 60*60*24;
                   5318:     my $now = time;
                   5319:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   5320:         return %privileged;
                   5321:     }
                   5322:     foreach my $dom (@{$domains}) {
                   5323:         next if (ref($privileged{$dom}) eq 'HASH');
                   5324:         my $needroles;
                   5325:         foreach my $role (@{$roles}) {
                   5326:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   5327:             if (defined($cached)) {
                   5328:                 if (ref($result) eq 'HASH') {
                   5329:                     $privileged{$dom}{$role} = $result;
                   5330:                 }
                   5331:             } else {
                   5332:                 $needroles = 1;
                   5333:             }
                   5334:         }
                   5335:         if ($needroles) {
                   5336:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   5337:             $privileged{$dom} = {};
                   5338:             foreach my $server (keys(%dompersonnel)) {
                   5339:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   5340:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   5341:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   5342:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   5343:                         next if ($end && $end < $now);
                   5344:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   5345:                             $dompersonnel{$server}{$item};
                   5346:                     }
                   5347:                 }
                   5348:             }
                   5349:             if (ref($privileged{$dom}) eq 'HASH') {
                   5350:                 foreach my $role (@{$roles}) {
                   5351:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5352:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   5353:                     } else {
                   5354:                         my %hash = ();
                   5355:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   5356:                     }
                   5357:                 }
                   5358:             }
                   5359:         }
                   5360:     }
                   5361:     return %privileged;
                   5362: }
                   5363: 
1.103     harris41 5364: # -------------------------------------------------------- Get user privileges
1.11      www      5365: 
                   5366: sub rolesinit {
1.1169    droeschl 5367:     my ($domain, $username) = @_;
                   5368:     my %userroles = ('user.login.time' => time);
                   5369:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   5370: 
                   5371:     # firstaccess and timerinterval are related to timed maps/resources. 
                   5372:     # also, blocking can be triggered by an activating timer
                   5373:     # it's saved in the user's %env.
                   5374:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   5375:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   5376:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   5377:         %timerintchk, %timerintenv);
                   5378: 
1.1162    raeburn  5379:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 5380:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  5381:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   5382:     }
1.1169    droeschl 5383: 
1.1162    raeburn  5384:     foreach my $key (keys(%timerinterval)) {
                   5385:         my ($cid,$rest) = split(/\0/,$key);
                   5386:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   5387:     }
1.1169    droeschl 5388: 
1.11      www      5389:     my %allroles=();
1.1162    raeburn  5390:     my %allgroups=();
1.11      www      5391: 
1.1172.2.58  raeburn  5392:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 5393:         my $role = $rolesdump{$area};
                   5394:         $area =~ s/\_\w\w$//;
                   5395: 
                   5396:         my ($trole, $tend, $tstart, $group_privs);
                   5397: 
                   5398:         if ($role =~ /^cr/) {
                   5399:         # Custom role, defined by a user 
                   5400:         # e.g., user.role.cr/msu/smith/mynewrole
                   5401:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5402:                 $trole = $1;
                   5403:                 ($tend, $tstart) = split('_', $2);
                   5404:             } else {
                   5405:                 $trole = $role;
                   5406:             }
                   5407:         } elsif ($role =~ m|^gr/|) {
                   5408:         # Role of member in a group, defined within a course/community
                   5409:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5410:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5411:             next if $tstart eq '-1';
                   5412:             ($trole, $group_privs) = split(/\//, $trole);
                   5413:             $group_privs = &unescape($group_privs);
                   5414:         } else {
                   5415:         # Just a normal role, defined in roles.tab
                   5416:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5417:         }
                   5418: 
                   5419:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5420:                  $username);
                   5421:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5422: 
                   5423:         # role expired or not available yet?
                   5424:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5425:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5426: 
                   5427:         next if $area eq '' or $trole eq '';
                   5428: 
                   5429:         my $spec = "$trole.$area";
                   5430:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5431: 
                   5432:         if ($trole =~ /^cr\//) {
                   5433:         # Custom role, defined by a user
                   5434:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5435:         } elsif ($trole eq 'gr') {
                   5436:         # Role of a member in a group, defined within a course/community
                   5437:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5438:             next;
                   5439:         } else {
                   5440:         # Normal role, defined in roles.tab
                   5441:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5442:         }
                   5443: 
                   5444:         my $cid = $tdomain.'_'.$trest;
                   5445:         unless ($firstaccchk{$cid}) {
                   5446:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5447:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5448:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5449:                         $coursetimerstarts{$cid}{$item}; 
                   5450:                 }
                   5451:             }
                   5452:             $firstaccchk{$cid} = 1;
                   5453:         }
                   5454:         unless ($timerintchk{$cid}) {
                   5455:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5456:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5457:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5458:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5459:                 }
1.12      www      5460:             }
1.1169    droeschl 5461:             $timerintchk{$cid} = 1;
1.191     harris41 5462:         }
1.11      www      5463:     }
1.1169    droeschl 5464: 
                   5465:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
                   5466:         \%allroles, \%allgroups);
                   5467:     $env{'user.adv'} = $userroles{'user.adv'};
                   5468: 
1.1162    raeburn  5469:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5470: }
                   5471: 
1.567     raeburn  5472: sub set_arearole {
1.1172.2.19  raeburn  5473:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   5474:     unless ($nolog) {
1.567     raeburn  5475: # log the associated role with the area
1.1172.2.19  raeburn  5476:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   5477:     }
1.743     albertel 5478:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5479: }
                   5480: 
                   5481: sub custom_roleprivs {
                   5482:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5483:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40  raeburn  5484:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 5485:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5486:         my ($rdummy,$roledef)=
                   5487:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5488:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5489:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5490:             if (defined($syspriv)) {
1.1043    raeburn  5491:                 if ($trest =~ /^$match_community$/) {
                   5492:                     $syspriv =~ s/bre\&S//; 
                   5493:                 }
1.567     raeburn  5494:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5495:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5496:             }
                   5497:             if ($tdomain ne '') {
                   5498:                 if (defined($dompriv)) {
                   5499:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5500:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5501:                 }
                   5502:                 if (($trest ne '') && (defined($coursepriv))) {
                   5503:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5504:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5505:                 }
                   5506:             }
                   5507:         }
                   5508:     }
                   5509: }
                   5510: 
1.678     raeburn  5511: sub group_roleprivs {
                   5512:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   5513:     my $access = 1;
                   5514:     my $now = time;
                   5515:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   5516:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   5517:     if ($access) {
1.811     albertel 5518:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  5519:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   5520:     }
                   5521: }
1.567     raeburn  5522: 
                   5523: sub standard_roleprivs {
                   5524:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   5525:     if (defined($pr{$trole.':s'})) {
                   5526:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   5527:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   5528:     }
                   5529:     if ($tdomain ne '') {
                   5530:         if (defined($pr{$trole.':d'})) {
                   5531:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5532:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5533:         }
                   5534:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   5535:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   5536:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   5537:         }
                   5538:     }
                   5539: }
                   5540: 
                   5541: sub set_userprivs {
1.1064    raeburn  5542:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  5543:     my $author=0;
                   5544:     my $adv=0;
1.678     raeburn  5545:     my %grouproles = ();
                   5546:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  5547:         my @groupkeys; 
1.1000    raeburn  5548:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  5549:             push(@groupkeys,$role);
                   5550:         }
                   5551:         if (ref($groups_roles) eq 'HASH') {
                   5552:             foreach my $key (keys(%{$groups_roles})) {
                   5553:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   5554:                     push(@groupkeys,$key);
                   5555:                 }
                   5556:             }
                   5557:         }
                   5558:         if (@groupkeys > 0) {
                   5559:             foreach my $role (@groupkeys) {
                   5560:                 my ($trole,$area,$sec,$extendedarea);
                   5561:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   5562:                     $trole = $1;
                   5563:                     $area = $2;
                   5564:                     $sec = $3;
                   5565:                     $extendedarea = $area.$sec;
                   5566:                     if (exists($$allgroups{$area})) {
                   5567:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   5568:                             my $spec = $trole.'.'.$extendedarea;
                   5569:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  5570:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  5571:                         }
1.678     raeburn  5572:                     }
                   5573:                 }
                   5574:             }
                   5575:         }
                   5576:     }
1.800     albertel 5577:     foreach my $group (keys(%grouproles)) {
                   5578:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  5579:     }
1.800     albertel 5580:     foreach my $role (keys(%{$allroles})) {
                   5581:         my %thesepriv;
1.941     raeburn  5582:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 5583:         foreach my $item (split(/:/,$$allroles{$role})) {
                   5584:             if ($item ne '') {
                   5585:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  5586:                 if ($restrictions eq '') {
                   5587:                     $thesepriv{$privilege}='F';
                   5588:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   5589:                     $thesepriv{$privilege}.=$restrictions;
                   5590:                 }
                   5591:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   5592:             }
                   5593:         }
                   5594:         my $thesestr='';
1.1104    raeburn  5595:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 5596: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   5597: 	}
                   5598:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  5599:     }
                   5600:     return ($author,$adv);
                   5601: }
                   5602: 
1.994     raeburn  5603: sub role_status {
1.1104    raeburn  5604:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  5605:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40  raeburn  5606:         my ($one,$two) = split(m{\./},$rolekey,2);
                   5607:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  5608:         unless (!defined($$role) || $$role eq '') {
1.1172.2.40  raeburn  5609:             $$where = '/'.$two;
1.994     raeburn  5610:             $$trolecode=$$role.'.'.$$where;
                   5611:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   5612:             $$tstatus='is';
1.1104    raeburn  5613:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  5614:                 $$tstatus='future';
1.1034    raeburn  5615:                 if ($$tstart<$now) {
                   5616:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  5617:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  5618:                             my (%allroles,%allgroups,$group_privs,
                   5619:                                 %groups_roles,@rolecodes);
1.1002    raeburn  5620:                             my %userroles = (
                   5621:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   5622:                             );
1.1064    raeburn  5623:                             @rolecodes = ('cm'); 
1.1002    raeburn  5624:                             my $spec=$$role.'.'.$$where;
                   5625:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   5626:                             if ($$role =~ /^cr\//) {
                   5627:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  5628:                                 push(@rolecodes,'cr');
1.1002    raeburn  5629:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  5630:                                 push(@rolecodes,$$role);
1.1002    raeburn  5631:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   5632:                                                     $env{'user.name'});
1.1064    raeburn  5633:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  5634:                                 (undef,my $group_privs) = split(/\//,$trole);
                   5635:                                 $group_privs = &unescape($group_privs);
                   5636:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  5637:                                 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  5638:                                 &get_groups_roles($tdomain,$trest,
                   5639:                                                   \%course_roles,\@rolecodes,
                   5640:                                                   \%groups_roles);
1.1002    raeburn  5641:                             } else {
1.1064    raeburn  5642:                                 push(@rolecodes,$$role);
1.1002    raeburn  5643:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   5644:                             }
1.1064    raeburn  5645:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   5646:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  5647:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   5648:                         }
                   5649:                     }
1.1034    raeburn  5650:                     $$tstatus = 'is';
1.1002    raeburn  5651:                 }
1.994     raeburn  5652:             }
                   5653:             if ($$tend) {
1.1104    raeburn  5654:                 if ($$tend<$update) {
1.994     raeburn  5655:                     $$tstatus='expired';
                   5656:                 } elsif ($$tend<$now) {
                   5657:                     $$tstatus='will_not';
                   5658:                 }
                   5659:             }
                   5660:         }
                   5661:     }
                   5662: }
                   5663: 
1.1104    raeburn  5664: sub get_groups_roles {
                   5665:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   5666:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   5667:                   (ref($rolecodes) eq 'ARRAY') && 
                   5668:                   (ref($groups_roles) eq 'HASH')); 
                   5669:     if (keys(%{$cdom_courseroles}) > 0) {
                   5670:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   5671:         if ($cdom ne '' && $cnum ne '') {
                   5672:             foreach my $key (keys(%{$cdom_courseroles})) {
                   5673:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   5674:                     my $crsrole = $1;
                   5675:                     my $crssec = $2;
                   5676:                     if ($crsrole =~ /^cr/) {
                   5677:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   5678:                             push(@{$rolecodes},'cr');
                   5679:                         }
                   5680:                     } else {
                   5681:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   5682:                             push(@{$rolecodes},$crsrole);
                   5683:                         }
                   5684:                     }
                   5685:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   5686:                     if ($crssec ne '') {
                   5687:                         $rolekey .= "/$crssec";
                   5688:                     }
                   5689:                     $rolekey .= './';
                   5690:                     $groups_roles->{$rolekey} = $rolecodes;
                   5691:                 }
                   5692:             }
                   5693:         }
                   5694:     }
                   5695:     return;
                   5696: }
                   5697: 
                   5698: sub delete_env_groupprivs {
                   5699:     my ($where,$courseroles,$possroles) = @_;
                   5700:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   5701:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   5702:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   5703:         %{$courseroles->{$udom}} =
                   5704:             &get_my_roles('','','userroles',['active'],
                   5705:                           $possroles,[$udom],1);
                   5706:     }
                   5707:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   5708:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   5709:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   5710:             my $area = '/'.$cdom.'/'.$cnum;
                   5711:             my $privkey = "user.priv.$crsrole.$area";
                   5712:             if ($crssec ne '') {
                   5713:                 $privkey .= '/'.$crssec;
                   5714:             }
                   5715:             $privkey .= ".$area/$group";
                   5716:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   5717:         }
                   5718:     }
                   5719:     return;
                   5720: }
                   5721: 
1.994     raeburn  5722: sub check_adhoc_privs {
1.1172.2.86  raeburn  5723:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  5724:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86  raeburn  5725:     if ($sec) {
                   5726:         $cckey .= '/'.$sec;
                   5727:     }
1.1172.2.9  raeburn  5728:     my $setprivs;
1.994     raeburn  5729:     if ($env{$cckey}) {
                   5730:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  5731:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  5732:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86  raeburn  5733:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  5734:             $setprivs = 1;
1.994     raeburn  5735:         }
                   5736:     } else {
1.1172.2.87  raeburn  5737:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  5738:         $setprivs = 1;
1.994     raeburn  5739:     }
1.1172.2.9  raeburn  5740:     return $setprivs;
1.994     raeburn  5741: }
                   5742: 
                   5743: sub set_adhoc_privileges {
1.1172.2.84  raeburn  5744: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86  raeburn  5745:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  5746:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86  raeburn  5747:     if ($sec ne '') {
                   5748:         $area .= '/'.$sec;
                   5749:     }
1.994     raeburn  5750:     my $spec = $role.'.'.$area;
                   5751:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  5752:                                   $env{'user.name'},1);
1.1172.2.84  raeburn  5753:     my %rolehash = ();
                   5754:     if ($role =~ m{^cr/$dcdom/$dcdom\Q-domainconfig\E/}) {
                   5755:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
                   5756:     } else {
                   5757:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   5758:     }
                   5759:     my ($author,$adv)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  5760:     &appenv(\%userroles,[$role,'cm']);
                   5761:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  5762:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   5763:         &appenv( {'request.role'        => $spec,
                   5764:                   'request.role.domain' => $dcdom,
                   5765:                   'request.course.sec'  => ''
                   5766:                  }
                   5767:                );
                   5768:         my $tadv=0;
                   5769:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   5770:         &appenv({'request.role.adv'    => $tadv});
                   5771:     }
1.994     raeburn  5772: }
                   5773: 
1.12      www      5774: # --------------------------------------------------------------- get interface
                   5775: 
                   5776: sub get {
1.131     albertel 5777:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5778:    my $items='';
1.800     albertel 5779:    foreach my $item (@$storearr) {
                   5780:        $items.=&escape($item).'&';
1.191     harris41 5781:    }
1.12      www      5782:    $items=~s/\&$//;
1.620     albertel 5783:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5784:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 5785:    my $uhome=&homeserver($uname,$udomain);
                   5786: 
1.133     albertel 5787:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5788:    my @pairs=split(/\&/,$rep);
1.273     albertel 5789:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   5790:      return @pairs;
                   5791:    }
1.15      www      5792:    my %returnhash=();
1.42      www      5793:    my $i=0;
1.800     albertel 5794:    foreach my $item (@$storearr) {
                   5795:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5796:       $i++;
1.191     harris41 5797:    }
1.15      www      5798:    return %returnhash;
1.27      www      5799: }
                   5800: 
                   5801: # --------------------------------------------------------------- del interface
                   5802: 
                   5803: sub del {
1.133     albertel 5804:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      5805:    my $items='';
1.800     albertel 5806:    foreach my $item (@$storearr) {
                   5807:        $items.=&escape($item).'&';
1.191     harris41 5808:    }
1.984     neumanie 5809: 
1.27      www      5810:    $items=~s/\&$//;
1.620     albertel 5811:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5812:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5813:    my $uhome=&homeserver($uname,$udomain);
                   5814:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5815: }
                   5816: 
                   5817: # -------------------------------------------------------------- dump interface
                   5818: 
1.1172.2.22  raeburn  5819: sub unserialize {
                   5820:     my ($rep, $escapedkeys) = @_;
                   5821: 
                   5822:     return {} if $rep =~ /^error/;
                   5823: 
                   5824:     my %returnhash=();
                   5825:     foreach my $item (split(/\&/,$rep)) {
                   5826:         my ($key, $value) = split(/=/, $item, 2);
                   5827:         $key = unescape($key) unless $escapedkeys;
                   5828:         next if $key =~ /^error: 2 /;
                   5829:         $returnhash{$key} = &thaw_unescape($value);
                   5830:     }
                   5831:     return \%returnhash;
                   5832: }
                   5833: 
                   5834: # see Lond::dump_with_regexp
                   5835: # if $escapedkeys hash keys won't get unescaped.
1.15      www      5836: sub dump {
1.1172.2.22  raeburn  5837:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 5838:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5839:     if (!$uname) { $uname=$env{'user.name'}; }
                   5840:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 5841: 
1.1172.2.55  raeburn  5842:     if ($regexp) {
                   5843:         $regexp=&escape($regexp);
                   5844:     } else {
                   5845:         $regexp='.';
                   5846:     }
1.1172.2.22  raeburn  5847:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   5848:         # user is hosted on this machine
1.1172.2.55  raeburn  5849:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  5850:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  5851:         return %{&unserialize($reply, $escapedkeys)};
                   5852:     }
1.1166    raeburn  5853:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 5854:     my @pairs=split(/\&/,$rep);
                   5855:     my %returnhash=();
1.1098    foxr     5856:     if (!($rep =~ /^error/ )) {
                   5857: 	foreach my $item (@pairs) {
                   5858: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  5859:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     5860: 	    next if ($key =~ /^error: 2 /);
                   5861: 	    $returnhash{$key}=&thaw_unescape($value);
                   5862: 	}
1.755     albertel 5863:     }
                   5864:     return %returnhash;
1.407     www      5865: }
                   5866: 
1.1098    foxr     5867: 
1.717     albertel 5868: # --------------------------------------------------------- dumpstore interface
                   5869: 
                   5870: sub dumpstore {
                   5871:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  5872:    # same as dump but keys must be escaped. They may contain colon separated
                   5873:    # lists of values that may themself contain colons (e.g. symbs).
                   5874:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 5875: }
                   5876: 
1.407     www      5877: # -------------------------------------------------------------- keys interface
                   5878: 
                   5879: sub getkeys {
                   5880:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 5881:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5882:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      5883:    my $uhome=&homeserver($uname,$udomain);
                   5884:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   5885:    my @keyarray=();
1.800     albertel 5886:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  5887:       next if ($key =~ /^error: 2 /);
1.800     albertel 5888:       push(@keyarray,&unescape($key));
1.407     www      5889:    }
                   5890:    return @keyarray;
1.318     matthew  5891: }
                   5892: 
1.319     matthew  5893: # --------------------------------------------------------------- currentdump
                   5894: sub currentdump {
1.328     matthew  5895:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 5896:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   5897:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   5898:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  5899:    my $uhome = &homeserver($sname,$sdom);
1.1172.2.50  raeburn  5900:    my $rep;
                   5901: 
                   5902:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   5903:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
                   5904:                    $courseid)));
                   5905:    } else {
                   5906:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   5907:    }
                   5908: 
1.318     matthew  5909:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  5910:    #
1.318     matthew  5911:    my %returnhash=();
1.319     matthew  5912:    #
                   5913:    if ($rep eq "unknown_cmd") { 
                   5914:        # an old lond will not know currentdump
                   5915:        # Do a dump and make it look like a currentdump
1.822     albertel 5916:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  5917:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   5918:        my %hash = @tmp;
                   5919:        @tmp=();
1.424     matthew  5920:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  5921:    } else {
                   5922:        my @pairs=split(/\&/,$rep);
1.800     albertel 5923:        foreach my $pair (@pairs) {
                   5924:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  5925:            my ($symb,$param) = split(/:/,$key);
                   5926:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 5927:                                                         &thaw_unescape($value);
1.319     matthew  5928:        }
1.191     harris41 5929:    }
1.12      www      5930:    return %returnhash;
1.424     matthew  5931: }
                   5932: 
                   5933: sub convert_dump_to_currentdump{
                   5934:     my %hash = %{shift()};
                   5935:     my %returnhash;
                   5936:     # Code ripped from lond, essentially.  The only difference
                   5937:     # here is the unescaping done by lonnet::dump().  Conceivably
                   5938:     # we might run in to problems with parameter names =~ /^v\./
                   5939:     while (my ($key,$value) = each(%hash)) {
                   5940:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 5941: 	$symb  = &unescape($symb);
                   5942: 	$param = &unescape($param);
1.424     matthew  5943:         next if ($v eq 'version' || $symb eq 'keys');
                   5944:         next if (exists($returnhash{$symb}) &&
                   5945:                  exists($returnhash{$symb}->{$param}) &&
                   5946:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   5947:         $returnhash{$symb}->{$param}=$value;
                   5948:         $returnhash{$symb}->{'v.'.$param}=$v;
                   5949:     }
                   5950:     #
                   5951:     # Remove all of the keys in the hashes which keep track of
                   5952:     # the version of the parameter.
                   5953:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   5954:         # use a foreach because we are going to delete from the hash.
                   5955:         foreach my $key (keys(%$param_hash)) {
                   5956:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   5957:         }
                   5958:     }
                   5959:     return \%returnhash;
1.12      www      5960: }
                   5961: 
1.627     albertel 5962: # ------------------------------------------------------ critical inc interface
                   5963: 
                   5964: sub cinc {
                   5965:     return &inc(@_,'critical');
                   5966: }
                   5967: 
1.449     matthew  5968: # --------------------------------------------------------------- inc interface
                   5969: 
                   5970: sub inc {
1.627     albertel 5971:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 5972:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5973:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  5974:     my $uhome=&homeserver($uname,$udomain);
                   5975:     my $items='';
                   5976:     if (! ref($store)) {
                   5977:         # got a single value, so use that instead
                   5978:         $items = &escape($store).'=&';
                   5979:     } elsif (ref($store) eq 'SCALAR') {
                   5980:         $items = &escape($$store).'=&';        
                   5981:     } elsif (ref($store) eq 'ARRAY') {
                   5982:         $items = join('=&',map {&escape($_);} @{$store});
                   5983:     } elsif (ref($store) eq 'HASH') {
                   5984:         while (my($key,$value) = each(%{$store})) {
                   5985:             $items.= &escape($key).'='.&escape($value).'&';
                   5986:         }
                   5987:     }
                   5988:     $items=~s/\&$//;
1.627     albertel 5989:     if ($critical) {
                   5990: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5991:     } else {
                   5992: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5993:     }
1.449     matthew  5994: }
                   5995: 
1.12      www      5996: # --------------------------------------------------------------- put interface
                   5997: 
                   5998: sub put {
1.134     albertel 5999:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6000:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6001:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6002:    my $uhome=&homeserver($uname,$udomain);
1.12      www      6003:    my $items='';
1.800     albertel 6004:    foreach my $item (keys(%$storehash)) {
                   6005:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6006:    }
1.12      www      6007:    $items=~s/\&$//;
1.134     albertel 6008:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      6009: }
                   6010: 
1.631     albertel 6011: # ------------------------------------------------------------ newput interface
                   6012: 
                   6013: sub newput {
                   6014:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   6015:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6016:    if (!$uname) { $uname=$env{'user.name'}; }
                   6017:    my $uhome=&homeserver($uname,$udomain);
                   6018:    my $items='';
                   6019:    foreach my $key (keys(%$storehash)) {
                   6020:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   6021:    }
                   6022:    $items=~s/\&$//;
                   6023:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   6024: }
                   6025: 
                   6026: # ---------------------------------------------------------  putstore interface
                   6027: 
1.524     raeburn  6028: sub putstore {
1.1172.2.59  raeburn  6029:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 6030:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6031:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  6032:    my $uhome=&homeserver($uname,$udomain);
                   6033:    my $items='';
1.715     albertel 6034:    foreach my $key (keys(%$storehash)) {
                   6035:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  6036:    }
1.715     albertel 6037:    $items=~s/\&$//;
1.716     albertel 6038:    my $esc_symb=&escape($symb);
                   6039:    my $esc_v=&escape($version);
1.715     albertel 6040:    my $reply =
1.716     albertel 6041:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 6042: 	      $uhome);
1.1172.2.59  raeburn  6043:    if (($tolog) && ($reply eq 'ok')) {
                   6044:        my $namevalue='';
                   6045:        foreach my $key (keys(%{$storehash})) {
                   6046:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   6047:        }
                   6048:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   6049:                      '&host='.&escape($perlvar{'lonHostID'}).
                   6050:                      '&version='.$esc_v.
                   6051:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   6052:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   6053:    }
1.715     albertel 6054:    if ($reply eq 'unknown_cmd') {
1.716     albertel 6055:        # gfall back to way things use to be done
1.715     albertel 6056:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   6057: 			    $uname);
1.524     raeburn  6058:    }
1.715     albertel 6059:    return $reply;
                   6060: }
                   6061: 
                   6062: sub old_putstore {
1.716     albertel 6063:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   6064:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6065:     if (!$uname) { $uname=$env{'user.name'}; }
                   6066:     my $uhome=&homeserver($uname,$udomain);
                   6067:     my %newstorehash;
1.800     albertel 6068:     foreach my $item (keys(%$storehash)) {
                   6069: 	my $key = $version.':'.&escape($symb).':'.$item;
                   6070: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 6071:     }
                   6072:     my $items='';
                   6073:     my %allitems = ();
1.800     albertel 6074:     foreach my $item (keys(%newstorehash)) {
                   6075: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 6076: 	    my $key = $1.':keys:'.$2;
                   6077: 	    $allitems{$key} .= $3.':';
                   6078: 	}
1.800     albertel 6079: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 6080:     }
1.800     albertel 6081:     foreach my $item (keys(%allitems)) {
                   6082: 	$allitems{$item} =~ s/\:$//;
                   6083: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 6084:     }
                   6085:     $items=~s/\&$//;
                   6086:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  6087: }
                   6088: 
1.47      www      6089: # ------------------------------------------------------ critical put interface
                   6090: 
                   6091: sub cput {
1.134     albertel 6092:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6093:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6094:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6095:    my $uhome=&homeserver($uname,$udomain);
1.47      www      6096:    my $items='';
1.800     albertel 6097:    foreach my $item (keys(%$storehash)) {
                   6098:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6099:    }
1.47      www      6100:    $items=~s/\&$//;
1.134     albertel 6101:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6102: }
                   6103: 
                   6104: # -------------------------------------------------------------- eget interface
                   6105: 
                   6106: sub eget {
1.133     albertel 6107:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6108:    my $items='';
1.800     albertel 6109:    foreach my $item (@$storearr) {
                   6110:        $items.=&escape($item).'&';
1.191     harris41 6111:    }
1.12      www      6112:    $items=~s/\&$//;
1.620     albertel 6113:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6114:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6115:    my $uhome=&homeserver($uname,$udomain);
                   6116:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6117:    my @pairs=split(/\&/,$rep);
                   6118:    my %returnhash=();
1.42      www      6119:    my $i=0;
1.800     albertel 6120:    foreach my $item (@$storearr) {
                   6121:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6122:       $i++;
1.191     harris41 6123:    }
1.12      www      6124:    return %returnhash;
                   6125: }
                   6126: 
1.667     albertel 6127: # ------------------------------------------------------------ tmpput interface
                   6128: sub tmpput {
1.802     raeburn  6129:     my ($storehash,$server,$context)=@_;
1.667     albertel 6130:     my $items='';
1.800     albertel 6131:     foreach my $item (keys(%$storehash)) {
                   6132: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 6133:     }
                   6134:     $items=~s/\&$//;
1.802     raeburn  6135:     if (defined($context)) {
                   6136:         $items .= ':'.&escape($context);
                   6137:     }
1.667     albertel 6138:     return &reply("tmpput:$items",$server);
                   6139: }
                   6140: 
                   6141: # ------------------------------------------------------------ tmpget interface
                   6142: sub tmpget {
1.688     albertel 6143:     my ($token,$server)=@_;
                   6144:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6145:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 6146:     my %returnhash;
1.1172.2.85  raeburn  6147:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   6148:         return %returnhash;
                   6149:     }
1.667     albertel 6150:     foreach my $item (split(/\&/,$rep)) {
                   6151: 	my ($key,$value)=split(/=/,$item);
                   6152: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   6153:     }
                   6154:     return %returnhash;
                   6155: }
                   6156: 
1.1113    raeburn  6157: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 6158: sub tmpdel {
                   6159:     my ($token,$server)=@_;
                   6160:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6161:     return &reply("tmpdel:$token",$server);
                   6162: }
                   6163: 
1.1172.2.13  raeburn  6164: # ------------------------------------------------------------ get_timebased_id
                   6165: 
                   6166: sub get_timebased_id {
                   6167:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   6168:         $maxtries) = @_;
                   6169:     my ($newid,$error,$dellock);
                   6170:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   6171:         return ('','ok','invalid call to get suffix');
                   6172:     }
                   6173: 
                   6174: # set defaults for any optional args for which values were not supplied
                   6175:     if ($who eq '') {
                   6176:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   6177:     }
                   6178:     if (!$locktries) {
                   6179:         $locktries = 3;
                   6180:     }
                   6181:     if (!$maxtries) {
                   6182:         $maxtries = 10;
                   6183:     }
                   6184: 
                   6185:     if (($cdom eq '') || ($cnum eq '')) {
                   6186:         if ($env{'request.course.id'}) {
                   6187:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6188:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6189:         }
                   6190:         if (($cdom eq '') || ($cnum eq '')) {
                   6191:             return ('','ok','call to get suffix not in course context');
                   6192:         }
                   6193:     }
                   6194: 
                   6195: # construct locking item
                   6196:     my $lockhash = {
                   6197:                       $prefix."\0".'locked_'.$keyid => $who,
                   6198:                    };
                   6199:     my $tries = 0;
                   6200: 
                   6201: # attempt to get lock on nohist_$namespace file
                   6202:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6203:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   6204:         $tries ++;
                   6205:         sleep 1;
                   6206:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6207:     }
                   6208: 
                   6209: # attempt to get unique identifier, based on current timestamp
                   6210:     if ($gotlock eq 'ok') {
                   6211:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   6212:         my $id = time;
                   6213:         $newid = $id;
1.1172.2.56  raeburn  6214:         if ($idtype eq 'addcode') {
                   6215:             $newid .= &sixnum_code();
                   6216:         }
1.1172.2.13  raeburn  6217:         my $idtries = 0;
                   6218:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   6219:             if ($idtype eq 'concat') {
                   6220:                 $newid = $id.$idtries;
1.1172.2.56  raeburn  6221:             } elsif ($idtype eq 'addcode') {
                   6222:                 $newid = $newid.&sixnum_code();
1.1172.2.13  raeburn  6223:             } else {
                   6224:                 $newid ++;
                   6225:             }
                   6226:             $idtries ++;
                   6227:         }
                   6228:         if (!exists($inuse{$prefix."\0".$newid})) {
                   6229:             my %new_item =  (
                   6230:                               $prefix."\0".$newid => $who,
                   6231:                             );
                   6232:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   6233:                                                  $cdom,$cnum);
                   6234:             if ($putresult ne 'ok') {
                   6235:                 undef($newid);
                   6236:                 $error = 'error saving new item: '.$putresult;
                   6237:             }
                   6238:         } else {
1.1172.2.56  raeburn  6239:              undef($newid);
1.1172.2.13  raeburn  6240:              $error = ('error: no unique suffix available for the new item ');
                   6241:         }
                   6242: #  remove lock
                   6243:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   6244:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   6245:     } else {
                   6246:         $error = "error: could not obtain lockfile\n";
                   6247:         $dellock = 'ok';
1.1172.2.58  raeburn  6248:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   6249:             $dellock = 'nolock';
                   6250:         }
1.1172.2.13  raeburn  6251:     }
                   6252:     return ($newid,$dellock,$error);
                   6253: }
                   6254: 
1.1172.2.56  raeburn  6255: sub sixnum_code {
                   6256:     my $code;
                   6257:     for (0..6) {
                   6258:         $code .= int( rand(9) );
                   6259:     }
                   6260:     return $code;
                   6261: }
                   6262: 
1.765     albertel 6263: # -------------------------------------------------- portfolio access checking
                   6264: 
                   6265: sub portfolio_access {
1.1172.2.77  raeburn  6266:     my ($requrl,$clientip) = @_;
1.765     albertel 6267:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77  raeburn  6268:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  6269:     if ($result) {
                   6270:         my %setters;
                   6271:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6272:             my ($startblock,$endblock) =
                   6273:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   6274:             if ($startblock && $endblock) {
                   6275:                 return 'B';
                   6276:             }
                   6277:         } else {
                   6278:             my ($startblock,$endblock) =
                   6279:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   6280:             if ($startblock && $endblock) {
                   6281:                 return 'B';
                   6282:             }
                   6283:         }
                   6284:     }
1.765     albertel 6285:     if ($result eq 'ok') {
1.766     albertel 6286:        return 'F';
1.765     albertel 6287:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 6288:        return 'A';
1.765     albertel 6289:     }
1.766     albertel 6290:     return '';
1.765     albertel 6291: }
                   6292: 
                   6293: sub get_portfolio_access {
1.1172.2.77  raeburn  6294:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 6295: 
                   6296:     if (!ref($access_hash)) {
                   6297: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   6298: 	my %access_controls = &get_access_controls($current_perms,$group,
                   6299: 						   $file_name);
                   6300: 	$access_hash = $access_controls{$file_name};
                   6301:     }
                   6302: 
1.1172.2.77  raeburn  6303:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 6304:     my $now = time;
                   6305:     if (ref($access_hash) eq 'HASH') {
                   6306:         foreach my $key (keys(%{$access_hash})) {
                   6307:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6308:             if ($start > $now) {
                   6309:                 next;
                   6310:             }
                   6311:             if ($end && $end<$now) {
                   6312:                 next;
                   6313:             }
                   6314:             if ($scope eq 'public') {
                   6315:                 $public = $key;
                   6316:                 last;
                   6317:             } elsif ($scope eq 'guest') {
                   6318:                 $guest = $key;
                   6319:             } elsif ($scope eq 'domains') {
                   6320:                 push(@domains,$key);
                   6321:             } elsif ($scope eq 'users') {
                   6322:                 push(@users,$key);
                   6323:             } elsif ($scope eq 'course') {
                   6324:                 push(@courses,$key);
                   6325:             } elsif ($scope eq 'group') {
                   6326:                 push(@groups,$key);
1.1172.2.77  raeburn  6327:             } elsif ($scope eq 'ip') {
                   6328:                 push(@ips,$key);
1.765     albertel 6329:             }
                   6330:         }
                   6331:         if ($public) {
                   6332:             return 'ok';
1.1172.2.77  raeburn  6333:         } elsif (@ips > 0) {
                   6334:             my $allowed;
                   6335:             foreach my $ipkey (@ips) {
                   6336:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   6337:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   6338:                         $allowed = 1;
                   6339:                         last;
                   6340:                     }
                   6341:                 }
                   6342:             }
                   6343:             if ($allowed) {
                   6344:                 return 'ok';
                   6345:             }
1.765     albertel 6346:         }
                   6347:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6348:             if ($guest) {
                   6349:                 return $guest;
                   6350:             }
                   6351:         } else {
                   6352:             if (@domains > 0) {
                   6353:                 foreach my $domkey (@domains) {
                   6354:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   6355:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   6356:                             return 'ok';
                   6357:                         }
                   6358:                     }
                   6359:                 }
                   6360:             }
                   6361:             if (@users > 0) {
                   6362:                 foreach my $userkey (@users) {
1.865     raeburn  6363:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   6364:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   6365:                             if (ref($item) eq 'HASH') {
                   6366:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   6367:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   6368:                                     return 'ok';
                   6369:                                 }
                   6370:                             }
                   6371:                         }
                   6372:                     } 
1.765     albertel 6373:                 }
                   6374:             }
                   6375:             my %roleshash;
                   6376:             my @courses_and_groups = @courses;
                   6377:             push(@courses_and_groups,@groups); 
                   6378:             if (@courses_and_groups > 0) {
                   6379:                 my (%allgroups,%allroles); 
                   6380:                 my ($start,$end,$role,$sec,$group);
                   6381:                 foreach my $envkey (%env) {
1.1060    raeburn  6382:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6383:                         my $cid = $2.'_'.$3; 
                   6384:                         if ($1 eq 'gr') {
                   6385:                             $group = $4;
                   6386:                             $allgroups{$cid}{$group} = $env{$envkey};
                   6387:                         } else {
                   6388:                             if ($4 eq '') {
                   6389:                                 $sec = 'none';
                   6390:                             } else {
                   6391:                                 $sec = $4;
                   6392:                             }
                   6393:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6394:                         }
1.811     albertel 6395:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6396:                         my $cid = $2.'_'.$3;
                   6397:                         if ($4 eq '') {
                   6398:                             $sec = 'none';
                   6399:                         } else {
                   6400:                             $sec = $4;
                   6401:                         }
                   6402:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6403:                     }
                   6404:                 }
                   6405:                 if (keys(%allroles) == 0) {
                   6406:                     return;
                   6407:                 }
                   6408:                 foreach my $key (@courses_and_groups) {
                   6409:                     my %content = %{$$access_hash{$key}};
                   6410:                     my $cnum = $content{'number'};
                   6411:                     my $cdom = $content{'domain'};
                   6412:                     my $cid = $cdom.'_'.$cnum;
                   6413:                     if (!exists($allroles{$cid})) {
                   6414:                         next;
                   6415:                     }    
                   6416:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   6417:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   6418:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   6419:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   6420:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   6421:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   6422:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   6423:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   6424:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   6425:                                         if (grep/^all$/,@sections) {
                   6426:                                             return 'ok';
                   6427:                                         } else {
                   6428:                                             if (grep/^$sec$/,@sections) {
                   6429:                                                 return 'ok';
                   6430:                                             }
                   6431:                                         }
                   6432:                                     }
                   6433:                                 }
                   6434:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   6435:                                     if (grep/^none$/,@groups) {
                   6436:                                         return 'ok';
                   6437:                                     }
                   6438:                                 } else {
                   6439:                                     if (grep/^all$/,@groups) {
                   6440:                                         return 'ok';
                   6441:                                     } 
                   6442:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   6443:                                         if (grep/^$group$/,@groups) {
                   6444:                                             return 'ok';
                   6445:                                         }
                   6446:                                     }
                   6447:                                 } 
                   6448:                             }
                   6449:                         }
                   6450:                     }
                   6451:                 }
                   6452:             }
                   6453:             if ($guest) {
                   6454:                 return $guest;
                   6455:             }
                   6456:         }
                   6457:     }
                   6458:     return;
                   6459: }
                   6460: 
                   6461: sub course_group_datechecker {
                   6462:     my ($dates,$now,$status) = @_;
                   6463:     my ($start,$end) = split(/\./,$dates);
                   6464:     if (!$start && !$end) {
                   6465:         return 'ok';
                   6466:     }
                   6467:     if (grep/^active$/,@{$status}) {
                   6468:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   6469:             return 'ok';
                   6470:         }
                   6471:     }
                   6472:     if (grep/^previous$/,@{$status}) {
                   6473:         if ($end > $now ) {
                   6474:             return 'ok';
                   6475:         }
                   6476:     }
                   6477:     if (grep/^future$/,@{$status}) {
                   6478:         if ($start > $now) {
                   6479:             return 'ok';
                   6480:         }
                   6481:     }
                   6482:     return; 
                   6483: }
                   6484: 
                   6485: sub parse_portfolio_url {
                   6486:     my ($url) = @_;
                   6487: 
                   6488:     my ($type,$udom,$unum,$group,$file_name);
                   6489:     
1.823     albertel 6490:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 6491: 	$type = 1;
                   6492:         $udom = $1;
                   6493:         $unum = $2;
                   6494:         $file_name = $3;
1.823     albertel 6495:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 6496: 	$type = 2;
                   6497:         $udom = $1;
                   6498:         $unum = $2;
                   6499:         $group = $3;
                   6500:         $file_name = $3.'/'.$4;
                   6501:     }
                   6502:     if (wantarray) {
                   6503: 	return ($type,$udom,$unum,$file_name,$group);
                   6504:     }
                   6505:     return $type;
                   6506: }
                   6507: 
                   6508: sub is_portfolio_url {
                   6509:     my ($url) = @_;
                   6510:     return scalar(&parse_portfolio_url($url));
                   6511: }
                   6512: 
1.798     raeburn  6513: sub is_portfolio_file {
                   6514:     my ($file) = @_;
1.820     raeburn  6515:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  6516:         return 1;
                   6517:     }
                   6518:     return;
                   6519: }
                   6520: 
1.976     raeburn  6521: sub usertools_access {
1.1084    raeburn  6522:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  6523:     my ($access,%tools);
                   6524:     if ($context eq '') {
                   6525:         $context = 'tools';
                   6526:     }
                   6527:     if ($context eq 'requestcourses') {
                   6528:         %tools = (
                   6529:                       official   => 1,
                   6530:                       unofficial => 1,
1.1006    raeburn  6531:                       community  => 1,
1.1172.2.37  raeburn  6532:                       textbook   => 1,
1.985     raeburn  6533:                  );
1.1172.2.9  raeburn  6534:     } elsif ($context eq 'requestauthor') {
                   6535:         %tools = (
                   6536:                       requestauthor => 1,
                   6537:                  );
1.985     raeburn  6538:     } else {
                   6539:         %tools = (
                   6540:                       aboutme   => 1,
                   6541:                       blog      => 1,
1.1172.2.6  raeburn  6542:                       webdav    => 1,
1.985     raeburn  6543:                       portfolio => 1,
                   6544:                  );
                   6545:     }
1.976     raeburn  6546:     return if (!defined($tools{$tool}));
                   6547: 
1.1172.2.35  raeburn  6548:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  6549:         $udom = $env{'user.domain'};
                   6550:         $uname = $env{'user.name'};
                   6551:     }
                   6552: 
1.978     raeburn  6553:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6554:         if ($action ne 'reload') {
1.985     raeburn  6555:             if ($context eq 'requestcourses') {
                   6556:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  6557:             } elsif ($context eq 'requestauthor') {
                   6558:                 return $env{'environment.canrequest.author'};
1.985     raeburn  6559:             } else {
                   6560:                 return $env{'environment.availabletools.'.$tool};
                   6561:             }
                   6562:         }
1.976     raeburn  6563:     }
                   6564: 
1.1172.2.9  raeburn  6565:     my ($toolstatus,$inststatus,$envkey);
                   6566:     if ($context eq 'requestauthor') {
                   6567:         $envkey = $context;
                   6568:     } else {
                   6569:         $envkey = $context.'.'.$tool;
                   6570:     }
1.976     raeburn  6571: 
1.985     raeburn  6572:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   6573:          ($action ne 'reload')) {
1.1172.2.9  raeburn  6574:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  6575:         $inststatus = $env{'environment.inststatus'};
                   6576:     } else {
1.1084    raeburn  6577:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  6578:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  6579:             $inststatus = $userenvref->{'inststatus'};
                   6580:         } else {
1.1172.2.9  raeburn  6581:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   6582:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  6583:             $inststatus = $userenv{'inststatus'};
                   6584:         }
1.976     raeburn  6585:     }
                   6586: 
                   6587:     if ($toolstatus ne '') {
                   6588:         if ($toolstatus) {
                   6589:             $access = 1;
                   6590:         } else {
                   6591:             $access = 0;
                   6592:         }
                   6593:         return $access;
                   6594:     }
                   6595: 
1.1084    raeburn  6596:     my ($is_adv,%domdef);
                   6597:     if (ref($is_advref) eq 'HASH') {
                   6598:         $is_adv = $is_advref->{'is_adv'};
                   6599:     } else {
                   6600:         $is_adv = &is_advanced_user($udom,$uname);
                   6601:     }
                   6602:     if (ref($domdefref) eq 'HASH') {
                   6603:         %domdef = %{$domdefref};
                   6604:     } else {
                   6605:         %domdef = &get_domain_defaults($udom);
                   6606:     }
1.976     raeburn  6607:     if (ref($domdef{$tool}) eq 'HASH') {
                   6608:         if ($is_adv) {
                   6609:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   6610:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   6611:                     $access = 1;
                   6612:                 } else {
                   6613:                     $access = 0;
                   6614:                 }
                   6615:                 return $access;
                   6616:             }
                   6617:         }
                   6618:         if ($inststatus ne '') {
                   6619:             my ($hasaccess,$hasnoaccess);
                   6620:             foreach my $affiliation (split(/:/,$inststatus)) {
                   6621:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   6622:                     if ($domdef{$tool}{$affiliation}) {
                   6623:                         $hasaccess = 1;
                   6624:                     } else {
                   6625:                         $hasnoaccess = 1;
                   6626:                     }
                   6627:                 }
                   6628:             }
                   6629:             if ($hasaccess || $hasnoaccess) {
                   6630:                 if ($hasaccess) {
                   6631:                     $access = 1;
                   6632:                 } elsif ($hasnoaccess) {
                   6633:                     $access = 0; 
                   6634:                 }
                   6635:                 return $access;
                   6636:             }
                   6637:         } else {
                   6638:             if ($domdef{$tool}{'default'} ne '') {
                   6639:                 if ($domdef{$tool}{'default'}) {
                   6640:                     $access = 1;
                   6641:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   6642:                     $access = 0;
                   6643:                 }
                   6644:                 return $access;
                   6645:             }
                   6646:         }
                   6647:     } else {
1.1172.2.6  raeburn  6648:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  6649:             $access = 1;
                   6650:         } else {
                   6651:             $access = 0;
                   6652:         }
1.976     raeburn  6653:         return $access;
                   6654:     }
                   6655: }
                   6656: 
1.1050    raeburn  6657: sub is_course_owner {
                   6658:     my ($cdom,$cnum,$udom,$uname) = @_;
                   6659:     if (($udom eq '') || ($uname eq '')) {
                   6660:         $udom = $env{'user.domain'};
                   6661:         $uname = $env{'user.name'};
                   6662:     }
                   6663:     unless (($udom eq '') || ($uname eq '')) {
                   6664:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   6665:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   6666:                 return 1;
                   6667:             } else {
                   6668:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   6669:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   6670:                     return 1;
                   6671:                 }
                   6672:             }
                   6673:         }
                   6674:     }
                   6675:     return;
                   6676: }
                   6677: 
1.976     raeburn  6678: sub is_advanced_user {
                   6679:     my ($udom,$uname) = @_;
1.1085    raeburn  6680:     if ($udom ne '' && $uname ne '') {
                   6681:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  6682:             if (wantarray) {
                   6683:                 return ($env{'user.adv'},$env{'user.author'});
                   6684:             } else {
                   6685:                 return $env{'user.adv'};
                   6686:             }
1.1085    raeburn  6687:         }
                   6688:     }
1.976     raeburn  6689:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   6690:     my %allroles;
1.1128    raeburn  6691:     my ($is_adv,$is_author);
1.976     raeburn  6692:     foreach my $role (keys(%roleshash)) {
                   6693:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   6694:         my $area = '/'.$tdomain.'/'.$trest;
                   6695:         if ($sec ne '') {
                   6696:             $area .= '/'.$sec;
                   6697:         }
                   6698:         if (($area ne '') && ($trole ne '')) {
                   6699:             my $spec=$trole.'.'.$area;
                   6700:             if ($trole =~ /^cr\//) {
                   6701:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6702:             } elsif ($trole ne 'gr') {
                   6703:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6704:             }
1.1128    raeburn  6705:             if ($trole eq 'au') {
                   6706:                 $is_author = 1;
                   6707:             }
1.976     raeburn  6708:         }
                   6709:     }
                   6710:     foreach my $role (keys(%allroles)) {
                   6711:         last if ($is_adv);
                   6712:         foreach my $item (split(/:/,$allroles{$role})) {
                   6713:             if ($item ne '') {
                   6714:                 my ($privilege,$restrictions)=split(/&/,$item);
                   6715:                 if ($privilege eq 'adv') {
                   6716:                     $is_adv = 1;
                   6717:                     last;
                   6718:                 }
                   6719:             }
                   6720:         }
                   6721:     }
1.1128    raeburn  6722:     if (wantarray) {
                   6723:         return ($is_adv,$is_author);
                   6724:     }
1.976     raeburn  6725:     return $is_adv;
                   6726: }
1.798     raeburn  6727: 
1.1035    raeburn  6728: sub check_can_request {
1.1036    raeburn  6729:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  6730:     my $canreq = 0;
                   6731:     my ($types,$typename) = &Apache::loncommon::course_types();
                   6732:     my @options = ('approval','validate','autolimit');
                   6733:     my $optregex = join('|',@options);
                   6734:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   6735:         foreach my $type (@{$types}) {
                   6736:             if (&usertools_access($env{'user.name'},
                   6737:                                   $env{'user.domain'},
                   6738:                                   $type,undef,'requestcourses')) {
                   6739:                 $canreq ++;
1.1036    raeburn  6740:                 if (ref($request_domains) eq 'HASH') {
                   6741:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   6742:                 }
1.1035    raeburn  6743:                 if ($dom eq $env{'user.domain'}) {
                   6744:                     $can_request->{$type} = 1;
                   6745:                 }
                   6746:             }
                   6747:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   6748:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   6749:                 if (@curr > 0) {
1.1036    raeburn  6750:                     foreach my $item (@curr) {
                   6751:                         if (ref($request_domains) eq 'HASH') {
                   6752:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   6753:                             if ($otherdom ne '') {
                   6754:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   6755:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   6756:                                         push(@{$request_domains->{$type}},$otherdom);
                   6757:                                     }
                   6758:                                 } else {
                   6759:                                     push(@{$request_domains->{$type}},$otherdom);
                   6760:                                 }
                   6761:                             }
                   6762:                         }
                   6763:                     }
                   6764:                     unless($dom eq $env{'user.domain'}) {
                   6765:                         $canreq ++;
1.1035    raeburn  6766:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   6767:                             $can_request->{$type} = 1;
                   6768:                         }
                   6769:                     }
                   6770:                 }
                   6771:             }
                   6772:         }
                   6773:     }
                   6774:     return $canreq;
                   6775: }
                   6776: 
1.341     www      6777: # ---------------------------------------------- Custom access rule evaluation
                   6778: 
                   6779: sub customaccess {
                   6780:     my ($priv,$uri)=@_;
1.807     albertel 6781:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      6782:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 6783:     $udom = &LONCAPA::clean_domain($udom);
                   6784:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      6785:     my $access=0;
1.800     albertel 6786:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 6787: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   6788: 	if ($type eq 'user') {
                   6789: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 6790: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 6791: 		if ($tdom) {
                   6792: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   6793: 		}
1.896     albertel 6794: 		if ($tuname) {
                   6795: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 6796: 		}
                   6797: 		$access=($effect eq 'allow');
                   6798: 		last;
                   6799: 	    }
                   6800: 	} else {
                   6801: 	    if ($role) {
                   6802: 		if ($role ne $urole) { next; }
                   6803: 	    }
                   6804: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   6805: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   6806: 		if ($tdom) {
                   6807: 		    if ($tdom ne $udom) { next; }
                   6808: 		}
                   6809: 		if ($tcrs) {
                   6810: 		    if ($tcrs ne $ucrs) { next; }
                   6811: 		}
                   6812: 		if ($tsec) {
                   6813: 		    if ($tsec ne $usec) { next; }
                   6814: 		}
                   6815: 		$access=($effect eq 'allow');
                   6816: 		last;
                   6817: 	    }
                   6818: 	    if ($realm eq '' && $role eq '') {
                   6819: 		$access=($effect eq 'allow');
                   6820: 	    }
1.402     bowersj2 6821: 	}
1.341     www      6822:     }
                   6823:     return $access;
                   6824: }
                   6825: 
1.103     harris41 6826: # ------------------------------------------------- Check for a user privilege
1.12      www      6827: 
                   6828: sub allowed {
1.1172.2.65  raeburn  6829:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 6830:     my $ver_orguri=$uri;
1.439     www      6831:     $uri=&deversion($uri);
1.152     www      6832:     my $orguri=$uri;
1.52      www      6833:     $uri=&declutter($uri);
1.809     raeburn  6834: 
1.810     raeburn  6835:     if ($priv eq 'evb') {
                   6836: # Evade communication block restrictions for specified role in a course
                   6837:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   6838:             return $1;
                   6839:         } else {
                   6840:             return;
                   6841:         }
                   6842:     }
                   6843: 
1.620     albertel 6844:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      6845: # Free bre access to adm and meta resources
1.775     albertel 6846:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 6847: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   6848: 	&& ($priv eq 'bre')) {
1.14      www      6849: 	return 'F';
1.159     www      6850:     }
                   6851: 
1.545     banghart 6852: # Free bre access to user's own portfolio contents
1.714     raeburn  6853:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  6854:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  6855: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  6856:         my %setters;
                   6857:         my ($startblock,$endblock) = 
                   6858:             &Apache::loncommon::blockcheck(\%setters,'port');
                   6859:         if ($startblock && $endblock) {
                   6860:             return 'B';
                   6861:         } else {
                   6862:             return 'F';
                   6863:         }
1.545     banghart 6864:     }
                   6865: 
1.762     raeburn  6866: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  6867:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   6868:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   6869:         if (exists($env{'request.course.id'})) {
                   6870:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6871:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6872:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   6873:                 my $courseprivid=$env{'request.course.id'};
                   6874:                 $courseprivid=~s/\_/\//;
                   6875:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   6876:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   6877:                     return $1; 
1.762     raeburn  6878:                 } else {
                   6879:                     if ($env{'request.course.sec'}) {
                   6880:                         $courseprivid.='/'.$env{'request.course.sec'};
                   6881:                     }
                   6882:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   6883:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   6884:                         return $2;
                   6885:                     }
1.714     raeburn  6886:                 }
                   6887:             }
                   6888:         }
                   6889:     }
                   6890: 
1.159     www      6891: # Free bre to public access
                   6892: 
                   6893:     if ($priv eq 'bre') {
1.238     www      6894:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 6895: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      6896:            return 'F'; 
                   6897:         }
1.238     www      6898:         if ($copyright eq 'priv') {
                   6899:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6900: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      6901: 		return '';
                   6902:             }
                   6903:         }
                   6904:         if ($copyright eq 'domain') {
                   6905:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6906: 	    unless (($env{'user.domain'} eq $1) ||
                   6907:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      6908: 		return '';
                   6909:             }
1.262     matthew  6910:         }
1.620     albertel 6911:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  6912:             # Library role, so allow browsing of resources in this domain.
                   6913:             return 'F';
1.238     www      6914:         }
1.341     www      6915:         if ($copyright eq 'custom') {
                   6916: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   6917:         }
1.14      www      6918:     }
1.264     matthew  6919:     # Domain coordinator is trying to create a course
1.620     albertel 6920:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  6921:         # uri is the requested domain in this case.
                   6922:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  6923:         # a role of dc for the domain in question.
1.620     albertel 6924:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  6925:     }
1.29      www      6926: 
1.52      www      6927:     my $thisallowed='';
                   6928:     my $statecond=0;
                   6929:     my $courseprivid='';
                   6930: 
1.1039    raeburn  6931:     my $ownaccess;
1.1043    raeburn  6932:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  6933:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   6934:         if ($uri eq '') {
                   6935:             $ownaccess = 1;
                   6936:         } else {
                   6937:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   6938:                 my $udom = $env{'user.domain'};
                   6939:                 my $uname = $env{'user.name'};
                   6940:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   6941:                     $ownaccess = 1;
1.1040    raeburn  6942:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  6943:                     unless ($uri =~ m{\.\./}) {
                   6944:                         $ownaccess = 1;
                   6945:                     }
                   6946:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   6947:                     my $now = time;
                   6948:                     if ($uri =~ m{^([^/]+)/?$}) {
                   6949:                         my $adom = $1;
                   6950:                         foreach my $key (keys(%env)) {
1.1042    raeburn  6951:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  6952:                                 my ($start,$end) = split('.',$env{$key});
                   6953:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6954:                                     $ownaccess = 1;
                   6955:                                     last;
                   6956:                                 }
                   6957:                             }
                   6958:                         }
                   6959:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   6960:                         my $adom = $1;
                   6961:                         my $aname = $2;
1.1042    raeburn  6962:                         foreach my $role ('ca','aa') { 
                   6963:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   6964:                                 my ($start,$end) =
                   6965:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   6966:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6967:                                     $ownaccess = 1;
                   6968:                                     last;
                   6969:                                 }
1.1039    raeburn  6970:                             }
                   6971:                         }
                   6972:                     }
                   6973:                 }
                   6974:             }
                   6975:         }
                   6976:     }
                   6977: 
1.52      www      6978: # Course
                   6979: 
1.620     albertel 6980:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6981:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6982:             $thisallowed.=$1;
                   6983:         }
1.52      www      6984:     }
1.29      www      6985: 
1.52      www      6986: # Domain
                   6987: 
1.620     albertel 6988:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 6989:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6990:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6991:             $thisallowed.=$1;
                   6992:         }
1.12      www      6993:     }
1.52      www      6994: 
1.1141    raeburn  6995: # User who is not author or co-author might still be able to edit
                   6996: # resource of an author in the domain (e.g., if Domain Coordinator).
                   6997:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   6998:         (&allowed('mdc',$env{'request.course.id'}))) {
                   6999:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   7000:             $thisallowed.=$1;
                   7001:         }
                   7002:     }
                   7003: 
1.52      www      7004: # Course: uri itself is a course
1.66      www      7005:     my $courseuri=$uri;
                   7006:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      7007:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      7008: 
1.620     albertel 7009:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 7010:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7011:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7012:             $thisallowed.=$1;
                   7013:         }
1.12      www      7014:     }
1.29      www      7015: 
1.665     albertel 7016: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 7017: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 7018:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 7019: 	$thisallowed='';
1.671     raeburn  7020:         my ($match)=&is_on_map($uri);
                   7021:         if ($match) {
                   7022:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   7023:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65  raeburn  7024:                 my $value = $1;
                   7025:                 if ($noblockcheck) {
                   7026:                     $thisallowed.=$value;
1.1162    raeburn  7027:                 } else {
1.1172.2.65  raeburn  7028:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7029:                     if (@blockers > 0) {
                   7030:                         $thisallowed = 'B';
                   7031:                     } else {
                   7032:                         $thisallowed.=$value;
                   7033:                     }
1.1162    raeburn  7034:                 }
1.671     raeburn  7035:             }
                   7036:         } else {
1.705     albertel 7037:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  7038:             if ($refuri) {
                   7039:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  7040:                     $thisallowed='F';
1.671     raeburn  7041:                 } else {
                   7042:                     $refuri=&declutter($refuri);
                   7043:                     my ($match) = &is_on_map($refuri);
                   7044:                     if ($match) {
1.1172.2.65  raeburn  7045:                         if ($noblockcheck) {
1.1162    raeburn  7046:                             $thisallowed='F';
1.1172.2.65  raeburn  7047:                         } else {
                   7048:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7049:                             if (@blockers > 0) {
                   7050:                                 $thisallowed = 'B';
                   7051:                             } else {
                   7052:                                 $thisallowed='F';
                   7053:                             }
1.1162    raeburn  7054:                         }
1.671     raeburn  7055:                     }
1.669     raeburn  7056:                 }
1.671     raeburn  7057:             }
                   7058:         }
1.314     www      7059:     }
1.492     albertel 7060: 
1.766     albertel 7061:     if ($priv eq 'bre'
                   7062: 	&& $thisallowed ne 'F' 
                   7063: 	&& $thisallowed ne '2'
                   7064: 	&& &is_portfolio_url($uri)) {
1.1172.2.77  raeburn  7065: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 7066:     }
                   7067:     
1.52      www      7068: # Full access at system, domain or course-wide level? Exit.
1.29      www      7069:     if ($thisallowed=~/F/) {
                   7070: 	return 'F';
                   7071:     }
                   7072: 
1.52      www      7073: # If this is generating or modifying users, exit with special codes
1.29      www      7074: 
1.643     www      7075:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   7076: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 7077: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      7078: # no author name given, so this just checks on the general right to make a co-author in this domain
                   7079: 	    unless ($auname) { return $thisallowed; }
                   7080: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 7081: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   7082: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   7083: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   7084: 	}
1.52      www      7085: 	return $thisallowed;
                   7086:     }
                   7087: #
1.103     harris41 7088: # Gathered so far: system, domain and course wide privileges
1.52      www      7089: #
                   7090: # Course: See if uri or referer is an individual resource that is part of 
                   7091: # the course
                   7092: 
1.620     albertel 7093:     if ($env{'request.course.id'}) {
1.232     www      7094: 
1.620     albertel 7095:        $courseprivid=$env{'request.course.id'};
                   7096:        if ($env{'request.course.sec'}) {
                   7097:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      7098:        }
                   7099:        $courseprivid=~s/\_/\//;
                   7100:        my $checkreferer=1;
1.232     www      7101:        my ($match,$cond)=&is_on_map($uri);
                   7102:        if ($match) {
                   7103:            $statecond=$cond;
1.620     albertel 7104:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7105:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7106:                my $value = $1;
                   7107:                if ($priv eq 'bre') {
1.1172.2.65  raeburn  7108:                    if ($noblockcheck) {
1.1162    raeburn  7109:                        $thisallowed.=$value;
1.1172.2.65  raeburn  7110:                    } else {
                   7111:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7112:                        if (@blockers > 0) {
                   7113:                            $thisallowed = 'B';
                   7114:                        } else {
                   7115:                            $thisallowed.=$value;
                   7116:                        }
1.1162    raeburn  7117:                    }
                   7118:                } else {
                   7119:                    $thisallowed.=$value;
                   7120:                }
1.52      www      7121:                $checkreferer=0;
                   7122:            }
1.29      www      7123:        }
1.83      www      7124:        
1.148     www      7125:        if ($checkreferer) {
1.620     albertel 7126: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      7127:             unless ($refuri) {
1.800     albertel 7128:                 foreach my $key (keys(%env)) {
                   7129: 		    if ($key=~/^httpref\..*\*/) {
                   7130: 			my $pattern=$key;
1.156     www      7131:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      7132:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   7133:                         $pattern=~s/\//\\\//g;
1.152     www      7134:                         if ($orguri=~/$pattern/) {
1.800     albertel 7135: 			    $refuri=$env{$key};
1.148     www      7136:                         }
                   7137:                     }
1.191     harris41 7138:                 }
1.148     www      7139:             }
1.232     www      7140: 
1.148     www      7141:          if ($refuri) { 
1.152     www      7142: 	  $refuri=&declutter($refuri);
1.232     www      7143:           my ($match,$cond)=&is_on_map($refuri);
                   7144:             if ($match) {
                   7145:               my $refstatecond=$cond;
1.620     albertel 7146:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7147:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7148:                   my $value = $1;
                   7149:                   if ($priv eq 'bre') {
1.1172.2.65  raeburn  7150:                       if ($noblockcheck) {
1.1162    raeburn  7151:                           $thisallowed.=$value;
1.1172.2.65  raeburn  7152:                       } else {
                   7153:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7154:                           if (@blockers > 0) {
                   7155:                               $thisallowed = 'B';
                   7156:                           } else {
                   7157:                               $thisallowed.=$value;
                   7158:                           }
1.1162    raeburn  7159:                       }
                   7160:                   } else {
                   7161:                       $thisallowed.=$value;
                   7162:                   }
1.53      www      7163:                   $uri=$refuri;
                   7164:                   $statecond=$refstatecond;
1.52      www      7165:               }
                   7166:           }
1.148     www      7167:         }
1.29      www      7168:        }
1.52      www      7169:    }
1.29      www      7170: 
1.52      www      7171: #
1.103     harris41 7172: # Gathered now: all privileges that could apply, and condition number
1.52      www      7173: # 
                   7174: #
                   7175: # Full or no access?
                   7176: #
1.29      www      7177: 
1.52      www      7178:     if ($thisallowed=~/F/) {
                   7179: 	return 'F';
                   7180:     }
1.29      www      7181: 
1.52      www      7182:     unless ($thisallowed) {
                   7183:         return '';
                   7184:     }
1.29      www      7185: 
1.52      www      7186: # Restrictions exist, deal with them
                   7187: #
                   7188: #   C:according to course preferences
                   7189: #   R:according to resource settings
                   7190: #   L:unless locked
                   7191: #   X:according to user session state
                   7192: #
                   7193: 
                   7194: # Possibly locked functionality, check all courses
1.54      www      7195: # Locks might take effect only after 10 minutes cache expiration for other
                   7196: # courses, and 2 minutes for current course
1.52      www      7197: 
                   7198:     my $envkey;
                   7199:     if ($thisallowed=~/L/) {
1.1000    raeburn  7200:         foreach $envkey (keys(%env)) {
1.54      www      7201:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   7202:                my $courseid=$2;
                   7203:                my $roleid=$1.'.'.$2;
1.92      www      7204:                $courseid=~s/^\///;
1.54      www      7205:                my $expiretime=600;
1.620     albertel 7206:                if ($env{'request.role'} eq $roleid) {
1.54      www      7207: 		  $expiretime=120;
                   7208:                }
                   7209: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   7210:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 7211:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 7212: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      7213:                }
1.620     albertel 7214:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7215:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   7216: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   7217:                        &log($env{'user.domain'},$env{'user.name'},
                   7218:                             $env{'user.home'},
1.57      www      7219:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      7220:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7221:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7222: 		       return '';
                   7223:                    }
                   7224:                }
1.620     albertel 7225:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7226:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   7227: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   7228:                        &log($env{'user.domain'},$env{'user.name'},
                   7229:                             $env{'user.home'},
1.57      www      7230:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      7231:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7232:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7233: 		       return '';
                   7234:                    }
                   7235:                }
                   7236: 	   }
1.29      www      7237:        }
1.52      www      7238:     }
                   7239:    
                   7240: #
                   7241: # Rest of the restrictions depend on selected course
                   7242: #
                   7243: 
1.620     albertel 7244:     unless ($env{'request.course.id'}) {
1.766     albertel 7245: 	if ($thisallowed eq 'A') {
                   7246: 	    return 'A';
1.814     raeburn  7247:         } elsif ($thisallowed eq 'B') {
                   7248:             return 'B';
1.766     albertel 7249: 	} else {
                   7250: 	    return '1';
                   7251: 	}
1.52      www      7252:     }
1.29      www      7253: 
1.52      www      7254: #
                   7255: # Now user is definitely in a course
                   7256: #
1.53      www      7257: 
                   7258: 
                   7259: # Course preferences
                   7260: 
                   7261:    if ($thisallowed=~/C/) {
1.620     albertel 7262:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   7263:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   7264:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 7265: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  7266: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7267: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7268: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   7269: 			$env{'request.course.id'});
                   7270: 	   }
1.237     www      7271:            return '';
                   7272:        }
                   7273: 
1.620     albertel 7274:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 7275: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  7276: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7277: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   7278: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   7279: 			$env{'request.course.id'});
                   7280: 	   }
1.54      www      7281:            return '';
                   7282:        }
1.53      www      7283:    }
                   7284: 
                   7285: # Resource preferences
                   7286: 
                   7287:    if ($thisallowed=~/R/) {
1.620     albertel 7288:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 7289:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  7290: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7291: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7292: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   7293: 	   }
                   7294: 	   return '';
1.54      www      7295:        }
1.53      www      7296:    }
1.30      www      7297: 
1.246     www      7298: # Restricted by state or randomout?
1.30      www      7299: 
1.52      www      7300:    if ($thisallowed=~/X/) {
1.620     albertel 7301:       if ($env{'acc.randomout'}) {
1.579     albertel 7302: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 7303:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      7304:             return ''; 
                   7305:          }
1.247     www      7306:       }
                   7307:       if (&condval($statecond)) {
1.52      www      7308: 	 return '2';
                   7309:       } else {
                   7310:          return '';
                   7311:       }
                   7312:    }
1.30      www      7313: 
1.766     albertel 7314:     if ($thisallowed eq 'A') {
                   7315: 	return 'A';
1.814     raeburn  7316:     } elsif ($thisallowed eq 'B') {
                   7317:         return 'B';
1.766     albertel 7318:     }
1.52      www      7319:    return 'F';
1.232     www      7320: }
1.1162    raeburn  7321: 
1.1172.2.13  raeburn  7322: # ------------------------------------------- Check construction space access
                   7323: 
                   7324: sub constructaccess {
                   7325:     my ($url,$setpriv)=@_;
                   7326: 
                   7327: # We do not allow editing of previous versions of files
                   7328:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   7329: 
                   7330: # Get username and domain from URL
                   7331:     my ($ownername,$ownerdomain,$ownerhome);
                   7332: 
                   7333:     ($ownerdomain,$ownername) =
1.1172.2.83  raeburn  7334:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13  raeburn  7335: 
                   7336: # The URL does not really point to any authorspace, forget it
                   7337:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   7338: 
                   7339: # Now we need to see if the user has access to the authorspace of
                   7340: # $ownername at $ownerdomain
                   7341: 
                   7342:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   7343: # Real author for this?
                   7344:        $ownerhome = $env{'user.home'};
                   7345:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   7346:           return ($ownername,$ownerdomain,$ownerhome);
                   7347:        }
                   7348:     } else {
                   7349: # Co-author for this?
                   7350:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   7351:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   7352:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   7353:             return ($ownername,$ownerdomain,$ownerhome);
                   7354:         }
                   7355:     }
                   7356: 
                   7357: # We don't have any access right now. If we are not possibly going to do anything about this,
                   7358: # we might as well leave
                   7359:    unless ($setpriv) { return ''; }
                   7360: 
                   7361: # Backdoor access?
                   7362:     my $allowed=&allowed('eco',$ownerdomain);
                   7363: # Nope
                   7364:     unless ($allowed) { return ''; }
                   7365: # Looks like we may have access, but could be locked by the owner of the construction space
                   7366:     if ($allowed eq 'U') {
                   7367:         my %blocked=&get('environment',['domcoord.author'],
                   7368:                          $ownerdomain,$ownername);
                   7369: # Is blocked by owner
                   7370:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   7371:     }
                   7372:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   7373: # Grant temporary access
                   7374:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  7375:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  7376:         if (!$update) { $update = $then; }
                   7377:         my $refresh=$env{'user.refresh.time'};
                   7378:         if (!$refresh) { $refresh = $update; }
                   7379:         my $now = time;
                   7380:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   7381:                            $now,'ca','constructaccess');
                   7382:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   7383:         return($ownername,$ownerdomain,$ownerhome);
                   7384:     }
                   7385: # No business here
                   7386:     return '';
                   7387: }
                   7388: 
1.1172.2.66  raeburn  7389: # ----------------------------------------------------------- Content Blocking
                   7390: 
                   7391: {
                   7392: # Caches for faster Course Contents display where content blocking
                   7393: # is in operation (i.e., interval param set) for timed quiz.
                   7394: #
                   7395: # User for whom data are being temporarily cached.
                   7396: my $cacheduser='';
                   7397: # Cached blockers for this user (a hash of blocking items).
                   7398: my %cachedblockers=();
                   7399: # When the data were last cached.
                   7400: my $cachedlast='';
                   7401: 
                   7402: sub load_all_blockers {
                   7403:     my ($uname,$udom,$blocks)=@_;
                   7404:     if (($uname ne '') && ($udom ne '')) {
                   7405:         if (($cacheduser eq $uname.':'.$udom) &&
                   7406:             (abs($cachedlast-time)<5)) {
                   7407:             return;
                   7408:         }
                   7409:     }
                   7410:     $cachedlast=time;
                   7411:     $cacheduser=$uname.':'.$udom;
                   7412:     %cachedblockers = &get_commblock_resources($blocks);
                   7413: }
                   7414: 
1.1162    raeburn  7415: sub get_comm_blocks {
                   7416:     my ($cdom,$cnum) = @_;
                   7417:     if ($cdom eq '' || $cnum eq '') {
                   7418:         return unless ($env{'request.course.id'});
                   7419:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7420:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7421:     }
                   7422:     my %commblocks;
                   7423:     my $hashid=$cdom.'_'.$cnum;
                   7424:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   7425:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   7426:         %commblocks = %{$blocksref};
                   7427:     } else {
                   7428:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   7429:         my $cachetime = 600;
                   7430:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   7431:     }
                   7432:     return %commblocks;
                   7433: }
                   7434: 
1.1172.2.66  raeburn  7435: sub get_commblock_resources {
                   7436:     my ($blocks) = @_;
                   7437:     my %blockers = ();
                   7438:     return %blockers unless ($env{'request.course.id'});
                   7439:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  7440:     my %commblocks;
                   7441:     if (ref($blocks) eq 'HASH') {
                   7442:         %commblocks = %{$blocks};
                   7443:     } else {
                   7444:         %commblocks = &get_comm_blocks();
                   7445:     }
1.1172.2.66  raeburn  7446:     return %blockers unless (keys(%commblocks) > 0);
1.1163    raeburn  7447:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66  raeburn  7448:     return %blockers unless (ref($navmap));
                   7449:     my $now = time;
1.1162    raeburn  7450:     foreach my $block (keys(%commblocks)) {
                   7451:         if ($block =~ /^(\d+)____(\d+)$/) {
                   7452:             my ($start,$end) = ($1,$2);
                   7453:             if ($start <= $now && $end >= $now) {
                   7454:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7455:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7456:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66  raeburn  7457:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7458:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162    raeburn  7459:                             }
                   7460:                         }
                   7461:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66  raeburn  7462:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7463:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  7464:                             }
                   7465:                         }
                   7466:                     }
                   7467:                 }
                   7468:             }
                   7469:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   7470:             my $item = $1;
1.1163    raeburn  7471:             my @to_test;
1.1162    raeburn  7472:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7473:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.66  raeburn  7474:                     my @interval;
                   7475:                     my $type = 'map';
                   7476:                     if ($item eq 'course') {
                   7477:                         $type = 'course';
                   7478:                         @interval=&EXT("resource.0.interval");
                   7479:                     } else {
                   7480:                         if ($item =~ /___\d+___/) {
                   7481:                             $type = 'resource';
                   7482:                             @interval=&EXT("resource.0.interval",$item);
                   7483:                             if (ref($navmap)) {
                   7484:                                 my $res = $navmap->getBySymb($item);
                   7485:                                 push(@to_test,$res);
                   7486:                             }
1.1162    raeburn  7487:                         } else {
1.1172.2.66  raeburn  7488:                             my $mapsymb = &symbread($item,1);
                   7489:                             if ($mapsymb) {
                   7490:                                 if (ref($navmap)) {
                   7491:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   7492:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   7493:                                     foreach my $res (@to_test) {
                   7494:                                         my $symb = $res->symb();
                   7495:                                         next if ($symb eq $mapsymb);
                   7496:                                         if ($symb ne '') {
                   7497:                                             @interval=&EXT("resource.0.interval",$symb);
                   7498:                                             if ($interval[1] eq 'map') {
                   7499:                                                 last;
1.1162    raeburn  7500:                                             }
                   7501:                                         }
                   7502:                                     }
                   7503:                                 }
                   7504:                             }
                   7505:                         }
1.1172.2.66  raeburn  7506:                     }
                   7507:                     if ($interval[0] =~ /^\d+$/) {
                   7508:                         my $first_access;
                   7509:                         if ($type eq 'resource') {
                   7510:                             $first_access=&get_first_access($interval[1],$item);
                   7511:                         } elsif ($type eq 'map') {
                   7512:                             $first_access=&get_first_access($interval[1],undef,$item);
                   7513:                         } else {
                   7514:                             $first_access=&get_first_access($interval[1]);
                   7515:                         }
                   7516:                         if ($first_access) {
                   7517:                             my $timesup = $first_access+$interval[0];
                   7518:                             if ($timesup > $now) {
                   7519:                                 my $activeblock;
                   7520:                                 foreach my $res (@to_test) {
                   7521:                                     if ($res->answerable()) {
                   7522:                                         $activeblock = 1;
                   7523:                                         last;
                   7524:                                     }
                   7525:                                 }
                   7526:                                 if ($activeblock) {
                   7527:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   7528:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7529:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   7530:                                          }
                   7531:                                     }
                   7532:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   7533:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7534:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  7535:                                         }
1.1162    raeburn  7536:                                     }
                   7537:                                 }
                   7538:                             }
                   7539:                         }
                   7540:                     }
                   7541:                 }
                   7542:             }
                   7543:         }
                   7544:     }
1.1172.2.66  raeburn  7545:     return %blockers;
1.1162    raeburn  7546: }
                   7547: 
1.1172.2.66  raeburn  7548: sub has_comm_blocking {
                   7549:     my ($priv,$symb,$uri,$blocks) = @_;
                   7550:     my @blockers;
                   7551:     return unless ($env{'request.course.id'});
                   7552:     return unless ($priv eq 'bre');
                   7553:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   7554:     return if ($env{'request.state'} eq 'construct');
                   7555:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   7556:     return unless (keys(%cachedblockers) > 0);
                   7557:     my (%possibles,@symbs);
                   7558:     if (!$symb) {
                   7559:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  7560:     }
1.1172.2.66  raeburn  7561:     if ($symb) {
                   7562:         @symbs = ($symb);
                   7563:     } elsif (keys(%possibles)) {
                   7564:         @symbs = keys(%possibles);
                   7565:     }
                   7566:     my $noblock;
                   7567:     foreach my $symb (@symbs) {
                   7568:         last if ($noblock);
                   7569:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   7570:         foreach my $block (keys(%cachedblockers)) {
                   7571:             if ($block =~ /^firstaccess____(.+)$/) {
                   7572:                 my $item = $1;
                   7573:                 if (($item eq $map) || ($item eq $symb)) {
                   7574:                     $noblock = 1;
                   7575:                     last;
                   7576:                 }
1.1162    raeburn  7577:             }
1.1172.2.66  raeburn  7578:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   7579:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   7580:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   7581:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   7582:                             push(@blockers,$block);
                   7583:                         }
                   7584:                     }
                   7585:                 }
                   7586:             }
                   7587:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   7588:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   7589:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   7590:                         push(@blockers,$block);
                   7591:                     }
                   7592:                 }
1.1162    raeburn  7593:             }
                   7594:         }
                   7595:     }
1.1172.2.66  raeburn  7596:     return if ($noblock);
                   7597:     return @blockers;
                   7598: }
1.1162    raeburn  7599: }
                   7600: 
1.1172.2.66  raeburn  7601: # -------------------------------- Deversion and split uri into path an filename
                   7602: 
1.1133    foxr     7603: #
1.1172.2.66  raeburn  7604: #   Removes the version from a URI and
1.1133    foxr     7605: #   splits it in to its filename and path to the filename.
                   7606: #   Seems like File::Basename could have done this more clearly.
                   7607: #   Parameters:
                   7608: #      $uri   - input URI
                   7609: #   Returns:
                   7610: #     Two element list consisting of 
                   7611: #     $pathname  - the URI up to and excluding the trailing /
                   7612: #     $filename  - The part of the URI following the last /
                   7613: #  NOTE:
                   7614: #    Another realization of this is simply:
                   7615: #    use File::Basename;
                   7616: #    ...
                   7617: #    $uri = shift;
                   7618: #    $filename = basename($uri);
                   7619: #    $path     = dirname($uri);
                   7620: #    return ($filename, $path);
                   7621: #
                   7622: #     The implementation below is probably faster however.
                   7623: #
1.710     albertel 7624: sub split_uri_for_cond {
                   7625:     my $uri=&deversion(&declutter(shift));
                   7626:     my @uriparts=split(/\//,$uri);
                   7627:     my $filename=pop(@uriparts);
                   7628:     my $pathname=join('/',@uriparts);
                   7629:     return ($pathname,$filename);
                   7630: }
1.232     www      7631: # --------------------------------------------------- Is a resource on the map?
                   7632: 
                   7633: sub is_on_map {
1.710     albertel 7634:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 7635:     #Trying to find the conditional for the file
1.620     albertel 7636:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 7637: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      7638:     if ($match) {
1.289     bowersj2 7639: 	return (1,$1);
                   7640:     } else {
1.434     www      7641: 	return (0,0);
1.289     bowersj2 7642:     }
1.12      www      7643: }
                   7644: 
1.427     www      7645: # --------------------------------------------------------- Get symb from alias
                   7646: 
                   7647: sub get_symb_from_alias {
                   7648:     my $symb=shift;
                   7649:     my ($map,$resid,$url)=&decode_symb($symb);
                   7650: # Already is a symb
                   7651:     if ($url) { return $symb; }
                   7652: # Must be an alias
                   7653:     my $aliassymb='';
                   7654:     my %bighash;
1.620     albertel 7655:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      7656:                             &GDBM_READER(),0640)) {
                   7657:         my $rid=$bighash{'mapalias_'.$symb};
                   7658: 	if ($rid) {
                   7659: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 7660: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   7661: 				    $resid,$bighash{'src_'.$rid});
1.427     www      7662: 	}
                   7663:         untie %bighash;
                   7664:     }
                   7665:     return $aliassymb;
                   7666: }
                   7667: 
1.12      www      7668: # ----------------------------------------------------------------- Define Role
                   7669: 
                   7670: sub definerole {
                   7671:   if (allowed('mcr','/')) {
1.1172.2.84  raeburn  7672:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 7673:     foreach my $role (split(':',$sysrole)) {
                   7674: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7675:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   7676:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   7677: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7678:                return "refused:s:$crole&$cqual"; 
                   7679:             }
                   7680:         }
1.191     harris41 7681:     }
1.800     albertel 7682:     foreach my $role (split(':',$domrole)) {
                   7683: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7684:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   7685:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   7686: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      7687:                return "refused:d:$crole&$cqual"; 
                   7688:             }
                   7689:         }
1.191     harris41 7690:     }
1.800     albertel 7691:     foreach my $role (split(':',$courole)) {
                   7692: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7693:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   7694:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   7695: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7696:                return "refused:c:$crole&$cqual"; 
                   7697:             }
                   7698:         }
1.191     harris41 7699:     }
1.1172.2.84  raeburn  7700:     my $uhome;
                   7701:     if (($uname ne '') && ($udom ne '')) {
                   7702:         $uhome = &homeserver($uname,$udom);
                   7703:         return $uhome if ($uhome eq 'no_host');
                   7704:     } else {
                   7705:         $uname = $env{'user.name'};
                   7706:         $udom = $env{'user.domain'};
                   7707:         $uhome = $env{'user.home'};
                   7708:     }
1.620     albertel 7709:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84  raeburn  7710:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      7711:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84  raeburn  7712:     return reply($command,$uhome);
1.12      www      7713:   } else {
                   7714:     return 'refused';
                   7715:   }
1.105     harris41 7716: }
                   7717: 
                   7718: # ---------------- Make a metadata query against the network of library servers
                   7719: 
                   7720: sub metadata_query {
1.1172.2.33  raeburn  7721:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 7722:     my %rhash;
1.845     albertel 7723:     my %libserv = &all_library();
1.244     matthew  7724:     my @server_list = (defined($server_array) ? @$server_array
                   7725:                                               : keys(%libserv) );
                   7726:     for my $server (@server_list) {
1.1172.2.33  raeburn  7727:         my $domains = '';
                   7728:         if (ref($domains_hash) eq 'HASH') {
                   7729:             $domains = $domains_hash->{$server};    
                   7730:         }
1.118     harris41 7731: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  7732: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 7733: 	    $rhash{$server}=$reply;
                   7734: 	}
                   7735: 	else {
                   7736: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  7737: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 7738: 			     $server);
                   7739: 	    $rhash{$server}=$reply;
                   7740: 	}
1.112     harris41 7741:     }
1.118     harris41 7742:     return \%rhash;
1.240     www      7743: }
                   7744: 
                   7745: # ----------------------------------------- Send log queries and wait for reply
                   7746: 
                   7747: sub log_query {
                   7748:     my ($uname,$udom,$query,%filters)=@_;
                   7749:     my $uhome=&homeserver($uname,$udom);
                   7750:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 7751:     my $uhost=&hostname($uhome);
1.800     albertel 7752:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      7753:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   7754:                        $uhome);
1.479     albertel 7755:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      7756:     return get_query_reply($queryid);
                   7757: }
                   7758: 
1.818     raeburn  7759: # -------------------------- Update MySQL table for portfolio file
                   7760: 
                   7761: sub update_portfolio_table {
1.821     raeburn  7762:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  7763:     if ($group ne '') {
                   7764:         $file_name =~s /^\Q$group\E//;
                   7765:     }
1.818     raeburn  7766:     my $homeserver = &homeserver($uname,$udom);
                   7767:     my $queryid=
1.821     raeburn  7768:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   7769:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  7770:     my $reply = &get_query_reply($queryid);
                   7771:     return $reply;
                   7772: }
                   7773: 
1.899     raeburn  7774: # -------------------------- Update MySQL allusers table
                   7775: 
                   7776: sub update_allusers_table {
                   7777:     my ($uname,$udom,$names) = @_;
                   7778:     my $homeserver = &homeserver($uname,$udom);
                   7779:     my $queryid=
                   7780:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   7781:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   7782:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   7783:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   7784:                'generation='.&escape($names->{'generation'}).'%%'.
                   7785:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   7786:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  7787:     return;
1.899     raeburn  7788: }
                   7789: 
1.508     raeburn  7790: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  7791: 
                   7792: sub fetch_enrollment_query {
1.511     raeburn  7793:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79  raeburn  7794:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  7795:     my $maxtries = 1;
1.508     raeburn  7796:     if ($context eq 'automated') {
                   7797:         $homeserver = $perlvar{'lonHostID'};
1.1172.2.79  raeburn  7798:         $sleep = 2;
                   7799:         $loopmax = 100;
1.547     raeburn  7800:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  7801:     } else {
                   7802:         $homeserver = &homeserver($cnum,$dom);
                   7803:     }
1.838     albertel 7804:     my $host=&hostname($homeserver);
1.506     raeburn  7805:     my $cmd = '';
1.1000    raeburn  7806:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 7807:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  7808:     }
                   7809:     $cmd =~ s/%%$//;
                   7810:     $cmd = &escape($cmd);
                   7811:     my $query = 'fetchenrollment';
1.620     albertel 7812:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  7813:     unless ($queryid=~/^\Q$host\E\_/) { 
                   7814:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   7815:         return 'error: '.$queryid;
                   7816:     }
1.1172.2.79  raeburn  7817:     my $reply = &get_query_reply($queryid,$sleep.$loopmax);
1.547     raeburn  7818:     my $tries = 1;
                   7819:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79  raeburn  7820:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  7821:         $tries ++;
                   7822:     }
1.526     raeburn  7823:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 7824:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  7825:     } else {
1.901     albertel 7826:         my @responses = split(/:/,$reply);
1.1172.2.82  raeburn  7827:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 7828:             foreach my $line (@responses) {
                   7829:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  7830:                 $$replyref{$key} = $value;
                   7831:             }
                   7832:         } else {
1.1117    foxr     7833:             my $pathname = LONCAPA::tempdir();
1.800     albertel 7834:             foreach my $line (@responses) {
                   7835:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  7836:                 $$replyref{$key} = $value;
                   7837:                 if ($value > 0) {
1.800     albertel 7838:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   7839:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  7840:                         my $destname = $pathname.'/'.$filename;
                   7841:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  7842:                         if ($xml_classlist =~ /^error/) {
                   7843:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   7844:                         } else {
1.506     raeburn  7845:                             if ( open(FILE,">$destname") ) {
                   7846:                                 print FILE &unescape($xml_classlist);
                   7847:                                 close(FILE);
1.526     raeburn  7848:                             } else {
                   7849:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  7850:                             }
                   7851:                         }
                   7852:                     }
                   7853:                 }
                   7854:             }
                   7855:         }
                   7856:         return 'ok';
                   7857:     }
                   7858:     return 'error';
                   7859: }
                   7860: 
1.242     www      7861: sub get_query_reply {
1.1172.2.79  raeburn  7862:     my ($queryid,$sleep,$loopmax) = @_;
                   7863:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   7864:         $sleep = 0.2;
                   7865:     }
                   7866:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   7867:         $loopmax = 100;
                   7868:     }
1.1117    foxr     7869:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      7870:     my $reply='';
1.1172.2.79  raeburn  7871:     for (1..$loopmax) {
                   7872: 	sleep($sleep);
1.240     www      7873:         if (-e $replyfile.'.end') {
1.448     albertel 7874: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 7875: 		$reply = join('',<$fh>);
                   7876: 		close($fh);
1.240     www      7877: 	   } else { return 'error: reply_file_error'; }
1.242     www      7878:            return &unescape($reply);
                   7879: 	}
1.240     www      7880:     }
1.242     www      7881:     return 'timeout:'.$queryid;
1.240     www      7882: }
                   7883: 
                   7884: sub courselog_query {
1.241     www      7885: #
                   7886: # possible filters:
                   7887: # url: url or symb
                   7888: # username
                   7889: # domain
                   7890: # action: view, submit, grade
                   7891: # start: timestamp
                   7892: # end: timestamp
                   7893: #
1.240     www      7894:     my (%filters)=@_;
1.620     albertel 7895:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      7896:     if ($filters{'url'}) {
                   7897: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   7898:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   7899:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   7900:     }
1.620     albertel 7901:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7902:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      7903:     return &log_query($cname,$cdom,'courselog',%filters);
                   7904: }
                   7905: 
                   7906: sub userlog_query {
1.858     raeburn  7907: #
                   7908: # possible filters:
                   7909: # action: log check role
                   7910: # start: timestamp
                   7911: # end: timestamp
                   7912: #
1.240     www      7913:     my ($uname,$udom,%filters)=@_;
                   7914:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      7915: }
                   7916: 
1.506     raeburn  7917: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   7918: 
                   7919: sub auto_run {
1.508     raeburn  7920:     my ($cnum,$cdom) = @_;
1.876     raeburn  7921:     my $response = 0;
                   7922:     my $settings;
                   7923:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   7924:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   7925:         $settings = $domconfig{'autoenroll'};
                   7926:         if ($settings->{'run'} eq '1') {
                   7927:             $response = 1;
                   7928:         }
                   7929:     } else {
1.934     raeburn  7930:         my $homeserver;
                   7931:         if (&is_course($cdom,$cnum)) {
                   7932:             $homeserver = &homeserver($cnum,$cdom);
                   7933:         } else {
                   7934:             $homeserver = &domain($cdom,'primary');
                   7935:         }
                   7936:         if ($homeserver ne 'no_host') {
                   7937:             $response = &reply('autorun:'.$cdom,$homeserver);
                   7938:         }
1.876     raeburn  7939:     }
1.506     raeburn  7940:     return $response;
                   7941: }
1.776     albertel 7942: 
1.506     raeburn  7943: sub auto_get_sections {
1.508     raeburn  7944:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  7945:     my $homeserver;
                   7946:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   7947:         $homeserver = &homeserver($cnum,$cdom);
                   7948:     }
                   7949:     if (!defined($homeserver)) { 
                   7950:         if ($cdom =~ /^$match_domain$/) {
                   7951:             $homeserver = &domain($cdom,'primary');
                   7952:         }
                   7953:     }
                   7954:     my @secs;
                   7955:     if (defined($homeserver)) {
                   7956:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   7957:         unless ($response eq 'refused') {
                   7958:             @secs = split(/:/,$response);
                   7959:         }
1.506     raeburn  7960:     }
                   7961:     return @secs;
                   7962: }
1.776     albertel 7963: 
1.506     raeburn  7964: sub auto_new_course {
1.1099    raeburn  7965:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  7966:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  7967:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  7968:     return $response;
                   7969: }
1.776     albertel 7970: 
1.506     raeburn  7971: sub auto_validate_courseID {
1.508     raeburn  7972:     my ($cnum,$cdom,$inst_course_id) = @_;
                   7973:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  7974:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  7975:     return $response;
                   7976: }
1.776     albertel 7977: 
1.1007    raeburn  7978: sub auto_validate_instcode {
1.1020    raeburn  7979:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  7980:     my ($homeserver,$response);
                   7981:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7982:         $homeserver = &homeserver($cnum,$cdom);
                   7983:     }
                   7984:     if (!defined($homeserver)) {
                   7985:         if ($cdom =~ /^$match_domain$/) {
                   7986:             $homeserver = &domain($cdom,'primary');
                   7987:         }
                   7988:     }
1.1065    raeburn  7989:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   7990:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  7991:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   7992:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  7993: }
                   7994: 
1.506     raeburn  7995: sub auto_create_password {
1.873     raeburn  7996:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   7997:     my ($homeserver,$response);
1.506     raeburn  7998:     my $create_passwd = 0;
                   7999:     my $authchk = '';
1.873     raeburn  8000:     if ($udom =~ /^$match_domain$/) {
                   8001:         $homeserver = &domain($udom,'primary');
                   8002:     }
                   8003:     if ($homeserver eq '') {
                   8004:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8005:             $homeserver = &homeserver($cnum,$cdom);
                   8006:         }
                   8007:     }
                   8008:     if ($homeserver eq '') {
                   8009:         $authchk = 'nodomain';
1.506     raeburn  8010:     } else {
1.873     raeburn  8011:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   8012:         if ($response eq 'refused') {
                   8013:             $authchk = 'refused';
                   8014:         } else {
1.901     albertel 8015:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  8016:         }
1.506     raeburn  8017:     }
                   8018:     return ($authparam,$create_passwd,$authchk);
                   8019: }
                   8020: 
1.706     raeburn  8021: sub auto_photo_permission {
                   8022:     my ($cnum,$cdom,$students) = @_;
                   8023:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 8024:     my ($outcome,$perm_reqd,$conditions) = 
                   8025: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 8026:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8027: 	return (undef,undef);
                   8028:     }
1.706     raeburn  8029:     return ($outcome,$perm_reqd,$conditions);
                   8030: }
                   8031: 
                   8032: sub auto_checkphotos {
                   8033:     my ($uname,$udom,$pid) = @_;
                   8034:     my $homeserver = &homeserver($uname,$udom);
                   8035:     my ($result,$resulttype);
                   8036:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 8037: 				   &escape($uname).':'.&escape($pid),
                   8038: 				   $homeserver));
1.709     albertel 8039:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8040: 	return (undef,undef);
                   8041:     }
1.706     raeburn  8042:     if ($outcome) {
                   8043:         ($result,$resulttype) = split(/:/,$outcome);
                   8044:     } 
                   8045:     return ($result,$resulttype);
                   8046: }
                   8047: 
                   8048: sub auto_photochoice {
                   8049:     my ($cnum,$cdom) = @_;
                   8050:     my $homeserver = &homeserver($cnum,$cdom);
                   8051:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 8052: 						       &escape($cdom),
                   8053: 						       $homeserver)));
1.709     albertel 8054:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8055: 	return (undef,undef);
                   8056:     }
1.706     raeburn  8057:     return ($update,$comment);
                   8058: }
                   8059: 
                   8060: sub auto_photoupdate {
                   8061:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   8062:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 8063:     my $host=&hostname($homeserver);
1.706     raeburn  8064:     my $cmd = '';
                   8065:     my $maxtries = 1;
1.800     albertel 8066:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   8067:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  8068:     }
                   8069:     $cmd =~ s/%%$//;
                   8070:     $cmd = &escape($cmd);
                   8071:     my $query = 'institutionalphotos';
                   8072:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   8073:     unless ($queryid=~/^\Q$host\E\_/) {
                   8074:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   8075:         return 'error: '.$queryid;
                   8076:     }
                   8077:     my $reply = &get_query_reply($queryid);
                   8078:     my $tries = 1;
                   8079:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   8080:         $reply = &get_query_reply($queryid);
                   8081:         $tries ++;
                   8082:     }
                   8083:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   8084:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   8085:     } else {
                   8086:         my @responses = split(/:/,$reply);
                   8087:         my $outcome = shift(@responses); 
                   8088:         foreach my $item (@responses) {
                   8089:             my ($key,$value) = split(/=/,$item);
                   8090:             $$photo{$key} = $value;
                   8091:         }
                   8092:         return $outcome;
                   8093:     }
                   8094:     return 'error';
                   8095: }
                   8096: 
1.521     raeburn  8097: sub auto_instcode_format {
1.793     albertel 8098:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   8099: 	$cat_order) = @_;
1.521     raeburn  8100:     my $courses = '';
1.772     raeburn  8101:     my @homeservers;
1.521     raeburn  8102:     if ($caller eq 'global') {
1.841     albertel 8103: 	my %servers = &get_servers($codedom,'library');
                   8104: 	foreach my $tryserver (keys(%servers)) {
                   8105: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8106: 		push(@homeservers,$tryserver);
                   8107: 	    }
1.584     raeburn  8108:         }
1.1022    raeburn  8109:     } elsif ($caller eq 'requests') {
                   8110:         if ($codedom =~ /^$match_domain$/) {
                   8111:             my $chome = &domain($codedom,'primary');
                   8112:             unless ($chome eq 'no_host') {
                   8113:                 push(@homeservers,$chome);
                   8114:             }
                   8115:         }
1.521     raeburn  8116:     } else {
1.772     raeburn  8117:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  8118:     }
1.793     albertel 8119:     foreach my $code (keys(%{$instcodes})) {
                   8120:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  8121:     }
                   8122:     chop($courses);
1.772     raeburn  8123:     my $ok_response = 0;
                   8124:     my $response;
                   8125:     while (@homeservers > 0 && $ok_response == 0) {
                   8126:         my $server = shift(@homeservers); 
                   8127:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   8128:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   8129:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 8130: 		split(/:/,$response);
1.772     raeburn  8131:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   8132:             push(@{$codetitles},&str2array($codetitles_str));
                   8133:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   8134:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   8135:             $ok_response = 1;
                   8136:         }
                   8137:     }
                   8138:     if ($ok_response) {
1.521     raeburn  8139:         return 'ok';
1.772     raeburn  8140:     } else {
                   8141:         return $response;
1.521     raeburn  8142:     }
                   8143: }
                   8144: 
1.792     raeburn  8145: sub auto_instcode_defaults {
                   8146:     my ($domain,$returnhash,$code_order) = @_;
                   8147:     my @homeservers;
1.841     albertel 8148: 
                   8149:     my %servers = &get_servers($domain,'library');
                   8150:     foreach my $tryserver (keys(%servers)) {
                   8151: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8152: 	    push(@homeservers,$tryserver);
                   8153: 	}
1.792     raeburn  8154:     }
1.841     albertel 8155: 
1.792     raeburn  8156:     my $response;
1.841     albertel 8157:     foreach my $server (@homeservers) {
1.792     raeburn  8158:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 8159:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   8160: 	
                   8161: 	foreach my $pair (split(/\&/,$response)) {
                   8162: 	    my ($name,$value)=split(/\=/,$pair);
                   8163: 	    if ($name eq 'code_order') {
                   8164: 		@{$code_order} = split(/\&/,&unescape($value));
                   8165: 	    } else {
                   8166: 		$returnhash->{&unescape($name)}=&unescape($value);
                   8167: 	    }
                   8168: 	}
                   8169: 	return 'ok';
1.792     raeburn  8170:     }
1.841     albertel 8171: 
                   8172:     return $response;
1.1003    raeburn  8173: }
                   8174: 
                   8175: sub auto_possible_instcodes {
1.1007    raeburn  8176:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   8177:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   8178:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8179:         return;
                   8180:     }
1.1003    raeburn  8181:     my (@homeservers,$uhome);
                   8182:     if (defined(&domain($domain,'primary'))) {
                   8183:         $uhome=&domain($domain,'primary');
                   8184:         push(@homeservers,&domain($domain,'primary'));
                   8185:     } else {
                   8186:         my %servers = &get_servers($domain,'library');
                   8187:         foreach my $tryserver (keys(%servers)) {
                   8188:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8189:                 push(@homeservers,$tryserver);
                   8190:             }
                   8191:         }
                   8192:     }
                   8193:     my $response;
                   8194:     foreach my $server (@homeservers) {
                   8195:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   8196:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  8197:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   8198:             split(':',$response);
                   8199:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   8200:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  8201:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  8202:             my ($name,$value)=split('=',$item);
                   8203:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8204:         }
                   8205:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  8206:             my ($name,$value)=split('=',$item);
                   8207:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8208:         }
                   8209:         return 'ok';
                   8210:     }
                   8211:     return $response;
                   8212: }
1.792     raeburn  8213: 
1.1010    raeburn  8214: sub auto_courserequest_checks {
                   8215:     my ($dom) = @_;
1.1020    raeburn  8216:     my ($homeserver,%validations);
                   8217:     if ($dom =~ /^$match_domain$/) {
                   8218:         $homeserver = &domain($dom,'primary');
                   8219:     }
                   8220:     unless ($homeserver eq 'no_host') {
                   8221:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   8222:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8223:             my @items = split(/&/,$response);
                   8224:             foreach my $item (@items) {
                   8225:                 my ($key,$value) = split('=',$item);
                   8226:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   8227:             }
                   8228:         }
                   8229:     }
1.1010    raeburn  8230:     return %validations; 
                   8231: }
                   8232: 
1.1020    raeburn  8233: sub auto_courserequest_validation {
1.1172.2.43  raeburn  8234:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  8235:     my ($homeserver,$response);
                   8236:     if ($dom =~ /^$match_domain$/) {
                   8237:         $homeserver = &domain($dom,'primary');
                   8238:     }
1.1172.2.43  raeburn  8239:     unless ($homeserver eq 'no_host') {
                   8240:         my $customdata;
                   8241:         if (ref($custominfo) eq 'HASH') {
                   8242:             $customdata = &freeze_escape($custominfo);
                   8243:         }
1.1020    raeburn  8244:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  8245:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43  raeburn  8246:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   8247:                                     $customdata,$homeserver));
1.1020    raeburn  8248:     }
                   8249:     return $response;
                   8250: }
                   8251: 
1.777     albertel 8252: sub auto_validate_class_sec {
1.918     raeburn  8253:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  8254:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  8255:     my $ownerlist;
                   8256:     if (ref($owners) eq 'ARRAY') {
                   8257:         $ownerlist = join(',',@{$owners});
                   8258:     } else {
                   8259:         $ownerlist = $owners;
                   8260:     }
1.773     raeburn  8261:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  8262:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  8263:     return $response;
                   8264: }
                   8265: 
1.1172.2.38  raeburn  8266: sub auto_crsreq_update {
                   8267:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45  raeburn  8268:         $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38  raeburn  8269:     my ($homeserver,%crsreqresponse);
                   8270:     if ($cdom =~ /^$match_domain$/) {
                   8271:         $homeserver = &domain($cdom,'primary');
                   8272:     }
                   8273:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8274:         my $info;
                   8275:         if (ref($inbound) eq 'HASH') {
                   8276:             $info = &freeze_escape($inbound);
                   8277:         }
                   8278:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   8279:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   8280:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45  raeburn  8281:                             &escape($title).':'.&escape($code).':'.
                   8282:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38  raeburn  8283:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8284:             my @items = split(/&/,$response);
                   8285:             foreach my $item (@items) {
                   8286:                 my ($key,$value) = split('=',$item);
                   8287:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   8288:             }
                   8289:         }
                   8290:     }
                   8291:     return \%crsreqresponse;
                   8292: }
                   8293: 
1.1172.2.78  raeburn  8294: sub auto_export_grades {
                   8295:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   8296:     my ($homeserver,%exportresponse);
                   8297:     if ($cdom =~ /^$match_domain$/) {
                   8298:         $homeserver = &domain($cdom,'primary');
                   8299:     }
                   8300:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8301:         my $info;
                   8302:         if (ref($inforef) eq 'HASH') {
                   8303:             $info = &freeze_escape($inforef);
                   8304:         }
                   8305:         if (ref($gradesref) eq 'HASH') {
                   8306:             my $grades = &freeze_escape($gradesref);
                   8307:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   8308:                                 $info.':'.$grades,$homeserver);
                   8309:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   8310:                 my @items = split(/&/,$response);
                   8311:                 foreach my $item (@items) {
                   8312:                     my ($key,$value) = split('=',$item);
                   8313:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   8314:                 }
                   8315:             }
                   8316:         }
                   8317:     }
                   8318:     return \%exportresponse;
                   8319: }
                   8320: 
1.1172.2.68  raeburn  8321: sub check_instcode_cloning {
                   8322:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   8323:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8324:         return;
                   8325:     }
                   8326:     my $canclone;
                   8327:     if (@{$code_order} > 0) {
                   8328:         my $instcoderegexp ='^';
                   8329:         my @clonecodes = split(/\&/,$cloner);
                   8330:         foreach my $item (@{$code_order}) {
                   8331:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   8332:                 foreach my $pair (@clonecodes) {
                   8333:                     my ($key,$val) = split(/\=/,$pair,2);
                   8334:                     $val = &unescape($val);
                   8335:                     if ($key eq $item) {
                   8336:                         $instcoderegexp .= '('.$val.')';
                   8337:                         last;
                   8338:                     }
                   8339:                 }
                   8340:             } else {
                   8341:                 $instcoderegexp .= $codedefaults->{$item};
                   8342:             }
                   8343:         }
                   8344:         $instcoderegexp .= '$';
                   8345:         my (@from,@to);
                   8346:         eval {
                   8347:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8348:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8349:         };
                   8350:         if ((@from > 0) && (@to > 0)) {
                   8351:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8352:             if (!@diffs) {
                   8353:                 $canclone = 1;
                   8354:             }
                   8355:         }
                   8356:     }
                   8357:     return $canclone;
                   8358: }
                   8359: 
                   8360: sub default_instcode_cloning {
                   8361:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   8362:     my (%codedefaults,@code_order,$canclone);
                   8363:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   8364:         %codedefaults = %{$codedefaultsref};
                   8365:         @code_order = @{$codeorderref};
                   8366:     } elsif ($clonedom) {
                   8367:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   8368:     }
                   8369:     if (($domdefclone) && (@code_order)) {
                   8370:         my @clonecodes = split(/\+/,$domdefclone);
                   8371:         my $instcoderegexp ='^';
                   8372:         foreach my $item (@code_order) {
                   8373:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   8374:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   8375:             } else {
                   8376:                 $instcoderegexp .= $codedefaults{$item};
                   8377:             }
                   8378:         }
                   8379:         $instcoderegexp .= '$';
                   8380:         my (@from,@to);
                   8381:         eval {
                   8382:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8383:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8384:         };
                   8385:         if ((@from > 0) && (@to > 0)) {
                   8386:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8387:             if (!@diffs) {
                   8388:                 $canclone = 1;
                   8389:             }
                   8390:         }
                   8391:     }
                   8392:     return $canclone;
                   8393: }
                   8394: 
1.679     raeburn  8395: # ------------------------------------------------------- Course Group routines
                   8396: 
                   8397: sub get_coursegroups {
1.809     raeburn  8398:     my ($cdom,$cnum,$group,$namespace) = @_;
                   8399:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  8400: }
                   8401: 
1.679     raeburn  8402: sub modify_coursegroup {
                   8403:     my ($cdom,$cnum,$groupsettings) = @_;
                   8404:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   8405: }
                   8406: 
1.809     raeburn  8407: sub toggle_coursegroup_status {
                   8408:     my ($cdom,$cnum,$group,$action) = @_;
                   8409:     my ($from_namespace,$to_namespace);
                   8410:     if ($action eq 'delete') {
                   8411:         $from_namespace = 'coursegroups';
                   8412:         $to_namespace = 'deleted_groups';
                   8413:     } else {
                   8414:         $from_namespace = 'deleted_groups';
                   8415:         $to_namespace = 'coursegroups';
                   8416:     }
                   8417:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  8418:     if (my $tmp = &error(%curr_group)) {
                   8419:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   8420:         return ('read error',$tmp);
                   8421:     } else {
                   8422:         my %savedsettings = %curr_group; 
1.809     raeburn  8423:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  8424:         my $deloutcome;
                   8425:         if ($result eq 'ok') {
1.809     raeburn  8426:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  8427:         } else {
                   8428:             return ('write error',$result);
                   8429:         }
                   8430:         if ($deloutcome eq 'ok') {
                   8431:             return 'ok';
                   8432:         } else {
                   8433:             return ('delete error',$deloutcome);
                   8434:         }
                   8435:     }
                   8436: }
                   8437: 
1.679     raeburn  8438: sub modify_group_roles {
1.957     raeburn  8439:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  8440:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   8441:     my $role = 'gr/'.&escape($userprivs);
                   8442:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  8443:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  8444:     if ($result eq 'ok') {
                   8445:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   8446:     }
1.679     raeburn  8447:     return $result;
                   8448: }
                   8449: 
                   8450: sub modify_coursegroup_membership {
                   8451:     my ($cdom,$cnum,$membership) = @_;
                   8452:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   8453:     return $result;
                   8454: }
                   8455: 
1.682     raeburn  8456: sub get_active_groups {
                   8457:     my ($udom,$uname,$cdom,$cnum) = @_;
                   8458:     my $now = time;
                   8459:     my %groups = ();
                   8460:     foreach my $key (keys(%env)) {
1.811     albertel 8461:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  8462:             my ($start,$end) = split(/\./,$env{$key});
                   8463:             if (($end!=0) && ($end<$now)) { next; }
                   8464:             if (($start!=0) && ($start>$now)) { next; }
                   8465:             if ($1 eq $cdom && $2 eq $cnum) {
                   8466:                 $groups{$3} = $env{$key} ;
                   8467:             }
                   8468:         }
                   8469:     }
                   8470:     return %groups;
                   8471: }
                   8472: 
1.683     raeburn  8473: sub get_group_membership {
                   8474:     my ($cdom,$cnum,$group) = @_;
                   8475:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   8476: }
                   8477: 
                   8478: sub get_users_groups {
                   8479:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  8480:     my @usersgroups;
1.683     raeburn  8481:     my $cachetime=1800;
                   8482: 
                   8483:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  8484:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   8485:     if (defined($cached)) {
1.734     albertel 8486:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  8487:     } else {  
                   8488:         $grouplist = '';
1.816     raeburn  8489:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  8490:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  8491:         my $access_end = $env{'course.'.$courseid.
                   8492:                               '.default_enrollment_end_date'};
                   8493:         my $now = time;
                   8494:         foreach my $key (keys(%roleshash)) {
                   8495:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   8496:                 my $group = $1;
                   8497:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   8498:                     my $start = $2;
                   8499:                     my $end = $1;
                   8500:                     if ($start == -1) { next; } # deleted from group
                   8501:                     if (($start!=0) && ($start>$now)) { next; }
                   8502:                     if (($end!=0) && ($end<$now)) {
                   8503:                         if ($access_end && $access_end < $now) {
                   8504:                             if ($access_end - $end < 86400) {
                   8505:                                 push(@usersgroups,$group);
1.733     raeburn  8506:                             }
                   8507:                         }
1.817     raeburn  8508:                         next;
1.733     raeburn  8509:                     }
1.817     raeburn  8510:                     push(@usersgroups,$group);
1.683     raeburn  8511:                 }
                   8512:             }
                   8513:         }
1.817     raeburn  8514:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   8515:         $grouplist = join(':',@usersgroups);
                   8516:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  8517:     }
1.733     raeburn  8518:     return @usersgroups;
1.683     raeburn  8519: }
                   8520: 
                   8521: sub devalidate_getgroups_cache {
                   8522:     my ($udom,$uname,$cdom,$cnum)=@_;
                   8523:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 8524: 
1.683     raeburn  8525:     my $hashid="$udom:$uname:$courseid";
                   8526:     &devalidate_cache_new('getgroups',$hashid);
                   8527: }
                   8528: 
1.12      www      8529: # ------------------------------------------------------------------ Plain Text
                   8530: 
                   8531: sub plaintext {
1.988     raeburn  8532:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  8533:     if ($short =~ m{^cr/}) {
1.758     albertel 8534: 	return (split('/',$short))[-1];
                   8535:     }
1.742     raeburn  8536:     if (!defined($cid)) {
                   8537:         $cid = $env{'request.course.id'};
                   8538:     }
                   8539:     my %rolenames = (
1.1008    raeburn  8540:                       Course    => 'std',
                   8541:                       Community => 'alt1',
1.742     raeburn  8542:                     );
1.1037    raeburn  8543:     if ($cid ne '') {
                   8544:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   8545:             unless ($forcedefault) {
                   8546:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   8547:                 &Apache::lonlocal::mt_escape(\$roletext);
                   8548:                 return &Apache::lonlocal::mt($roletext);
                   8549:             }
                   8550:         }
                   8551:     }
                   8552:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   8553:         (defined($rolenames{$type})) && 
                   8554:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  8555:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  8556:     } elsif ($cid ne '') {
                   8557:         my $crstype = $env{'course.'.$cid.'.type'};
                   8558:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   8559:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   8560:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   8561:         }
1.742     raeburn  8562:     }
1.1037    raeburn  8563:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      8564: }
                   8565: 
                   8566: # ----------------------------------------------------------------- Assign Role
                   8567: 
                   8568: sub assignrole {
1.957     raeburn  8569:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   8570:         $context)=@_;
1.21      www      8571:     my $mrole;
                   8572:     if ($role =~ /^cr\//) {
1.393     www      8573:         my $cwosec=$url;
1.811     albertel 8574:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      8575: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  8576:            my $refused = 1;
                   8577:            if ($context eq 'requestcourses') {
                   8578:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   8579:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   8580:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   8581:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8582:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8583:                            if ($crsenv{'internal.courseowner'} eq
                   8584:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   8585:                                $refused = '';
                   8586:                            }
                   8587:                        }
                   8588:                    }
                   8589:                }
                   8590:            }
                   8591:            if ($refused) {
                   8592:                &logthis('Refused custom assignrole: '.
                   8593:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   8594:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   8595:                return 'refused';
                   8596:            }
1.104     www      8597:         }
1.21      www      8598:         $mrole='cr';
1.678     raeburn  8599:     } elsif ($role =~ /^gr\//) {
                   8600:         my $cwogrp=$url;
1.811     albertel 8601:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  8602:         unless (&allowed('mdg',$cwogrp)) {
                   8603:             &logthis('Refused group assignrole: '.
                   8604:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   8605:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   8606:             return 'refused';
                   8607:         }
                   8608:         $mrole='gr';
1.21      www      8609:     } else {
1.82      www      8610:         my $cwosec=$url;
1.811     albertel 8611:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  8612:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   8613:             my $refused;
                   8614:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   8615:                 if (!(&allowed('c'.$role,$url))) {
                   8616:                     $refused = 1;
                   8617:                 }
                   8618:             } else {
                   8619:                 $refused = 1;
                   8620:             }
1.947     raeburn  8621:             if ($refused) {
1.1045    raeburn  8622:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8623:                 if (!$selfenroll && $context eq 'course') {
                   8624:                     my %crsenv;
                   8625:                     if ($role eq 'cc' || $role eq 'co') {
                   8626:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8627:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   8628:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   8629:                                 if ($crsenv{'internal.courseowner'} eq 
                   8630:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8631:                                     $refused = '';
                   8632:                                 }
                   8633:                             }
                   8634:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   8635:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   8636:                                 if ($crsenv{'internal.courseowner'} eq 
                   8637:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8638:                                     $refused = '';
                   8639:                                 }
                   8640:                             }
                   8641:                         }
                   8642:                     }
                   8643:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  8644:                     $refused = '';
1.1017    raeburn  8645:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  8646:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  8647:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  8648:                         my $wrongcc;
                   8649:                         if ($cnum =~ /^$match_community$/) {
                   8650:                             $wrongcc = 1 if ($role eq 'cc');
                   8651:                         } else {
                   8652:                             $wrongcc = 1 if ($role eq 'co');
                   8653:                         }
                   8654:                         unless ($wrongcc) {
                   8655:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8656:                             if ($crsenv{'internal.courseowner'} eq 
                   8657:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   8658:                                 $refused = '';
                   8659:                             }
1.1017    raeburn  8660:                         }
                   8661:                     }
1.1172.2.9  raeburn  8662:                 } elsif ($context eq 'requestauthor') {
                   8663:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   8664:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   8665:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   8666:                             $refused = '';
                   8667:                         } else {
                   8668:                             my %domdefaults = &get_domain_defaults($udom);
                   8669:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   8670:                                 my $checkbystatus;
                   8671:                                 if ($env{'user.adv'}) {
                   8672:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   8673:                                     if ($disposition eq 'automatic') {
                   8674:                                         $refused = '';
                   8675:                                     } elsif ($disposition eq '') {
                   8676:                                         $checkbystatus = 1;
                   8677:                                     }
                   8678:                                 } else {
                   8679:                                     $checkbystatus = 1;
                   8680:                                 }
                   8681:                                 if ($checkbystatus) {
                   8682:                                     if ($env{'environment.inststatus'}) {
                   8683:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   8684:                                         foreach my $type (@inststatuses) {
                   8685:                                             if (($type ne '') &&
                   8686:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   8687:                                                 $refused = '';
                   8688:                                             }
                   8689:                                         }
                   8690:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   8691:                                         $refused = '';
                   8692:                                     }
                   8693:                                 }
                   8694:                             }
                   8695:                         }
                   8696:                     }
1.1017    raeburn  8697:                 }
                   8698:                 if ($refused) {
1.947     raeburn  8699:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   8700:                              ' '.$role.' '.$end.' '.$start.' by '.
                   8701: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   8702:                     return 'refused';
                   8703:                 }
1.932     raeburn  8704:             }
1.1131    raeburn  8705:         } elsif ($role eq 'au') {
                   8706:             if ($url ne '/'.$udom.'/') {
                   8707:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   8708:                          ' to assign author role for '.$uname.':'.$udom.
                   8709:                          ' in domain: '.$url.' refused (wrong domain).');
                   8710:                 return 'refused';
                   8711:             }
1.104     www      8712:         }
1.21      www      8713:         $mrole=$role;
                   8714:     }
1.620     albertel 8715:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      8716:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      8717:     if ($end) { $command.='_'.$end; }
1.21      www      8718:     if ($start) {
                   8719: 	if ($end) { 
1.81      www      8720:            $command.='_'.$start; 
1.21      www      8721:         } else {
1.81      www      8722:            $command.='_0_'.$start;
1.21      www      8723:         }
                   8724:     }
1.739     raeburn  8725:     my $origstart = $start;
                   8726:     my $origend = $end;
1.957     raeburn  8727:     my $delflag;
1.357     www      8728: # actually delete
                   8729:     if ($deleteflag) {
1.373     www      8730: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      8731: # modify command to delete the role
1.620     albertel 8732:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      8733:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 8734: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      8735: # set start and finish to negative values for userrolelog
                   8736:            $start=-1;
                   8737:            $end=-1;
1.957     raeburn  8738:            $delflag = 1;
1.357     www      8739:         }
                   8740:     }
                   8741: # send command
1.349     www      8742:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      8743: # log new user role if status is ok
1.349     www      8744:     if ($answer eq 'ok') {
1.663     raeburn  8745: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  8746:         if (($role eq 'cc') || ($role eq 'in') ||
                   8747:             ($role eq 'ep') || ($role eq 'ad') ||
                   8748:             ($role eq 'ta') || ($role eq 'st') ||
                   8749:             ($role=~/^cr/) || ($role eq 'gr') ||
                   8750:             ($role eq 'co')) {
1.1172.2.13  raeburn  8751: # for course roles, perform group memberships changes triggered by role change.
                   8752:             unless ($role =~ /^gr/) {
                   8753:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   8754:                                                  $origstart,$selfenroll,$context);
                   8755:             }
1.1172.2.9  raeburn  8756:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8757:                            $selfenroll,$context);
                   8758:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.84  raeburn  8759:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh')) {
1.1172.2.9  raeburn  8760:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8761:                            $context);
                   8762:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   8763:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8764:                              $context);
                   8765:         }
1.1053    raeburn  8766:         if ($role eq 'cc') {
                   8767:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   8768:         }
1.349     www      8769:     }
                   8770:     return $answer;
1.169     harris41 8771: }
                   8772: 
1.1053    raeburn  8773: sub autoupdate_coowners {
                   8774:     my ($url,$end,$start,$uname,$udom) = @_;
                   8775:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   8776:     if (($cdom ne '') && ($cnum ne '')) {
                   8777:         my $now = time;
                   8778:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   8779:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   8780:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   8781:             my $instcode = $coursehash{'internal.coursecode'};
                   8782:             if ($instcode ne '') {
1.1056    raeburn  8783:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   8784:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  8785:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  8786:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   8787:                         if ($result eq 'valid') {
                   8788:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  8789:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8790:                                     push(@newcoowners,$coowner);
                   8791:                                 }
                   8792:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   8793:                                     push(@newcoowners,$uname.':'.$udom);
                   8794:                                 }
                   8795:                                 @newcoowners = sort(@newcoowners);
                   8796:                             } else {
                   8797:                                 push(@newcoowners,$uname.':'.$udom);
                   8798:                             }
                   8799:                         } else {
                   8800:                             if ($coursehash{'internal.co-owners'}) {
                   8801:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8802:                                     unless ($coowner eq $uname.':'.$udom) {
                   8803:                                         push(@newcoowners,$coowner);
                   8804:                                     }
                   8805:                                 }
                   8806:                                 unless (@newcoowners > 0) {
                   8807:                                     $delcoowners = 1;
                   8808:                                     $coowners = '';
                   8809:                                 }
                   8810:                             }
                   8811:                         }
                   8812:                         if (@newcoowners || $delcoowners) {
                   8813:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   8814:                                             $delcoowners,@newcoowners);
                   8815:                         }
                   8816:                     }
                   8817:                 }
                   8818:             }
                   8819:         }
                   8820:     }
                   8821: }
                   8822: 
                   8823: sub store_coowners {
                   8824:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   8825:     my $cid = $cdom.'_'.$cnum;
                   8826:     my ($coowners,$delresult,$putresult);
                   8827:     if (@newcoowners) {
                   8828:         $coowners = join(',',@newcoowners);
                   8829:         my %coownershash = (
                   8830:                             'internal.co-owners' => $coowners,
                   8831:                            );
                   8832:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   8833:         if ($putresult eq 'ok') {
                   8834:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   8835:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   8836:             }
                   8837:         }
                   8838:     }
                   8839:     if ($delcoowners) {
                   8840:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   8841:         if ($delresult eq 'ok') {
                   8842:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   8843:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   8844:             }
                   8845:         }
                   8846:     }
                   8847:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   8848:         my %crsinfo =
                   8849:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   8850:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   8851:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   8852:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   8853:         }
                   8854:     }
                   8855: }
                   8856: 
1.169     harris41 8857: # -------------------------------------------------- Modify user authentication
1.197     www      8858: # Overrides without validation
                   8859: 
1.169     harris41 8860: sub modifyuserauth {
                   8861:     my ($udom,$uname,$umode,$upass)=@_;
                   8862:     my $uhome=&homeserver($uname,$udom);
1.197     www      8863:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   8864:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 8865:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8866:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 8867:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   8868: 		     &escape($upass),$uhome);
1.620     albertel 8869:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      8870:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   8871:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   8872:     &log($udom,,$uname,$uhome,
1.620     albertel 8873:         'Authentication changed by '.$env{'user.domain'}.', '.
                   8874:                                      $env{'user.name'}.', '.$umode.
1.197     www      8875:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 8876:     unless ($reply eq 'ok') {
1.197     www      8877:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 8878: 	return 'error: '.$reply;
                   8879:     }   
1.170     harris41 8880:     return 'ok';
1.80      www      8881: }
                   8882: 
1.81      www      8883: # --------------------------------------------------------------- Modify a user
1.80      www      8884: 
1.81      www      8885: sub modifyuser {
1.206     matthew  8886:     my ($udom,    $uname, $uid,
                   8887:         $umode,   $upass, $first,
                   8888:         $middle,  $last,  $gene,
1.1058    raeburn  8889:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 8890:     $udom= &LONCAPA::clean_domain($udom);
                   8891:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  8892:     my $showcandelete = 'none';
                   8893:     if (ref($candelete) eq 'ARRAY') {
                   8894:         if (@{$candelete} > 0) {
                   8895:             $showcandelete = join(', ',@{$candelete});
                   8896:         }
                   8897:     }
1.81      www      8898:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      8899:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  8900: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  8901:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   8902:                                      ' desiredhome not specified'). 
1.620     albertel 8903:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8904:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 8905:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  8906:     my $newuser;
                   8907:     if ($uhome eq 'no_host') {
                   8908:         $newuser = 1;
                   8909:     }
1.80      www      8910: # ----------------------------------------------------------------- Create User
1.406     albertel 8911:     if (($uhome eq 'no_host') && 
                   8912: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      8913:         my $unhome='';
1.844     albertel 8914:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  8915:             $unhome = $desiredhome;
1.620     albertel 8916: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   8917: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  8918:         } else { # load balancing routine for determining $unhome
1.81      www      8919:             my $loadm=10000000;
1.841     albertel 8920: 	    my %servers = &get_servers($udom,'library');
                   8921: 	    foreach my $tryserver (keys(%servers)) {
                   8922: 		my $answer=reply('load',$tryserver);
                   8923: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   8924: 		    $loadm=$answer;
                   8925: 		    $unhome=$tryserver;
                   8926: 		}
1.80      www      8927: 	    }
                   8928:         }
                   8929:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  8930: 	    return 'error: unable to find a home server for '.$uname.
                   8931:                    ' in domain '.$udom;
1.80      www      8932:         }
                   8933:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   8934:                          &escape($upass),$unhome);
                   8935: 	unless ($reply eq 'ok') {
                   8936:             return 'error: '.$reply;
                   8937:         }   
1.230     stredwic 8938:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      8939:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  8940: 	    return 'error: unable verify users home machine.';
1.80      www      8941:         }
1.209     matthew  8942:     }   # End of creation of new user
1.80      www      8943: # ---------------------------------------------------------------------- Add ID
                   8944:     if ($uid) {
                   8945:        $uid=~tr/A-Z/a-z/;
                   8946:        my %uidhash=&idrget($udom,$uname);
1.196     www      8947:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   8948:          && (!$forceid)) {
1.80      www      8949: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  8950: 	      return 'error: user id "'.$uid.'" does not match '.
                   8951:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      8952:           }
                   8953:        } else {
                   8954: 	  &idput($udom,($uname => $uid));
                   8955:        }
                   8956:     }
                   8957: # -------------------------------------------------------------- Add names, etc
1.313     matthew  8958:     my @tmp=&get('environment',
1.899     raeburn  8959: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  8960:                     'permanentemail','inststatus'],
1.134     albertel 8961: 		   $udom,$uname);
1.1075    raeburn  8962:     my (%names,%oldnames);
1.313     matthew  8963:     if ($tmp[0] =~ m/^error:.*/) { 
                   8964:         %names=(); 
                   8965:     } else {
                   8966:         %names = @tmp;
1.1075    raeburn  8967:         %oldnames = %names;
1.313     matthew  8968:     }
1.388     www      8969: #
1.1058    raeburn  8970: # If name, email and/or uid are blank (e.g., because an uploaded file
                   8971: # of users did not contain them), do not overwrite existing values
                   8972: # unless field is in $candelete array ref.  
                   8973: #
                   8974: 
                   8975:     my @fields = ('firstname','middlename','lastname','generation',
                   8976:                   'permanentemail','id');
                   8977:     my %newvalues;
                   8978:     if (ref($candelete) eq 'ARRAY') {
                   8979:         foreach my $field (@fields) {
                   8980:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   8981:                 if ($field eq 'firstname') {
                   8982:                     $names{$field} = $first;
                   8983:                 } elsif ($field eq 'middlename') {
                   8984:                     $names{$field} = $middle;
                   8985:                 } elsif ($field eq 'lastname') {
                   8986:                     $names{$field} = $last;
                   8987:                 } elsif ($field eq 'generation') { 
                   8988:                     $names{$field} = $gene;
                   8989:                 } elsif ($field eq 'permanentemail') {
                   8990:                     $names{$field} = $email;
                   8991:                 } elsif ($field eq 'id') {
                   8992:                     $names{$field}  = $uid;
                   8993:                 }
                   8994:             }
                   8995:         }
                   8996:     }
1.388     www      8997:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  8998:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      8999:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  9000:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      9001:     if ($email) {
                   9002:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  9003:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      9004:     }
1.899     raeburn  9005:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  9006:     if (defined($inststatus)) {
                   9007:         $names{'inststatus'} = '';
                   9008:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   9009:         if (ref($usertypes) eq 'HASH') {
                   9010:             my @okstatuses; 
                   9011:             foreach my $item (split(/:/,$inststatus)) {
                   9012:                 if (defined($usertypes->{$item})) {
                   9013:                     push(@okstatuses,$item);  
                   9014:                 }
                   9015:             }
                   9016:             if (@okstatuses) {
                   9017:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   9018:             }
                   9019:         }
                   9020:     }
1.1075    raeburn  9021:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  9022:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  9023:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  9024:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   9025:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   9026:     } else {
                   9027:         $logmsg .= ' during self creation';
                   9028:     }
1.1075    raeburn  9029:     my $changed;
                   9030:     if ($newuser) {
                   9031:         $changed = 1;
                   9032:     } else {
                   9033:         foreach my $field (@fields) {
                   9034:             if ($names{$field} ne $oldnames{$field}) {
                   9035:                 $changed = 1;
                   9036:                 last;
                   9037:             }
                   9038:         }
                   9039:     }
                   9040:     unless ($changed) {
                   9041:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   9042:         &logthis($logmsg);
                   9043:         return 'ok';
                   9044:     }
                   9045:     my $reply = &put('environment', \%names, $udom,$uname);
                   9046:     if ($reply ne 'ok') { 
                   9047:         return 'error: '.$reply;
                   9048:     }
1.1087    raeburn  9049:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   9050:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   9051:     }
1.1075    raeburn  9052:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   9053:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   9054:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  9055:     &logthis($logmsg);
1.134     albertel 9056:     return 'ok';
1.80      www      9057: }
                   9058: 
1.81      www      9059: # -------------------------------------------------------------- Modify student
1.80      www      9060: 
1.81      www      9061: sub modifystudent {
                   9062:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  9063:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76  raeburn  9064:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 9065:     if (!$cid) {
1.620     albertel 9066: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9067: 	    return 'not_in_class';
                   9068: 	}
1.80      www      9069:     }
                   9070: # --------------------------------------------------------------- Make the user
1.81      www      9071:     my $reply=&modifyuser
1.209     matthew  9072: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  9073:          $desiredhome,$email,$inststatus);
1.80      www      9074:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  9075:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  9076:     # student's environment
1.297     matthew  9077:     $uid = undef if (!$forceid);
1.455     albertel 9078:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  9079: 					$gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76  raeburn  9080:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  9081:     return $reply;
                   9082: }
                   9083: 
                   9084: sub modify_student_enrollment {
1.1172.2.23  raeburn  9085:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76  raeburn  9086:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 9087:     my ($cdom,$cnum,$chome);
                   9088:     if (!$cid) {
1.620     albertel 9089: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9090: 	    return 'not_in_class';
                   9091: 	}
1.620     albertel 9092: 	$cdom=$env{'course.'.$cid.'.domain'};
                   9093: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 9094:     } else {
                   9095: 	($cdom,$cnum)=split(/_/,$cid);
                   9096:     }
1.620     albertel 9097:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 9098:     if (!$chome) {
1.457     raeburn  9099: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  9100:     }
1.455     albertel 9101:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  9102:     # Make sure the user exists
1.81      www      9103:     my $uhome=&homeserver($uname,$udom);
                   9104:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9105: 	return 'error: no such user';
                   9106:     }
1.297     matthew  9107:     # Get student data if we were not given enough information
                   9108:     if (!defined($first)  || $first  eq '' || 
                   9109:         !defined($last)   || $last   eq '' || 
                   9110:         !defined($uid)    || $uid    eq '' || 
                   9111:         !defined($middle) || $middle eq '' || 
                   9112:         !defined($gene)   || $gene   eq '') {
1.294     matthew  9113:         # They did not supply us with enough data to enroll the student, so
                   9114:         # we need to pick up more information.
1.297     matthew  9115:         my %tmp = &get('environment',
1.294     matthew  9116:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  9117:                        ,$udom,$uname);
                   9118: 
1.800     albertel 9119:         #foreach my $key (keys(%tmp)) {
                   9120:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 9121:         #}
1.294     matthew  9122:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   9123:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   9124:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  9125:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  9126:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   9127:     }
1.556     albertel 9128:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  9129:     my $user = "$uname:$udom";
                   9130:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 9131:     my $reply=cput('classlist',
1.1148    raeburn  9132: 		   {$user => 
1.1172.2.76  raeburn  9133: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 9134: 		   $cdom,$cnum);
1.1148    raeburn  9135:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   9136:         &devalidate_getsection_cache($udom,$uname,$cid);
                   9137:     } else { 
1.81      www      9138: 	return 'error: '.$reply;
                   9139:     }
1.297     matthew  9140:     # Add student role to user
1.83      www      9141:     my $uurl='/'.$cid;
1.81      www      9142:     $uurl=~s/\_/\//g;
                   9143:     if ($usec) {
                   9144: 	$uurl.='/'.$usec;
                   9145:     }
1.1148    raeburn  9146:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   9147:                              $selfenroll,$context);
                   9148:     if ($result ne 'ok') {
                   9149:         if ($old_entry{$user} ne '') {
                   9150:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   9151:         } else {
                   9152:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   9153:         }
                   9154:     }
                   9155:     return $result; 
1.21      www      9156: }
                   9157: 
1.556     albertel 9158: sub format_name {
                   9159:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   9160:     my $name;
                   9161:     if ($first ne 'lastname') {
                   9162: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   9163:     } else {
                   9164: 	if ($lastname=~/\S/) {
                   9165: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   9166: 	    $name=~s/\s+,/,/;
                   9167: 	} else {
                   9168: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   9169: 	}
                   9170:     }
                   9171:     $name=~s/^\s+//;
                   9172:     $name=~s/\s+$//;
                   9173:     $name=~s/\s+/ /g;
                   9174:     return $name;
                   9175: }
                   9176: 
1.84      www      9177: # ------------------------------------------------- Write to course preferences
                   9178: 
                   9179: sub writecoursepref {
                   9180:     my ($courseid,%prefs)=@_;
                   9181:     $courseid=~s/^\///;
                   9182:     $courseid=~s/\_/\//g;
                   9183:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   9184:     my $chome=homeserver($cnum,$cdomain);
                   9185:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   9186: 	return 'error: no such course';
                   9187:     }
                   9188:     my $cstring='';
1.800     albertel 9189:     foreach my $pref (keys(%prefs)) {
                   9190: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 9191:     }
1.84      www      9192:     $cstring=~s/\&$//;
                   9193:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   9194: }
                   9195: 
                   9196: # ---------------------------------------------------------- Make/modify course
                   9197: 
                   9198: sub createcourse {
1.741     raeburn  9199:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  9200:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      9201:     $url=&declutter($url);
                   9202:     my $cid='';
1.1028    raeburn  9203:     if ($context eq 'requestcourses') {
                   9204:         my $can_create = 0;
                   9205:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   9206:         if ($udom eq $ownerdom) {
                   9207:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   9208:                                   $context)) {
                   9209:                 $can_create = 1;
                   9210:             }
                   9211:         } else {
                   9212:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   9213:                                            $category);
                   9214:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   9215:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   9216:                 if (@curr > 0) {
                   9217:                     my @options = qw(approval validate autolimit);
                   9218:                     my $optregex = join('|',@options);
                   9219:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   9220:                         $can_create = 1;
                   9221:                     }
                   9222:                 }
                   9223:             }
                   9224:         }
                   9225:         if ($can_create) {
                   9226:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   9227:                 unless (&allowed('ccc',$udom)) {
                   9228:                     return 'refused'; 
                   9229:                 }
1.1017    raeburn  9230:             }
                   9231:         } else {
                   9232:             return 'refused';
                   9233:         }
1.1028    raeburn  9234:     } elsif (!&allowed('ccc',$udom)) {
                   9235:         return 'refused';
1.84      www      9236:     }
1.1011    raeburn  9237: # --------------------------------------------------------------- Get Unique ID
                   9238:     my $uname;
                   9239:     if ($cnum =~ /^$match_courseid$/) {
                   9240:         my $chome=&homeserver($cnum,$udom,'true');
                   9241:         if (($chome eq '') || ($chome eq 'no_host')) {
                   9242:             $uname = $cnum;
                   9243:         } else {
1.1038    raeburn  9244:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9245:         }
                   9246:     } else {
1.1038    raeburn  9247:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9248:     }
                   9249:     return $uname if ($uname =~ /^error/);
                   9250: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  9251:     if (!defined($course_server)) {
                   9252:         if (defined(&domain($udom,'primary'))) {
                   9253:             $course_server = &domain($udom,'primary');
                   9254:         } else {
                   9255:             $course_server = $env{'user.home'}; 
                   9256:         }
                   9257:     }
                   9258:     my %host_servers =
                   9259:         &Apache::lonnet::get_servers($udom,'library');
                   9260:     unless ($host_servers{$course_server}) {
                   9261:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  9262:     }
1.84      www      9263: # ------------------------------------------------------------- Make the course
                   9264:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  9265:                       $course_server);
1.84      www      9266:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  9267:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      9268:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9269: 	return 'error: no such course';
                   9270:     }
1.271     www      9271: # ----------------------------------------------------------------- Course made
1.516     raeburn  9272: # log existence
1.1029    raeburn  9273:     my $now = time;
1.918     raeburn  9274:     my $newcourse = {
                   9275:                     $udom.'_'.$uname => {
1.921     raeburn  9276:                                      description => $description,
                   9277:                                      inst_code   => $inst_code,
                   9278:                                      owner       => $course_owner,
                   9279:                                      type        => $crstype,
1.1029    raeburn  9280:                                      creator     => $env{'user.name'}.':'.
                   9281:                                                     $env{'user.domain'},
                   9282:                                      created     => $now,
                   9283:                                      context     => $context,
1.918     raeburn  9284:                                                 },
                   9285:                     };
1.921     raeburn  9286:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      9287: # set toplevel url
1.271     www      9288:     my $topurl=$url;
                   9289:     unless ($nonstandard) {
                   9290: # ------------------------------------------ For standard courses, make top url
                   9291:         my $mapurl=&clutter($url);
1.278     www      9292:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 9293:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      9294: <map>
                   9295: <resource id="1" type="start"></resource>
                   9296: <resource id="2" src="$mapurl"></resource>
                   9297: <resource id="3" type="finish"></resource>
                   9298: <link index="1" from="1" to="2"></link>
                   9299: <link index="2" from="2" to="3"></link>
                   9300: </map>
                   9301: ENDINITMAP
                   9302:         $topurl=&declutter(
1.638     albertel 9303:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      9304:                           );
                   9305:     }
                   9306: # ----------------------------------------------------------- Write preferences
1.84      www      9307:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  9308:                      ('description'              => $description,
                   9309:                       'url'                      => $topurl,
                   9310:                       'internal.creator'         => $env{'user.name'}.':'.
                   9311:                                                     $env{'user.domain'},
                   9312:                       'internal.created'         => $now,
                   9313:                       'internal.creationcontext' => $context)
                   9314:                     );
1.84      www      9315:     return '/'.$udom.'/'.$uname;
                   9316: }
                   9317: 
1.1011    raeburn  9318: # ------------------------------------------------------------------- Create ID
                   9319: sub generate_coursenum {
1.1038    raeburn  9320:     my ($udom,$crstype) = @_;
1.1011    raeburn  9321:     my $domdesc = &domain($udom);
                   9322:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  9323:     my $first;
                   9324:     if ($crstype eq 'Community') {
                   9325:         $first = '0';
                   9326:     } else {
                   9327:         $first = int(1+rand(9)); 
                   9328:     } 
                   9329:     my $uname=$first.
1.1011    raeburn  9330:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9331:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9332:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9333: # ----------------------------------------------- Make sure that does not exist
                   9334:     my $uhome=&homeserver($uname,$udom,'true');
                   9335:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  9336:         if ($crstype eq 'Community') {
                   9337:             $first = '0';
                   9338:         } else {
                   9339:             $first = int(1+rand(9));
                   9340:         }
                   9341:         $uname=$first.
1.1011    raeburn  9342:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9343:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9344:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9345:         $uhome=&homeserver($uname,$udom,'true');
                   9346:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   9347:             return 'error: unable to generate unique course-ID';
                   9348:         }
                   9349:     }
                   9350:     return $uname;
                   9351: }
                   9352: 
1.813     albertel 9353: sub is_course {
1.1167    droeschl 9354:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   9355:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   9356: 
                   9357:     return unless $cdom and $cnum;
                   9358: 
                   9359:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   9360:         '.');
                   9361: 
1.1172.2.23  raeburn  9362:     return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167    droeschl 9363:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 9364: }
                   9365: 
1.1015    raeburn  9366: sub store_userdata {
                   9367:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  9368:     my $result;
1.1016    raeburn  9369:     if ($datakey ne '') {
1.1013    raeburn  9370:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  9371:             if ($udom eq '' || $uname eq '') {
                   9372:                 $udom = $env{'user.domain'};
                   9373:                 $uname = $env{'user.name'};
                   9374:             }
                   9375:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  9376:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   9377:                 $result = 'error: no_host';
                   9378:             } else {
                   9379:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   9380:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   9381: 
                   9382:                 my $namevalue='';
                   9383:                 foreach my $key (keys(%{$storehash})) {
                   9384:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   9385:                 }
                   9386:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  9387:                 unless ($namespace eq 'courserequests') {
                   9388:                     $datakey = &escape($datakey);
                   9389:                 }
1.1105    raeburn  9390:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   9391:                                   $namevalue,$uhome);
1.1013    raeburn  9392:             }
                   9393:         } else {
                   9394:             $result = 'error: data to store was not a hash reference'; 
                   9395:         }
                   9396:     } else {
                   9397:         $result= 'error: invalid requestkey'; 
                   9398:     }
                   9399:     return $result;
                   9400: }
                   9401: 
1.21      www      9402: # ---------------------------------------------------------- Assign Custom Role
                   9403: 
                   9404: sub assigncustomrole {
1.957     raeburn  9405:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9406:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  9407:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      9408: }
                   9409: 
                   9410: # ----------------------------------------------------------------- Revoke Role
                   9411: 
                   9412: sub revokerole {
1.957     raeburn  9413:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9414:     my $now=time;
1.965     raeburn  9415:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      9416: }
                   9417: 
                   9418: # ---------------------------------------------------------- Revoke Custom Role
                   9419: 
                   9420: sub revokecustomrole {
1.957     raeburn  9421:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9422:     my $now=time;
1.357     www      9423:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  9424:            $deleteflag,$selfenroll,$context);
1.17      www      9425: }
                   9426: 
1.533     banghart 9427: # ------------------------------------------------------------ Disk usage
1.535     albertel 9428: sub diskusage {
1.955     raeburn  9429:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   9430:     $directorypath =~ s/\/$//;
                   9431:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   9432:                        .&escape($getpropath).':'.&escape($uname).':'
                   9433:                        .&escape($udom),homeserver($uname,$udom));
                   9434:     if ($listing eq 'unknown_cmd') {
                   9435:         if ($getpropath) {
                   9436:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   9437:         }
                   9438:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   9439:     }
1.514     albertel 9440:     return $listing;
1.512     banghart 9441: }
                   9442: 
1.566     banghart 9443: sub is_locked {
1.1096    raeburn  9444:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 9445:     my @check;
                   9446:     my $is_locked;
1.1093    raeburn  9447:     push (@check,$file_name);
1.613     albertel 9448:     my %locked = &get('file_permissions',\@check,
1.620     albertel 9449: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 9450:     my ($tmp)=keys(%locked);
                   9451:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  9452:     
1.566     banghart 9453:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  9454:         $is_locked = 'false';
                   9455:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  9456:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  9457:                $is_locked = 'true';
1.1096    raeburn  9458:                if (ref($which) eq 'ARRAY') {
                   9459:                    push(@{$which},$entry);
                   9460:                } else {
                   9461:                    last;
                   9462:                }
1.745     raeburn  9463:            }
                   9464:        }
1.566     banghart 9465:     } else {
                   9466:         $is_locked = 'false';
                   9467:     }
1.1093    raeburn  9468:     return $is_locked;
1.566     banghart 9469: }
                   9470: 
1.759     albertel 9471: sub declutter_portfile {
                   9472:     my ($file) = @_;
1.833     albertel 9473:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 9474:     return $file;
                   9475: }
                   9476: 
1.559     banghart 9477: # ------------------------------------------------------------- Mark as Read Only
                   9478: 
                   9479: sub mark_as_readonly {
                   9480:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 9481:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9482:     my ($tmp)=keys(%current_permissions);
                   9483:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 9484:     foreach my $file (@{$files}) {
1.759     albertel 9485: 	$file = &declutter_portfile($file);
1.561     banghart 9486:         push(@{$current_permissions{$file}},$what);
1.559     banghart 9487:     }
1.613     albertel 9488:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9489:     return;
                   9490: }
                   9491: 
1.572     banghart 9492: # ------------------------------------------------------------Save Selected Files
                   9493: 
                   9494: sub save_selected_files {
                   9495:     my ($user, $path, @files) = @_;
                   9496:     my $filename = $user."savedfiles";
1.573     banghart 9497:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 9498:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 9499:     foreach my $file (@files) {
1.620     albertel 9500:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 9501:     }
                   9502:     foreach my $file (@other_files) {
1.574     banghart 9503:         print (OUT $file."\n");
1.572     banghart 9504:     }
1.574     banghart 9505:     close (OUT);
1.572     banghart 9506:     return 'ok';
                   9507: }
                   9508: 
1.574     banghart 9509: sub clear_selected_files {
                   9510:     my ($user) = @_;
                   9511:     my $filename = $user."savedfiles";
1.1117    foxr     9512:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 9513:     print (OUT undef);
                   9514:     close (OUT);
                   9515:     return ("ok");    
                   9516: }
                   9517: 
1.572     banghart 9518: sub files_in_path {
                   9519:     my ($user, $path) = @_;
                   9520:     my $filename = $user."savedfiles";
                   9521:     my %return_files;
1.1117    foxr     9522:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 9523:     while (my $line_in = <IN>) {
1.574     banghart 9524:         chomp ($line_in);
                   9525:         my @paths_and_file = split (m!/!, $line_in);
                   9526:         my $file_part = pop (@paths_and_file);
                   9527:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 9528:         $path_part.='/';
                   9529:         my $path_and_file = $path_part.$file_part;
                   9530:         if ($path_part eq $path) {
                   9531:             $return_files{$file_part}= 'selected';
                   9532:         }
                   9533:     }
1.574     banghart 9534:     close (IN);
                   9535:     return (\%return_files);
1.572     banghart 9536: }
                   9537: 
                   9538: # called in portfolio select mode, to show files selected NOT in current directory
                   9539: sub files_not_in_path {
                   9540:     my ($user, $path) = @_;
                   9541:     my $filename = $user."savedfiles";
                   9542:     my @return_files;
                   9543:     my $path_part;
1.1117    foxr     9544:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 9545:     while (my $line = <IN>) {
1.572     banghart 9546:         #ok, I know it's clunky, but I want it to work
1.800     albertel 9547:         my @paths_and_file = split(m|/|, $line);
                   9548:         my $file_part = pop(@paths_and_file);
                   9549:         chomp($file_part);
                   9550:         my $path_part = join('/', @paths_and_file);
1.572     banghart 9551:         $path_part .= '/';
                   9552:         my $path_and_file = $path_part.$file_part;
                   9553:         if ($path_part ne $path) {
1.800     albertel 9554:             push(@return_files, ($path_and_file));
1.572     banghart 9555:         }
                   9556:     }
1.800     albertel 9557:     close(OUT);
1.574     banghart 9558:     return (@return_files);
1.572     banghart 9559: }
                   9560: 
1.745     raeburn  9561: #----------------------------------------------Get portfolio file permissions
1.629     banghart 9562: 
1.745     raeburn  9563: sub get_portfile_permissions {
                   9564:     my ($domain,$user) = @_;
1.613     albertel 9565:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9566:     my ($tmp)=keys(%current_permissions);
                   9567:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9568:     return \%current_permissions;
                   9569: }
                   9570: 
                   9571: #---------------------------------------------Get portfolio file access controls
                   9572: 
1.749     raeburn  9573: sub get_access_controls {
1.745     raeburn  9574:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 9575:     my %access;
                   9576:     my $real_file = $file;
                   9577:     $file =~ s/\.meta$//;
1.745     raeburn  9578:     if (defined($file)) {
1.749     raeburn  9579:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   9580:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 9581:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  9582:             }
                   9583:         }
1.745     raeburn  9584:     } else {
1.749     raeburn  9585:         foreach my $key (keys(%{$current_permissions})) {
                   9586:             if ($key =~ /\0accesscontrol$/) {
                   9587:                 if (defined($group)) {
                   9588:                     if ($key !~ m-^\Q$group\E/-) {
                   9589:                         next;
                   9590:                     }
                   9591:                 }
                   9592:                 my ($fullpath) = split(/\0/,$key);
                   9593:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   9594:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   9595:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   9596:                     }
                   9597:                 }
                   9598:             }
                   9599:         }
                   9600:     }
                   9601:     return %access;
                   9602: }
                   9603: 
                   9604: sub modify_access_controls {
                   9605:     my ($file_name,$changes,$domain,$user)=@_;
                   9606:     my ($outcome,$deloutcome);
                   9607:     my %store_permissions;
                   9608:     my %new_values;
                   9609:     my %new_control;
                   9610:     my %translation;
                   9611:     my @deletions = ();
                   9612:     my $now = time;
                   9613:     if (exists($$changes{'activate'})) {
                   9614:         if (ref($$changes{'activate'}) eq 'HASH') {
                   9615:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   9616:             my $numnew = scalar(@newitems);
                   9617:             for (my $i=0; $i<$numnew; $i++) {
                   9618:                 my $newkey = $newitems[$i];
                   9619:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  9620:                 if ($newkey =~ /^\d+:/) { 
                   9621:                     $newkey =~ s/^(\d+)/$newid/;
                   9622:                     $translation{$1} = $newid;
                   9623:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   9624:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   9625:                     $translation{$1} = $newid;
                   9626:                 }
1.749     raeburn  9627:                 $new_values{$file_name."\0".$newkey} = 
                   9628:                                           $$changes{'activate'}{$newitems[$i]};
                   9629:                 $new_control{$newkey} = $now;
                   9630:             }
                   9631:         }
                   9632:     }
                   9633:     my %todelete;
                   9634:     my %changed_items;
                   9635:     foreach my $action ('delete','update') {
                   9636:         if (exists($$changes{$action})) {
                   9637:             if (ref($$changes{$action}) eq 'HASH') {
                   9638:                 foreach my $key (keys(%{$$changes{$action}})) {
                   9639:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   9640:                     if ($action eq 'delete') { 
                   9641:                         $todelete{$itemnum} = 1;
                   9642:                     } else {
                   9643:                         $changed_items{$itemnum} = $key;
                   9644:                     }
                   9645:                 }
1.745     raeburn  9646:             }
                   9647:         }
1.749     raeburn  9648:     }
                   9649:     # get lock on access controls for file.
                   9650:     my $lockhash = {
                   9651:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   9652:                                                        ':'.$env{'user.domain'},
                   9653:                    }; 
                   9654:     my $tries = 0;
                   9655:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9656:    
1.1172.2.79  raeburn  9657:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  9658:         $tries ++;
1.1172.2.79  raeburn  9659:         sleep(0.1);
1.749     raeburn  9660:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9661:     }
                   9662:     if ($gotlock eq 'ok') {
                   9663:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   9664:         my ($tmp)=keys(%curr_permissions);
                   9665:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   9666:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   9667:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   9668:             if (ref($curr_controls) eq 'HASH') {
                   9669:                 foreach my $control_item (keys(%{$curr_controls})) {
                   9670:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   9671:                     if (defined($todelete{$itemnum})) {
                   9672:                         push(@deletions,$file_name."\0".$control_item);
                   9673:                     } else {
                   9674:                         if (defined($changed_items{$itemnum})) {
                   9675:                             $new_control{$changed_items{$itemnum}} = $now;
                   9676:                             push(@deletions,$file_name."\0".$control_item);
                   9677:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   9678:                         } else {
                   9679:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   9680:                         }
                   9681:                     }
1.745     raeburn  9682:                 }
                   9683:             }
                   9684:         }
1.970     raeburn  9685:         my ($group);
                   9686:         if (&is_course($domain,$user)) {
                   9687:             ($group,my $file) = split(/\//,$file_name,2);
                   9688:         }
1.749     raeburn  9689:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   9690:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   9691:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   9692:         #  remove lock
                   9693:         my @del_lock = ($file_name."\0".'locked_access_records');
                   9694:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  9695:         my $sqlresult =
1.970     raeburn  9696:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  9697:                                     $group);
1.749     raeburn  9698:     } else {
                   9699:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  9700:     }
1.749     raeburn  9701:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  9702: }
                   9703: 
1.827     raeburn  9704: sub make_public_indefinitely {
                   9705:     my ($requrl) = @_;
                   9706:     my $now = time;
                   9707:     my $action = 'activate';
                   9708:     my $aclnum = 0;
                   9709:     if (&is_portfolio_url($requrl)) {
                   9710:         my (undef,$udom,$unum,$file_name,$group) =
                   9711:             &parse_portfolio_url($requrl);
                   9712:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   9713:         my %access_controls = &get_access_controls($current_perms,
                   9714:                                                    $group,$file_name);
                   9715:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   9716:             my ($num,$scope,$end,$start) = 
                   9717:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   9718:             if ($scope eq 'public') {
                   9719:                 if ($start <= $now && $end == 0) {
                   9720:                     $action = 'none';
                   9721:                 } else {
                   9722:                     $action = 'update';
                   9723:                     $aclnum = $num;
                   9724:                 }
                   9725:                 last;
                   9726:             }
                   9727:         }
                   9728:         if ($action eq 'none') {
                   9729:              return 'ok';
                   9730:         } else {
                   9731:             my %changes;
                   9732:             my $newend = 0;
                   9733:             my $newstart = $now;
                   9734:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   9735:             $changes{$action}{$newkey} = {
                   9736:                 type => 'public',
                   9737:                 time => {
                   9738:                     start => $newstart,
                   9739:                     end   => $newend,
                   9740:                 },
                   9741:             };
                   9742:             my ($outcome,$deloutcome,$new_values,$translation) =
                   9743:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   9744:             return $outcome;
                   9745:         }
                   9746:     } else {
                   9747:         return 'invalid';
                   9748:     }
                   9749: }
                   9750: 
1.745     raeburn  9751: #------------------------------------------------------Get Marked as Read Only
                   9752: 
                   9753: sub get_marked_as_readonly {
                   9754:     my ($domain,$user,$what,$group) = @_;
                   9755:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 9756:     my @readonly_files;
1.629     banghart 9757:     my $cmp1=$what;
                   9758:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  9759:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9760:         if (defined($group)) {
                   9761:             if ($file_name !~ m-^\Q$group\E/-) {
                   9762:                 next;
                   9763:             }
                   9764:         }
1.561     banghart 9765:         if (ref($value) eq "ARRAY"){
                   9766:             foreach my $stored_what (@{$value}) {
1.629     banghart 9767:                 my $cmp2=$stored_what;
1.759     albertel 9768:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  9769:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  9770:                 }
1.629     banghart 9771:                 if ($cmp1 eq $cmp2) {
1.561     banghart 9772:                     push(@readonly_files, $file_name);
1.745     raeburn  9773:                     last;
1.563     banghart 9774:                 } elsif (!defined($what)) {
                   9775:                     push(@readonly_files, $file_name);
1.745     raeburn  9776:                     last;
1.561     banghart 9777:                 }
                   9778:             }
1.745     raeburn  9779:         }
1.561     banghart 9780:     }
                   9781:     return @readonly_files;
                   9782: }
1.577     banghart 9783: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 9784: 
1.577     banghart 9785: sub get_marked_as_readonly_hash {
1.745     raeburn  9786:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 9787:     my %readonly_files;
1.745     raeburn  9788:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9789:         if (defined($group)) {
                   9790:             if ($file_name !~ m-^\Q$group\E/-) {
                   9791:                 next;
                   9792:             }
                   9793:         }
1.577     banghart 9794:         if (ref($value) eq "ARRAY"){
                   9795:             foreach my $stored_what (@{$value}) {
1.745     raeburn  9796:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 9797:                     foreach my $lock_descriptor(@{$stored_what}) {
                   9798:                         if ($lock_descriptor eq 'graded') {
                   9799:                             $readonly_files{$file_name} = 'graded';
                   9800:                         } elsif ($lock_descriptor eq 'handback') {
                   9801:                             $readonly_files{$file_name} = 'handback';
                   9802:                         } else {
                   9803:                             if (!exists($readonly_files{$file_name})) {
                   9804:                                 $readonly_files{$file_name} = 'locked';
                   9805:                             }
                   9806:                         }
1.745     raeburn  9807:                     }
1.750     banghart 9808:                 } 
1.577     banghart 9809:             }
                   9810:         } 
                   9811:     }
                   9812:     return %readonly_files;
                   9813: }
1.559     banghart 9814: # ------------------------------------------------------------ Unmark as Read Only
                   9815: 
                   9816: sub unmark_as_readonly {
1.629     banghart 9817:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   9818:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  9819:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 9820:     $file_name = &declutter_portfile($file_name);
1.634     albertel 9821:     my $symb_crs = $what;
                   9822:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  9823:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 9824:     my ($tmp)=keys(%current_permissions);
                   9825:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9826:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 9827:     foreach my $file (@readonly_files) {
1.759     albertel 9828: 	my $clean_file = &declutter_portfile($file);
                   9829: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 9830: 	my $current_locks = $current_permissions{$file};
1.563     banghart 9831:         my @new_locks;
                   9832:         my @del_keys;
                   9833:         if (ref($current_locks) eq "ARRAY"){
                   9834:             foreach my $locker (@{$current_locks}) {
1.632     albertel 9835:                 my $compare=$locker;
1.749     raeburn  9836:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  9837:                     $compare=join('',@{$locker});
1.746     raeburn  9838:                     if ($compare ne $symb_crs) {
                   9839:                         push(@new_locks, $locker);
                   9840:                     }
1.563     banghart 9841:                 }
                   9842:             }
1.650     albertel 9843:             if (scalar(@new_locks) > 0) {
1.563     banghart 9844:                 $current_permissions{$file} = \@new_locks;
                   9845:             } else {
                   9846:                 push(@del_keys, $file);
1.613     albertel 9847:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 9848:                 delete($current_permissions{$file});
1.563     banghart 9849:             }
                   9850:         }
1.561     banghart 9851:     }
1.613     albertel 9852:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9853:     return;
                   9854: }
1.512     banghart 9855: 
1.17      www      9856: # ------------------------------------------------------------ Directory lister
                   9857: 
                   9858: sub dirlist {
1.955     raeburn  9859:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      9860:     $uri=~s/^\///;
                   9861:     $uri=~s/\/$//;
1.253     stredwic 9862:     my ($udom, $uname);
1.955     raeburn  9863:     if ($getuserdir) {
1.253     stredwic 9864:         $udom = $userdomain;
                   9865:         $uname = $username;
1.955     raeburn  9866:     } else {
                   9867:         (undef,$udom,$uname)=split(/\//,$uri);
                   9868:         if(defined($userdomain)) {
                   9869:             $udom = $userdomain;
                   9870:         }
                   9871:         if(defined($username)) {
                   9872:             $uname = $username;
                   9873:         }
1.253     stredwic 9874:     }
1.955     raeburn  9875:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 9876: 
1.955     raeburn  9877:     $dirRoot = $perlvar{'lonDocRoot'};
                   9878:     if (defined($getpropath)) {
                   9879:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 9880:         $dirRoot =~ s/\/$//;
1.955     raeburn  9881:     } elsif (defined($getuserdir)) {
                   9882:         my $subdir=$uname.'__';
                   9883:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   9884:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   9885:                    ."/$udom/$subdir/$uname";
                   9886:     } elsif (defined($alternateRoot)) {
                   9887:         $dirRoot = $alternateRoot;
1.751     banghart 9888:     }
1.253     stredwic 9889: 
                   9890:     if($udom) {
                   9891:         if($uname) {
1.1135    raeburn  9892:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  9893:             if ($uhome eq 'no_host') {
                   9894:                 return ([],'no_host');
                   9895:             }
1.955     raeburn  9896:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  9897:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  9898:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  9899:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9900:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  9901:             } else {
                   9902:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9903:             }
1.605     matthew  9904:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9905:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  9906:                 @listing_results = split(/:/,$listing);
                   9907:             } else {
                   9908:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9909:             }
1.1135    raeburn  9910:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  9911:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9912:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9913:                 return ([],$listing);
                   9914:             } else {
                   9915:                 return (\@listing_results);
1.1135    raeburn  9916:             }
1.955     raeburn  9917:         } elsif(!$alternateRoot) {
1.1136    raeburn  9918:             my (%allusers,%listerror);
1.841     albertel 9919: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  9920:  	    foreach my $tryserver (keys(%servers)) {
                   9921:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   9922:                                   &escape($udom),$tryserver);
                   9923:                 if ($listing eq 'unknown_cmd') {
                   9924: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9925: 				      $udom, $tryserver);
                   9926:                 } else {
                   9927:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9928:                 }
1.841     albertel 9929: 		if ($listing eq 'unknown_cmd') {
                   9930: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9931: 				      $udom, $tryserver);
                   9932: 		    @listing_results = split(/:/,$listing);
                   9933: 		} else {
                   9934: 		    @listing_results =
                   9935: 			map { &unescape($_); } split(/:/,$listing);
                   9936: 		}
1.1136    raeburn  9937:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   9938:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9939:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9940:                     $listerror{$tryserver} = $listing;
                   9941:                 } else {
1.841     albertel 9942: 		    foreach my $line (@listing_results) {
                   9943: 			my ($entry) = split(/&/,$line,2);
                   9944: 			$allusers{$entry} = 1;
                   9945: 		    }
                   9946: 		}
1.253     stredwic 9947:             }
1.1136    raeburn  9948:             my @alluserslist=();
1.800     albertel 9949:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  9950:                 push(@alluserslist,$user.'&user');
1.253     stredwic 9951:             }
1.1172.2.80  raeburn  9952:             if (!%listerror) {
                   9953:                 # no errors
                   9954:                 return (\@alluserslist);
                   9955:             } elsif (scalar(keys(%servers)) == 1) {
                   9956:                 # one library server, one error
                   9957:                 my ($key) = keys(%listerror);
                   9958:                 return (\@alluserslist, $listerror{$key});
                   9959:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   9960:                 # con_lost indicates that we might miss data from at least one
                   9961:                 # library server
                   9962:                 return (\@alluserslist, 'con_lost');
                   9963:             } else {
                   9964:                 # multiple library servers and no con_lost -> data should be
                   9965:                 # complete.
                   9966:                 return (\@alluserslist);
                   9967:             }
                   9968: 
1.253     stredwic 9969:         } else {
1.1136    raeburn  9970:             return ([],'missing username');
1.253     stredwic 9971:         }
1.955     raeburn  9972:     } elsif(!defined($getpropath)) {
1.1136    raeburn  9973:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   9974:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   9975:         return (\@all_domains);
1.955     raeburn  9976:     } else {
1.1136    raeburn  9977:         return ([],'missing domain');
1.275     stredwic 9978:     }
                   9979: }
                   9980: 
                   9981: # --------------------------------------------- GetFileTimestamp
                   9982: # This function utilizes dirlist and returns the date stamp for
                   9983: # when it was last modified.  It will also return an error of -1
                   9984: # if an error occurs
                   9985: 
                   9986: sub GetFileTimestamp {
1.955     raeburn  9987:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 9988:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   9989:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  9990:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   9991:                                     undef,$getuserdir);
                   9992:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9993:         return -1;
                   9994:     }
                   9995:     if (ref($fileref) eq 'ARRAY') {
                   9996:         my @stats = split('&',$fileref->[0]);
1.375     matthew  9997:         # @stats contains first the filename, then the stat output
                   9998:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 9999:     } else {
                   10000:         return -1;
1.253     stredwic 10001:     }
1.26      www      10002: }
                   10003: 
1.712     albertel 10004: sub stat_file {
                   10005:     my ($uri) = @_;
1.787     albertel 10006:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 10007: 
1.955     raeburn  10008:     my ($udom,$uname,$file);
1.712     albertel 10009:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   10010: 	($udom,$uname,$file) =
1.811     albertel 10011: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 10012: 	$file = 'userfiles/'.$file;
                   10013:     }
                   10014:     if ($uri =~ m-^/res/-) {
                   10015: 	($udom,$uname) = 
1.807     albertel 10016: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 10017: 	$file = $uri;
                   10018:     }
                   10019: 
                   10020:     if (!$udom || !$uname || !$file) {
                   10021: 	# unable to handle the uri
                   10022: 	return ();
                   10023:     }
1.956     raeburn  10024:     my $getpropath;
                   10025:     if ($file =~ /^userfiles\//) {
                   10026:         $getpropath = 1;
                   10027:     }
1.1136    raeburn  10028:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   10029:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10030:         return ();
                   10031:     } else {
                   10032:         if (ref($listref) eq 'ARRAY') {
                   10033:             my @stats = split('&',$listref->[0]);
                   10034: 	    shift(@stats); #filename is first
                   10035: 	    return @stats;
                   10036:         }
1.712     albertel 10037:     }
                   10038:     return ();
                   10039: }
                   10040: 
1.26      www      10041: # -------------------------------------------------------- Value of a Condition
                   10042: 
1.713     albertel 10043: # gets the value of a specific preevaluated condition
                   10044: #    stored in the string  $env{user.state.<cid>}
                   10045: # or looks up a condition reference in the bighash and if if hasn't
                   10046: # already been evaluated recurses into docondval to get the value of
                   10047: # the condition, then memoizing it to 
                   10048: #   $env{user.state.<cid>.<condition>}
1.40      www      10049: sub directcondval {
                   10050:     my $number=shift;
1.620     albertel 10051:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 10052: 	&Apache::lonuserstate::evalstate();
                   10053:     }
1.713     albertel 10054:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   10055: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   10056:     } elsif ($number =~ /^_/) {
                   10057: 	my $sub_condition;
                   10058: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10059: 		&GDBM_READER(),0640)) {
                   10060: 	    $sub_condition=$bighash{'conditions'.$number};
                   10061: 	    untie(%bighash);
                   10062: 	}
                   10063: 	my $value = &docondval($sub_condition);
1.949     raeburn  10064: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 10065: 	return $value;
                   10066:     }
1.620     albertel 10067:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   10068:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      10069:     } else {
                   10070:        return 2;
                   10071:     }
                   10072: }
                   10073: 
1.713     albertel 10074: # get the collection of conditions for this resource
1.26      www      10075: sub condval {
                   10076:     my $condidx=shift;
1.54      www      10077:     my $allpathcond='';
1.713     albertel 10078:     foreach my $cond (split(/\|/,$condidx)) {
                   10079: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   10080: 	    $allpathcond.=
                   10081: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   10082: 	}
1.191     harris41 10083:     }
1.54      www      10084:     $allpathcond=~s/\|$//;
1.713     albertel 10085:     return &docondval($allpathcond);
                   10086: }
                   10087: 
                   10088: #evaluates an expression of conditions
                   10089: sub docondval {
                   10090:     my ($allpathcond) = @_;
                   10091:     my $result=0;
                   10092:     if ($env{'request.course.id'}
                   10093: 	&& defined($allpathcond)) {
                   10094: 	my $operand='|';
                   10095: 	my @stack;
                   10096: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   10097: 	    if ($chunk eq '(') {
                   10098: 		push @stack,($operand,$result);
                   10099: 	    } elsif ($chunk eq ')') {
                   10100: 		my $before=pop @stack;
                   10101: 		if (pop @stack eq '&') {
                   10102: 		    $result=$result>$before?$before:$result;
                   10103: 		} else {
                   10104: 		    $result=$result>$before?$result:$before;
                   10105: 		}
                   10106: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   10107: 		$operand=$chunk;
                   10108: 	    } else {
                   10109: 		my $new=directcondval($chunk);
                   10110: 		if ($operand eq '&') {
                   10111: 		    $result=$result>$new?$new:$result;
                   10112: 		} else {
                   10113: 		    $result=$result>$new?$result:$new;
                   10114: 		}
                   10115: 	    }
                   10116: 	}
1.26      www      10117:     }
                   10118:     return $result;
1.421     albertel 10119: }
                   10120: 
                   10121: # ---------------------------------------------------- Devalidate courseresdata
                   10122: 
                   10123: sub devalidatecourseresdata {
                   10124:     my ($coursenum,$coursedomain)=@_;
                   10125:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10126:     &devalidate_cache_new('courseres',$hashid);
1.28      www      10127: }
                   10128: 
1.763     www      10129: 
1.200     www      10130: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     10131: #
                   10132: #  Parameters:
                   10133: #      $coursenum    - Number of the course.
                   10134: #      $coursedomain - Domain at which the course was created.
                   10135: #  Returns:
                   10136: #     A hash of the course parameters along (I think) with timestamps
                   10137: #     and version info.
1.877     foxr     10138: 
1.624     albertel 10139: sub get_courseresdata {
                   10140:     my ($coursenum,$coursedomain)=@_;
1.200     www      10141:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   10142:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10143:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 10144:     my %dumpreply;
1.417     albertel 10145:     unless (defined($cached)) {
1.624     albertel 10146: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 10147: 	$result=\%dumpreply;
1.251     albertel 10148: 	my ($tmp) = keys(%dumpreply);
                   10149: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 10150: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 10151: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   10152: 	    return $tmp;
1.416     albertel 10153: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 10154: 	    $result=undef;
1.599     albertel 10155: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 10156: 	}
                   10157:     }
1.624     albertel 10158:     return $result;
                   10159: }
                   10160: 
1.633     albertel 10161: sub devalidateuserresdata {
                   10162:     my ($uname,$udom)=@_;
                   10163:     my $hashid="$udom:$uname";
                   10164:     &devalidate_cache_new('userres',$hashid);
                   10165: }
                   10166: 
1.624     albertel 10167: sub get_userresdata {
                   10168:     my ($uname,$udom)=@_;
                   10169:     #most student don\'t have any data set, check if there is some data
                   10170:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   10171: 
                   10172:     my $hashid="$udom:$uname";
                   10173:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   10174:     if (!defined($cached)) {
                   10175: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   10176: 	$result=\%resourcedata;
                   10177: 	&do_cache_new('userres',$hashid,$result,600);
                   10178:     }
                   10179:     my ($tmp)=keys(%$result);
                   10180:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   10181: 	return $result;
                   10182:     }
                   10183:     #error 2 occurs when the .db doesn't exist
                   10184:     if ($tmp!~/error: 2 /) {
1.1172.2.71  raeburn  10185:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   10186: 	    &logthis("<font color=\"blue\">WARNING:".
                   10187: 		     " Trying to get resource data for ".
                   10188: 		     $uname." at ".$udom.": ".
                   10189: 		     $tmp."</font>");
                   10190:         }
1.624     albertel 10191:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 10192: 	#&EXT_cache_set($udom,$uname);
                   10193: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 10194: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 10195:     }
                   10196:     return $tmp;
                   10197: }
1.879     foxr     10198: #----------------------------------------------- resdata - return resource data
                   10199: #  Purpose:
                   10200: #    Return resource data for either users or for a course.
                   10201: #  Parameters:
                   10202: #     $name      - Course/user name.
                   10203: #     $domain    - Name of the domain the user/course is registered on.
                   10204: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   10205: #     @which     - Array of names of resources desired.
                   10206: #  Returns:
                   10207: #     The value of the first reasource in @which that is found in the
                   10208: #     resource hash.
                   10209: #  Exceptional Conditions:
                   10210: #     If the $type passed in is not valid (not the string 'course' or 
                   10211: #     'user', an undefined  reference is returned.
                   10212: #     If none of the resources are found, an undef is returned
1.624     albertel 10213: sub resdata {
                   10214:     my ($name,$domain,$type,@which)=@_;
                   10215:     my $result;
                   10216:     if ($type eq 'course') {
                   10217: 	$result=&get_courseresdata($name,$domain);
                   10218:     } elsif ($type eq 'user') {
                   10219: 	$result=&get_userresdata($name,$domain);
                   10220:     }
                   10221:     if (!ref($result)) { return $result; }    
1.251     albertel 10222:     foreach my $item (@which) {
1.927     albertel 10223: 	if (defined($result->{$item->[0]})) {
                   10224: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 10225: 	}
1.250     albertel 10226:     }
1.291     albertel 10227:     return undef;
1.200     www      10228: }
                   10229: 
1.1172.2.31  raeburn  10230: sub get_numsuppfiles {
                   10231:     my ($cnum,$cdom,$ignorecache)=@_;
                   10232:     my $hashid=$cnum.':'.$cdom;
                   10233:     my ($suppcount,$cached);
                   10234:     unless ($ignorecache) {
                   10235:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   10236:     }
                   10237:     unless (defined($cached)) {
                   10238:         my $chome=&homeserver($cnum,$cdom);
                   10239:         unless ($chome eq 'no_host') {
                   10240:             ($suppcount,my $errors) = (0,0);
                   10241:             my $suppmap = 'supplemental.sequence';
                   10242:             ($suppcount,$errors) =
                   10243:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   10244:         }
                   10245:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   10246:     }
                   10247:     return $suppcount;
                   10248: }
                   10249: 
1.379     matthew  10250: #
                   10251: # EXT resource caching routines
                   10252: #
                   10253: 
                   10254: sub clear_EXT_cache_status {
1.383     albertel 10255:     &delenv('cache.EXT.');
1.379     matthew  10256: }
                   10257: 
                   10258: sub EXT_cache_status {
                   10259:     my ($target_domain,$target_user) = @_;
1.383     albertel 10260:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 10261:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  10262:         # We know already the user has no data
                   10263:         return 1;
                   10264:     } else {
                   10265:         return 0;
                   10266:     }
                   10267: }
                   10268: 
                   10269: sub EXT_cache_set {
                   10270:     my ($target_domain,$target_user) = @_;
1.383     albertel 10271:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  10272:     #&appenv({$cachename => time});
1.379     matthew  10273: }
                   10274: 
1.28      www      10275: # --------------------------------------------------------- Value of a Variable
1.58      www      10276: sub EXT {
1.715     albertel 10277: 
1.1172.2.28  raeburn  10278:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      10279:     unless ($varname) { return ''; }
1.218     albertel 10280:     #get real user name/domain, courseid and symb
                   10281:     my $courseid;
1.359     albertel 10282:     my $publicuser;
1.427     www      10283:     if ($symbparm) {
                   10284: 	$symbparm=&get_symb_from_alias($symbparm);
                   10285:     }
1.218     albertel 10286:     if (!($uname && $udom)) {
1.790     albertel 10287:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 10288:       if (!$symbparm) {	$symbparm=$cursymb; }
                   10289:     } else {
1.620     albertel 10290: 	$courseid=$env{'request.course.id'};
1.218     albertel 10291:     }
1.48      www      10292:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   10293:     my $rest;
1.320     albertel 10294:     if (defined($therest[0])) {
1.48      www      10295:        $rest=join('.',@therest);
                   10296:     } else {
                   10297:        $rest='';
                   10298:     }
1.320     albertel 10299: 
1.57      www      10300:     my $qualifierrest=$qualifier;
                   10301:     if ($rest) { $qualifierrest.='.'.$rest; }
                   10302:     my $spacequalifierrest=$space;
                   10303:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      10304:     if ($realm eq 'user') {
1.48      www      10305: # --------------------------------------------------------------- user.resource
                   10306: 	if ($space eq 'resource') {
1.651     albertel 10307: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   10308: 		  || defined($Apache::lonhomework::parsing_a_task))
                   10309: 		 &&
1.744     albertel 10310: 		 ($symbparm eq &symbread()) ) {	
                   10311: 		# if we are in the middle of processing the resource the
                   10312: 		# get the value we are planning on committing
                   10313:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   10314:                     return $Apache::lonhomework::results{$qualifierrest};
                   10315:                 } else {
                   10316:                     return $Apache::lonhomework::history{$qualifierrest};
                   10317:                 }
1.335     albertel 10318: 	    } else {
1.359     albertel 10319: 		my %restored;
1.620     albertel 10320: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 10321: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   10322: 		} else {
                   10323: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   10324: 		}
1.335     albertel 10325: 		return $restored{$qualifierrest};
                   10326: 	    }
1.48      www      10327: # ----------------------------------------------------------------- user.access
                   10328:         } elsif ($space eq 'access') {
1.218     albertel 10329: 	    # FIXME - not supporting calls for a specific user
1.48      www      10330:             return &allowed($qualifier,$rest);
                   10331: # ------------------------------------------ user.preferences, user.environment
                   10332:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 10333: 	    if (($uname eq $env{'user.name'}) &&
                   10334: 		($udom eq $env{'user.domain'})) {
                   10335: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 10336: 	    } else {
1.359     albertel 10337: 		my %returnhash;
                   10338: 		if (!$publicuser) {
                   10339: 		    %returnhash=&userenvironment($udom,$uname,
                   10340: 						 $qualifierrest);
                   10341: 		}
1.218     albertel 10342: 		return $returnhash{$qualifierrest};
                   10343: 	    }
1.48      www      10344: # ----------------------------------------------------------------- user.course
                   10345:         } elsif ($space eq 'course') {
1.218     albertel 10346: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10347:             return $env{join('.',('request.course',$qualifier))};
1.48      www      10348: # ------------------------------------------------------------------- user.role
                   10349:         } elsif ($space eq 'role') {
1.218     albertel 10350: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10351:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      10352:             if ($qualifier eq 'value') {
                   10353: 		return $role;
                   10354:             } elsif ($qualifier eq 'extent') {
                   10355:                 return $where;
                   10356:             }
                   10357: # ----------------------------------------------------------------- user.domain
                   10358:         } elsif ($space eq 'domain') {
1.218     albertel 10359:             return $udom;
1.48      www      10360: # ------------------------------------------------------------------- user.name
                   10361:         } elsif ($space eq 'name') {
1.218     albertel 10362:             return $uname;
1.48      www      10363: # ---------------------------------------------------- Any other user namespace
1.29      www      10364:         } else {
1.359     albertel 10365: 	    my %reply;
                   10366: 	    if (!$publicuser) {
                   10367: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   10368: 	    }
                   10369: 	    return $reply{$qualifierrest};
1.48      www      10370:         }
1.236     www      10371:     } elsif ($realm eq 'query') {
                   10372: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 10373:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   10374: 						[$spacequalifierrest]);
1.620     albertel 10375: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      10376:    } elsif ($realm eq 'request') {
1.48      www      10377: # ------------------------------------------------------------- request.browser
                   10378:         if ($space eq 'browser') {
1.1145    bisitz   10379:             return $env{'browser.'.$qualifier};
1.57      www      10380: # ------------------------------------------------------------ request.filename
                   10381:         } else {
1.620     albertel 10382:             return $env{'request.'.$spacequalifierrest};
1.29      www      10383:         }
1.28      www      10384:     } elsif ($realm eq 'course') {
1.48      www      10385: # ---------------------------------------------------------- course.description
1.620     albertel 10386:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      10387:     } elsif ($realm eq 'resource') {
1.165     www      10388: 
1.620     albertel 10389: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 10390: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   10391: 	}
1.693     albertel 10392: 
1.1172.2.30  raeburn  10393:         if ($qualifier eq '') {
                   10394: 	    if ($space eq 'title') {
                   10395: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   10396: 	        return &gettitle($symbparm);
                   10397: 	    }
1.693     albertel 10398: 	
1.1172.2.30  raeburn  10399: 	    if ($space eq 'map') {
                   10400: 	        my ($map) = &decode_symb($symbparm);
                   10401: 	        return &symbread($map);
                   10402: 	    }
                   10403:             if ($space eq 'maptitle') {
                   10404:                 my ($map) = &decode_symb($symbparm);
                   10405:                 return &gettitle($map);
                   10406:             }
                   10407: 	    if ($space eq 'filename') {
                   10408: 	        if ($symbparm) {
                   10409: 		    return &clutter((&decode_symb($symbparm))[2]);
                   10410: 	        }
                   10411: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 10412: 	    }
1.1172.2.30  raeburn  10413: 
                   10414:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   10415:                 if ($space eq 'visibleparts') {
                   10416:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   10417:                     my $item;
                   10418:                     if (ref($navmap)) {
                   10419:                         my $res = $navmap->getBySymb($symbparm);
                   10420:                         my $parts = $res->parts();
                   10421:                         if (ref($parts) eq 'ARRAY') {
                   10422:                             $item = join(',',@{$parts});
                   10423:                         }
                   10424:                         undef($navmap);
                   10425:                     }
                   10426:                     return $item;
                   10427:                 }
                   10428:             }
                   10429:         }
1.693     albertel 10430: 
                   10431: 	my ($section, $group, @groups);
1.593     albertel 10432: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  10433:         if (($courseid eq '') && ($cid)) {
                   10434:             $courseid = $cid;
                   10435:         }
                   10436: 	if (($symbparm && $courseid) && 
                   10437: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      10438: 
1.218     albertel 10439: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      10440: 
1.60      www      10441: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 10442: 	    my $symbp=$symbparm;
1.735     albertel 10443: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 10444: 
                   10445: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   10446: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   10447: 
1.620     albertel 10448: 	    if (($env{'user.name'} eq $uname) &&
                   10449: 		($env{'user.domain'} eq $udom)) {
                   10450: 		$section=$env{'request.course.sec'};
1.733     raeburn  10451:                 @groups = split(/:/,$env{'request.course.groups'});  
                   10452:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 10453: 	    } else {
1.539     albertel 10454: 		if (! defined($usection)) {
1.551     albertel 10455: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 10456: 		} else {
                   10457: 		    $section = $usection;
                   10458: 		}
1.733     raeburn  10459:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 10460: 	    }
                   10461: 
                   10462: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   10463: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   10464: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   10465: 
1.593     albertel 10466: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 10467: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 10468: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      10469: 
1.60      www      10470: # ----------------------------------------------------------- first, check user
1.624     albertel 10471: 
                   10472: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 10473: 				       ([$courselevelr,'resource'],
                   10474: 					[$courselevelm,'map'     ],
                   10475: 					[$courselevel, 'course'  ]));
1.931     albertel 10476: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      10477: 
1.594     albertel 10478: # ------------------------------------------------ second, check some of course
1.684     raeburn  10479:             my $coursereply;
1.691     raeburn  10480:             if (@groups > 0) {
                   10481:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   10482:                                        $mapparm,$spacequalifierrest);
1.927     albertel 10483:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  10484:             }
1.96      www      10485: 
1.684     raeburn  10486: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 10487: 				  $env{'course.'.$courseid.'.domain'},
                   10488: 				  'course',
                   10489: 				  ([$seclevelr,   'resource'],
                   10490: 				   [$seclevelm,   'map'     ],
                   10491: 				   [$seclevel,    'course'  ],
                   10492: 				   [$courselevelr,'resource']));
                   10493: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      10494: 
1.60      www      10495: # ------------------------------------------------------ third, check map parms
1.218     albertel 10496: 	    my %parmhash=();
                   10497: 	    my $thisparm='';
                   10498: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 10499: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 10500: 		    &GDBM_READER(),0640)) {
1.218     albertel 10501: 		$thisparm=$parmhash{$symbparm};
                   10502: 		untie(%parmhash);
                   10503: 	    }
1.927     albertel 10504: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 10505: 	}
1.594     albertel 10506: # ------------------------------------------ fourth, look in resource metadata
1.71      www      10507: 
1.218     albertel 10508: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 10509: 	my $filename;
                   10510: 	if (!$symbparm) { $symbparm=&symbread(); }
                   10511: 	if ($symbparm) {
1.409     www      10512: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 10513: 	} else {
1.620     albertel 10514: 	    $filename=$env{'request.filename'};
1.282     albertel 10515: 	}
                   10516: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 10517: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 10518: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 10519: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      10520: 
1.927     albertel 10521: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 10522: 	if ($symbparm && defined($courseid) && 
1.620     albertel 10523: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 10524: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   10525: 				     $env{'course.'.$courseid.'.domain'},
                   10526: 				     'course',
1.927     albertel 10527: 				     ([$courselevelm,'map'   ],
                   10528: 				      [$courselevel, 'course']));
                   10529: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 10530: 	}
1.145     www      10531: # ------------------------------------------------------------------ Cascade up
1.218     albertel 10532: 	unless ($space eq '0') {
1.336     albertel 10533: 	    my @parts=split(/_/,$space);
                   10534: 	    my $id=pop(@parts);
                   10535: 	    my $part=join('_',@parts);
                   10536: 	    if ($part eq '') { $part='0'; }
1.927     albertel 10537: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 10538: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  10539: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 10540: 	}
1.395     albertel 10541: 	if ($recurse) { return undef; }
                   10542: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 10543: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      10544: # ---------------------------------------------------- Any other user namespace
                   10545:     } elsif ($realm eq 'environment') {
                   10546: # ----------------------------------------------------------------- environment
1.620     albertel 10547: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   10548: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 10549: 	} else {
1.770     albertel 10550: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   10551: 		return '';
                   10552: 	    }
1.219     albertel 10553: 	    my %returnhash=&userenvironment($udom,$uname,
                   10554: 					    $spacequalifierrest);
                   10555: 	    return $returnhash{$spacequalifierrest};
                   10556: 	}
1.28      www      10557:     } elsif ($realm eq 'system') {
1.48      www      10558: # ----------------------------------------------------------------- system.time
                   10559: 	if ($space eq 'time') {
                   10560: 	    return time;
                   10561:         }
1.696     albertel 10562:     } elsif ($realm eq 'server') {
                   10563: # ----------------------------------------------------------------- system.time
                   10564: 	if ($space eq 'name') {
                   10565: 	    return $ENV{'SERVER_NAME'};
                   10566:         }
1.28      www      10567:     }
1.48      www      10568:     return '';
1.61      www      10569: }
                   10570: 
1.927     albertel 10571: sub get_reply {
                   10572:     my ($reply_value) = @_;
1.940     raeburn  10573:     if (ref($reply_value) eq 'ARRAY') {
                   10574:         if (wantarray) {
                   10575: 	    return @$reply_value;
                   10576:         }
                   10577:         return $reply_value->[0];
                   10578:     } else {
                   10579:         return $reply_value;
1.927     albertel 10580:     }
                   10581: }
                   10582: 
1.691     raeburn  10583: sub check_group_parms {
                   10584:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   10585:     my @groupitems = ();
                   10586:     my $resultitem;
1.927     albertel 10587:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  10588:     foreach my $group (@{$groups}) {
                   10589:         foreach my $level (@levels) {
1.927     albertel 10590:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   10591:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  10592:         }
                   10593:     }
                   10594:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   10595:                             $env{'course.'.$courseid.'.domain'},
                   10596:                                      'course',@groupitems);
                   10597:     return $coursereply;
                   10598: }
                   10599: 
                   10600: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  10601:     my ($courseid,@groups) = @_;
                   10602:     @groups = sort(@groups);
1.691     raeburn  10603:     return @groups;
                   10604: }
                   10605: 
1.395     albertel 10606: sub packages_tab_default {
                   10607:     my ($uri,$varname)=@_;
                   10608:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 10609: 
                   10610:     my (@extension,@specifics,$do_default);
                   10611:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 10612: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 10613: 	if ($pack_type eq 'default') {
                   10614: 	    $do_default=1;
                   10615: 	} elsif ($pack_type eq 'extension') {
                   10616: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 10617: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 10618: 	    # only look at packages defaults for packages that this id is
1.738     albertel 10619: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   10620: 	}
                   10621:     }
                   10622:     # first look for a package that matches the requested part id
                   10623:     foreach my $package (@specifics) {
                   10624: 	my (undef,$pack_type,$pack_part)=@{$package};
                   10625: 	next if ($pack_part ne $part);
                   10626: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10627: 	    return $packagetab{"$pack_type&$name&default"};
                   10628: 	}
                   10629:     }
                   10630:     # look for any possible matching non extension_ package
                   10631:     foreach my $package (@specifics) {
                   10632: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 10633: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10634: 	    return $packagetab{"$pack_type&$name&default"};
                   10635: 	}
1.585     albertel 10636: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 10637: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   10638: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 10639: 	}
                   10640:     }
1.738     albertel 10641:     # look for any posible extension_ match
                   10642:     foreach my $package (@extension) {
                   10643: 	my ($package,$pack_type)=@{$package};
                   10644: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10645: 	    return $packagetab{"$pack_type&$name&default"};
                   10646: 	}
                   10647: 	if (defined($packagetab{$package."&$name&default"})) {
                   10648: 	    return $packagetab{$package."&$name&default"};
                   10649: 	}
                   10650:     }
                   10651:     # look for a global default setting
                   10652:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   10653: 	return $packagetab{"default&$name&default"};
                   10654:     }
1.395     albertel 10655:     return undef;
                   10656: }
                   10657: 
1.334     albertel 10658: sub add_prefix_and_part {
                   10659:     my ($prefix,$part)=@_;
                   10660:     my $keyroot;
                   10661:     if (defined($prefix) && $prefix !~ /^__/) {
                   10662: 	# prefix that has a part already
                   10663: 	$keyroot=$prefix;
                   10664:     } elsif (defined($prefix)) {
                   10665: 	# prefix that is missing a part
                   10666: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   10667:     } else {
                   10668: 	# no prefix at all
                   10669: 	if (defined($part)) { $keyroot='_'.$part; }
                   10670:     }
                   10671:     return $keyroot;
                   10672: }
                   10673: 
1.71      www      10674: # ---------------------------------------------------------------- Get metadata
                   10675: 
1.599     albertel 10676: my %metaentry;
1.1070    www      10677: my %importedpartids;
1.71      www      10678: sub metadata {
1.176     www      10679:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      10680:     $uri=&declutter($uri);
1.288     albertel 10681:     # if it is a non metadata possible uri return quickly
1.529     albertel 10682:     if (($uri eq '') || 
                   10683: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.20  raeburn  10684: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108    raeburn  10685:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 10686: 	return undef;
                   10687:     }
1.1172.2.49  raeburn  10688:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 10689: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 10690: 	return undef;
1.288     albertel 10691:     }
1.73      www      10692:     my $filename=$uri;
                   10693:     $uri=~s/\.meta$//;
1.172     www      10694: #
                   10695: # Is the metadata already cached?
1.177     www      10696: # Look at timestamp of caching
1.172     www      10697: # Everything is cached by the main uri, libraries are never directly cached
                   10698: #
1.428     albertel 10699:     if (!defined($liburi)) {
1.599     albertel 10700: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 10701: 	if (defined($cached)) { return $result->{':'.$what}; }
                   10702:     }
                   10703:     {
1.1069    www      10704: # Imported parts would go here
1.1070    www      10705:         my %importedids=();
                   10706:         my @origfileimportpartids=();
1.1069    www      10707:         my $importedparts=0;
1.172     www      10708: #
                   10709: # Is this a recursive call for a library?
                   10710: #
1.599     albertel 10711: #	if (! exists($metacache{$uri})) {
                   10712: #	    $metacache{$uri}={};
                   10713: #	}
1.924     albertel 10714: 	my $cachetime = 60*60;
1.171     www      10715:         if ($liburi) {
                   10716: 	    $liburi=&declutter($liburi);
                   10717:             $filename=$liburi;
1.401     bowersj2 10718:         } else {
1.599     albertel 10719: 	    &devalidate_cache_new('meta',$uri);
                   10720: 	    undef(%metaentry);
1.401     bowersj2 10721: 	}
1.140     www      10722:         my %metathesekeys=();
1.73      www      10723:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 10724: 	my $metastring;
1.1140    www      10725: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 10726: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 10727: 	    $metastring = 
1.929     albertel 10728: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 10729: 					  ('grade_target' => 'meta'));
                   10730: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  10731: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   10732:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 10733: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 10734: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 10735: 	    $metastring=&getfile($file);
1.489     albertel 10736: 	}
1.208     albertel 10737:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      10738:         my $token;
1.140     www      10739:         undef %metathesekeys;
1.71      www      10740:         while ($token=$parser->get_token) {
1.339     albertel 10741: 	    if ($token->[0] eq 'S') {
                   10742: 		if (defined($token->[2]->{'package'})) {
1.172     www      10743: #
                   10744: # This is a package - get package info
                   10745: #
1.339     albertel 10746: 		    my $package=$token->[2]->{'package'};
                   10747: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10748: 		    if (defined($token->[2]->{'id'})) { 
                   10749: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   10750: 		    }
1.599     albertel 10751: 		    if ($metaentry{':packages'}) {
                   10752: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 10753: 		    } else {
1.599     albertel 10754: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 10755: 		    }
1.736     albertel 10756: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 10757: 			my $part=$keyroot;
                   10758: 			$part=~s/^\_//;
1.736     albertel 10759: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   10760: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   10761: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 10762: 			    # ignore package.tab specified default values
                   10763:                             # here &package_tab_default() will fetch those
                   10764: 			    if ($subp eq 'default') { next; }
1.736     albertel 10765: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 10766: 			    my $unikey;
                   10767: 			    if ($pack =~ /_0$/) {
                   10768: 				$unikey='parameter_0_'.$name;
                   10769: 				$part=0;
                   10770: 			    } else {
                   10771: 				$unikey='parameter'.$keyroot.'_'.$name;
                   10772: 			    }
1.339     albertel 10773: 			    if ($subp eq 'display') {
                   10774: 				$value.=' [Part: '.$part.']';
                   10775: 			    }
1.599     albertel 10776: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 10777: 			    $metathesekeys{$unikey}=1;
1.599     albertel 10778: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10779: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 10780: 			    }
1.599     albertel 10781: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   10782: 				$metaentry{':'.$unikey}=
                   10783: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 10784: 			    }
1.339     albertel 10785: 			}
                   10786: 		    }
                   10787: 		} else {
1.172     www      10788: #
                   10789: # This is not a package - some other kind of start tag
1.339     albertel 10790: #
                   10791: 		    my $entry=$token->[1];
1.1068    www      10792: 		    my $unikey='';
1.175     www      10793: 
1.339     albertel 10794: 		    if ($entry eq 'import') {
1.175     www      10795: #
                   10796: # Importing a library here
1.339     albertel 10797: #
1.1067    www      10798:                         my $location=$parser->get_text('/import');
                   10799:                         my $dir=$filename;
                   10800:                         $dir=~s|[^/]*$||;
                   10801:                         $location=&filelocation($dir,$location);
1.1069    www      10802:                        
1.1068    www      10803:                         my $importmode=$token->[2]->{'importmode'};
                   10804:                         if ($importmode eq 'problem') {
1.1069    www      10805: # Import as problem/response
1.1068    www      10806:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10807:                         } elsif ($importmode eq 'part') {
                   10808: # Import as part(s)
1.1069    www      10809:                            $importedparts=1;
                   10810: # We need to get the original file and the imported file to get the part order correct
                   10811: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   10812: # Load and inspect original file
1.1070    www      10813:                            if ($#origfileimportpartids<0) {
                   10814:                               undef(%importedpartids);
                   10815:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   10816:                               my $origfile=&getfile($origfilelocation);
                   10817:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10818:                            }
                   10819: 
1.1069    www      10820: # Load and inspect imported file
                   10821:                            my $impfile=&getfile($location);
                   10822:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10823:                            if ($#impfilepartids>=0) {
                   10824: # This problem had parts
1.1070    www      10825:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      10826:                            } else {
                   10827: # Importing by turning a single problem into a problem part
                   10828: # It gets the import-tags ID as part-ID
                   10829:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      10830:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      10831:                            }
1.1068    www      10832:                         } else {
                   10833: # Normal import
                   10834:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10835:                            if (defined($token->[2]->{'id'})) {
                   10836:                               $unikey.='_'.$token->[2]->{'id'};
                   10837:                            }
1.1067    www      10838:                         }
                   10839: 
1.339     albertel 10840: 			if ($depthcount<20) {
1.736     albertel 10841: 			    my $metadata = 
                   10842: 				&metadata($uri,'keys', $location,$unikey,
                   10843: 					  $depthcount+1);
                   10844: 			    foreach my $meta (split(',',$metadata)) {
                   10845: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   10846: 				$metathesekeys{$meta}=1;
1.339     albertel 10847: 			    }
1.1068    www      10848: 			
                   10849:                         }
1.1067    www      10850: 		    } else {
                   10851: #
                   10852: # Not importing, some other kind of non-package, non-library start tag
                   10853: # 
                   10854:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10855:                         if (defined($token->[2]->{'id'})) {
                   10856:                             $unikey.='_'.$token->[2]->{'id'};
                   10857:                         }
1.339     albertel 10858: 			if (defined($token->[2]->{'name'})) { 
                   10859: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   10860: 			}
                   10861: 			$metathesekeys{$unikey}=1;
1.736     albertel 10862: 			foreach my $param (@{$token->[3]}) {
                   10863: 			    $metaentry{':'.$unikey.'.'.$param} =
                   10864: 				$token->[2]->{$param};
1.339     albertel 10865: 			}
                   10866: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 10867: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 10868: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   10869: 		 # only ws inside the tag, and not in default, so use default
                   10870: 		 # as value
1.599     albertel 10871: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 10872: 			} elsif ( $internaltext =~ /\S/ ) {
                   10873: 		  # something interesting inside the tag
                   10874: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 10875: 			} else {
1.908     albertel 10876: 		  # no interesting values, don't set a default
1.339     albertel 10877: 			}
1.172     www      10878: # end of not-a-package not-a-library import
1.339     albertel 10879: 		    }
1.172     www      10880: # end of not-a-package start tag
1.339     albertel 10881: 		}
1.172     www      10882: # the next is the end of "start tag"
1.339     albertel 10883: 	    }
                   10884: 	}
1.483     albertel 10885: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 10886: 	$extension = lc($extension);
                   10887: 	if ($extension eq 'htm') { $extension='html'; }
                   10888: 
1.737     albertel 10889: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 10890: 	    #no specific packages #how's our extension
                   10891: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 10892: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 10893: 					 \%metathesekeys);
                   10894: 	}
1.883     albertel 10895: 
                   10896: 	if (!exists($metaentry{':packages'})
                   10897: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 10898: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 10899: 		#no specific packages well let's get default then
                   10900: 		if ($key!~/^default&/) { next; }
1.488     albertel 10901: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 10902: 					     \%metathesekeys);
                   10903: 	    }
                   10904: 	}
1.338     www      10905: # are there custom rights to evaluate
1.599     albertel 10906: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 10907: 
1.338     www      10908:     #
                   10909:     # Importing a rights file here
1.339     albertel 10910:     #
                   10911: 	    unless ($depthcount) {
1.599     albertel 10912: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 10913: 		my $dir=$filename;
                   10914: 		$dir=~s|[^/]*$||;
                   10915: 		$location=&filelocation($dir,$location);
1.736     albertel 10916: 		my $rights_metadata =
                   10917: 		    &metadata($uri,'keys',$location,'_rights',
                   10918: 			      $depthcount+1);
                   10919: 		foreach my $rights (split(',',$rights_metadata)) {
                   10920: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   10921: 		    $metathesekeys{$rights}=1;
1.339     albertel 10922: 		}
                   10923: 	    }
                   10924: 	}
1.737     albertel 10925: 	# uniqifiy package listing
                   10926: 	my %seen;
                   10927: 	my @uniq_packages =
                   10928: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   10929: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   10930: 
1.1070    www      10931:         if ($importedparts) {
                   10932: # We had imported parts and need to rebuild partorder
                   10933:            $metaentry{':partorder'}='';
                   10934:            $metathesekeys{'partorder'}=1;
                   10935:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   10936:                if ($origfileimportpartids[$index] eq 'part') {
                   10937: # original part, part of the problem
                   10938:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   10939:                } else {
                   10940: # we have imported parts at this position
                   10941:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   10942:                }
                   10943:            }
                   10944:            $metaentry{':partorder'}=~s/^\,//;
                   10945:         }
                   10946: 
1.737     albertel 10947: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 10948: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58  raeburn  10949: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 10950: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      10951: # this is the end of "was not already recently cached
1.71      www      10952:     }
1.599     albertel 10953:     return $metaentry{':'.$what};
1.261     albertel 10954: }
                   10955: 
1.488     albertel 10956: sub metadata_create_package_def {
1.483     albertel 10957:     my ($uri,$key,$package,$metathesekeys)=@_;
                   10958:     my ($pack,$name,$subp)=split(/\&/,$key);
                   10959:     if ($subp eq 'default') { next; }
                   10960:     
1.599     albertel 10961:     if (defined($metaentry{':packages'})) {
                   10962: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 10963:     } else {
1.599     albertel 10964: 	$metaentry{':packages'}=$package;
1.483     albertel 10965:     }
                   10966:     my $value=$packagetab{$key};
                   10967:     my $unikey;
                   10968:     $unikey='parameter_0_'.$name;
1.599     albertel 10969:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 10970:     $$metathesekeys{$unikey}=1;
1.599     albertel 10971:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10972: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 10973:     }
1.599     albertel 10974:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   10975: 	$metaentry{':'.$unikey}=
                   10976: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 10977:     }
                   10978: }
                   10979: 
1.261     albertel 10980: sub metadata_generate_part0 {
                   10981:     my ($metadata,$metacache,$uri) = @_;
                   10982:     my %allnames;
1.737     albertel 10983:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 10984: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 10985: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   10986: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 10987: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 10988: 	    $allnames{$name}=$part;
                   10989: 	  }
                   10990: 	}
                   10991:     }
                   10992:     foreach my $name (keys(%allnames)) {
                   10993:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 10994:       my $key=":parameter_0_$name";
1.261     albertel 10995:       $$metacache{"$key.part"}='0';
                   10996:       $$metacache{"$key.name"}=$name;
1.428     albertel 10997:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 10998: 					   $allnames{$name}.'_'.$name.
                   10999: 					   '.type'};
1.428     albertel 11000:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 11001: 			     '.display'};
1.644     www      11002:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 11003:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 11004:       $$metacache{"$key.display"}=$olddis;
                   11005:     }
1.71      www      11006: }
                   11007: 
1.764     albertel 11008: # ------------------------------------------------------ Devalidate title cache
                   11009: 
                   11010: sub devalidate_title_cache {
                   11011:     my ($url)=@_;
                   11012:     if (!$env{'request.course.id'}) { return; }
                   11013:     my $symb=&symbread($url);
                   11014:     if (!$symb) { return; }
                   11015:     my $key=$env{'request.course.id'}."\0".$symb;
                   11016:     &devalidate_cache_new('title',$key);
                   11017: }
                   11018: 
1.1014    droeschl 11019: # ------------------------------------------------- Get the title of a course
                   11020: 
                   11021: sub current_course_title {
                   11022:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   11023: }
1.301     www      11024: # ------------------------------------------------- Get the title of a resource
                   11025: 
                   11026: sub gettitle {
                   11027:     my $urlsymb=shift;
                   11028:     my $symb=&symbread($urlsymb);
1.534     albertel 11029:     if ($symb) {
1.620     albertel 11030: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 11031: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 11032: 	if (defined($cached)) { 
                   11033: 	    return $result;
                   11034: 	}
1.534     albertel 11035: 	my ($map,$resid,$url)=&decode_symb($symb);
                   11036: 	my $title='';
1.907     albertel 11037: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   11038: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   11039: 	} else {
                   11040: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11041: 		    &GDBM_READER(),0640)) {
                   11042: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   11043: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   11044: 		untie(%bighash);
                   11045: 	    }
1.534     albertel 11046: 	}
                   11047: 	$title=~s/\&colon\;/\:/gs;
                   11048: 	if ($title) {
1.1159    www      11049: # Remember both $symb and $title for dynamic metadata
                   11050:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      11051:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      11052: # Cache this title and then return it
1.599     albertel 11053: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 11054: 	}
                   11055: 	$urlsymb=$url;
                   11056:     }
                   11057:     my $title=&metadata($urlsymb,'title');
                   11058:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   11059:     return $title;
1.301     www      11060: }
1.613     albertel 11061: 
1.614     albertel 11062: sub get_slot {
                   11063:     my ($which,$cnum,$cdom)=@_;
                   11064:     if (!$cnum || !$cdom) {
1.790     albertel 11065: 	(undef,my $courseid)=&whichuser();
1.620     albertel 11066: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   11067: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 11068:     }
1.703     albertel 11069:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   11070:     my %slotinfo;
                   11071:     if (exists($remembered{$key})) {
                   11072: 	$slotinfo{$which} = $remembered{$key};
                   11073:     } else {
                   11074: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   11075: 	&Apache::lonhomework::showhash(%slotinfo);
                   11076: 	my ($tmp)=keys(%slotinfo);
                   11077: 	if ($tmp=~/^error:/) { return (); }
                   11078: 	$remembered{$key} = $slotinfo{$which};
                   11079:     }
1.616     albertel 11080:     if (ref($slotinfo{$which}) eq 'HASH') {
                   11081: 	return %{$slotinfo{$which}};
                   11082:     }
                   11083:     return $slotinfo{$which};
1.614     albertel 11084: }
1.1150    raeburn  11085: 
                   11086: sub get_reservable_slots {
                   11087:     my ($cnum,$cdom,$uname,$udom) = @_;
                   11088:     my $now = time;
                   11089:     my $reservable_info;
                   11090:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   11091:     if (exists($remembered{$key})) {
                   11092:         $reservable_info = $remembered{$key};
                   11093:     } else {
                   11094:         my %resv;
                   11095:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   11096:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   11097:         $reservable_info = \%resv;
                   11098:         $remembered{$key} = $reservable_info;
                   11099:     }
                   11100:     return $reservable_info;
                   11101: }
                   11102: 
                   11103: sub get_course_slots {
                   11104:     my ($cnum,$cdom) = @_;
                   11105:     my $hashid=$cnum.':'.$cdom;
                   11106:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   11107:     if (defined($cached)) {
                   11108:         if (ref($result) eq 'HASH') {
                   11109:             return %{$result};
                   11110:         }
                   11111:     } else {
                   11112:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   11113:         my ($tmp) = keys(%slots);
                   11114:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  11115:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  11116:             return %slots;
                   11117:         }
                   11118:     }
                   11119:     return;
                   11120: }
                   11121: 
                   11122: sub devalidate_slots_cache {
                   11123:     my ($cnum,$cdom)=@_;
                   11124:     my $hashid=$cnum.':'.$cdom;
                   11125:     &devalidate_cache_new('allslots',$hashid);
                   11126: }
                   11127: 
1.1172.2.8  raeburn  11128: sub get_coursechange {
                   11129:     my ($cdom,$cnum) = @_;
                   11130:     if ($cdom eq '' || $cnum eq '') {
                   11131:         return unless ($env{'request.course.id'});
                   11132:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   11133:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   11134:     }
                   11135:     my $hashid=$cdom.'_'.$cnum;
                   11136:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   11137:     if ((defined($cached)) && ($change ne '')) {
                   11138:         return $change;
                   11139:     } else {
                   11140:         my %crshash;
                   11141:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   11142:         if ($crshash{'internal.contentchange'} eq '') {
                   11143:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   11144:             if ($change eq '') {
                   11145:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   11146:                 $change = $crshash{'internal.created'};
                   11147:             }
                   11148:         } else {
                   11149:             $change = $crshash{'internal.contentchange'};
                   11150:         }
                   11151:         my $cachetime = 600;
                   11152:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   11153:     }
                   11154:     return $change;
                   11155: }
                   11156: 
                   11157: sub devalidate_coursechange_cache {
                   11158:     my ($cnum,$cdom)=@_;
                   11159:     my $hashid=$cnum.':'.$cdom;
                   11160:     &devalidate_cache_new('crschange',$hashid);
                   11161: }
                   11162: 
1.31      www      11163: # ------------------------------------------------- Update symbolic store links
                   11164: 
                   11165: sub symblist {
                   11166:     my ($mapname,%newhash)=@_;
1.438     www      11167:     $mapname=&deversion(&declutter($mapname));
1.31      www      11168:     my %hash;
1.620     albertel 11169:     if (($env{'request.course.fn'}) && (%newhash)) {
                   11170:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11171:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  11172: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 11173: 		next if ($url eq 'last_known'
                   11174: 			 && $env{'form.no_update_last_known'});
                   11175: 		$hash{declutter($url)}=&encode_symb($mapname,
                   11176: 						    $newhash{$url}->[1],
                   11177: 						    $newhash{$url}->[0]);
1.191     harris41 11178:             }
1.31      www      11179:             if (untie(%hash)) {
                   11180: 		return 'ok';
                   11181:             }
                   11182:         }
                   11183:     }
                   11184:     return 'error';
1.212     www      11185: }
                   11186: 
                   11187: # --------------------------------------------------------------- Verify a symb
                   11188: 
                   11189: sub symbverify {
1.1172.2.11  raeburn  11190:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      11191:     my $thisfn=$thisurl;
1.439     www      11192:     $thisfn=&declutter($thisfn);
1.215     www      11193: # direct jump to resource in page or to a sequence - will construct own symbs
                   11194:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   11195: # check URL part
1.409     www      11196:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      11197: 
1.431     www      11198:     unless ($url eq $thisfn) { return 0; }
1.213     www      11199: 
1.216     www      11200:     $symb=&symbclean($symb);
1.510     www      11201:     $thisurl=&deversion($thisurl);
1.439     www      11202:     $thisfn=&deversion($thisfn);
1.213     www      11203: 
                   11204:     my %bighash;
                   11205:     my $okay=0;
1.431     www      11206: 
1.620     albertel 11207:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11208:                             &GDBM_READER(),0640)) {
1.1172.2.13  raeburn  11209:         my $noclutter;
1.1032    raeburn  11210:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   11211:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  11212:             if ($map =~ m{^uploaded/.+\.page$}) {
                   11213:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   11214:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   11215:                 $noclutter = 1;
                   11216:             }
                   11217:         }
                   11218:         my $ids;
                   11219:         if ($noclutter) {
                   11220:             $ids=$bighash{'ids_'.$thisurl};
                   11221:         } else {
                   11222:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  11223:         }
1.1102    raeburn  11224:         unless ($ids) {
1.1172.2.13  raeburn  11225:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  11226:             $ids=$bighash{$idkey};
1.216     www      11227:         }
                   11228:         if ($ids) {
                   11229: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  11230:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   11231:                 $symb =~ s/\?.+$//;
                   11232:             }
1.800     albertel 11233: 	    foreach my $id (split(/\,/,$ids)) {
                   11234: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      11235:                if (
                   11236:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  11237:    eq $symb) {
1.1172.2.11  raeburn  11238:                    if (ref($encstate)) {
                   11239:                        $$encstate = $bighash{'encrypted_'.$id};
                   11240:                    }
1.1172.2.13  raeburn  11241:                    if (($env{'request.role.adv'}) ||
                   11242:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  11243:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  11244:                        $okay=1;
                   11245:                        last;
                   11246:                    }
                   11247:                }
                   11248:            }
1.216     www      11249:         }
1.213     www      11250: 	untie(%bighash);
                   11251:     }
                   11252:     return $okay;
1.31      www      11253: }
                   11254: 
1.210     www      11255: # --------------------------------------------------------------- Clean-up symb
                   11256: 
                   11257: sub symbclean {
                   11258:     my $symb=shift;
1.568     albertel 11259:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      11260: # remove version from map
                   11261:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      11262: 
1.210     www      11263: # remove version from URL
                   11264:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      11265: 
1.507     www      11266: # remove wrapper
                   11267: 
1.510     www      11268:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 11269:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      11270:     return $symb;
1.409     www      11271: }
                   11272: 
                   11273: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 11274: 
                   11275: sub encode_symb {
                   11276:     my ($map,$resid,$url)=@_;
                   11277:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   11278: }
1.409     www      11279: 
                   11280: sub decode_symb {
1.568     albertel 11281:     my $symb=shift;
                   11282:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   11283:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      11284:     return (&fixversion($map),$resid,&fixversion($url));
                   11285: }
                   11286: 
                   11287: sub fixversion {
                   11288:     my $fn=shift;
1.609     banghart 11289:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      11290:     my %bighash;
                   11291:     my $uri=&clutter($fn);
1.620     albertel 11292:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      11293: # is this cached?
1.599     albertel 11294:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      11295:     if (defined($cached)) { return $result; }
                   11296: # unfortunately not cached, or expired
1.620     albertel 11297:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      11298: 	    &GDBM_READER(),0640)) {
                   11299:  	if ($bighash{'version_'.$uri}) {
                   11300:  	    my $version=$bighash{'version_'.$uri};
1.444     www      11301:  	    unless (($version eq 'mostrecent') || 
                   11302: 		    ($version==&getversion($uri))) {
1.440     www      11303:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   11304:  	    }
                   11305:  	}
                   11306:  	untie %bighash;
1.413     www      11307:     }
1.599     albertel 11308:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      11309: }
                   11310: 
                   11311: sub deversion {
                   11312:     my $url=shift;
                   11313:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   11314:     return $url;
1.210     www      11315: }
                   11316: 
1.31      www      11317: # ------------------------------------------------------ Return symb list entry
                   11318: 
                   11319: sub symbread {
1.1172.2.66  raeburn  11320:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1172.2.54  raeburn  11321:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.66  raeburn  11322:     if (defined($env{$cache_str})) {
                   11323:         if ($ignorecachednull) {
                   11324:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   11325:         } else {
                   11326:             return $env{$cache_str};
                   11327:         }
                   11328:     }
1.242     www      11329: # no filename provided? try from environment
1.1172.2.54  raeburn  11330:     unless ($thisfn) {
1.620     albertel 11331:         if ($env{'request.symb'}) {
1.1172.2.13  raeburn  11332:             return $env{$cache_str}=&symbclean($env{'request.symb'});
                   11333:         }
                   11334:         $thisfn=$env{'request.filename'};
1.44      www      11335:     }
1.569     albertel 11336:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      11337: # is that filename actually a symb? Verify, clean, and return
                   11338:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 11339: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 11340: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 11341: 	}
1.242     www      11342:     }
1.44      www      11343:     $thisfn=declutter($thisfn);
1.31      www      11344:     my %hash;
1.37      www      11345:     my %bighash;
                   11346:     my $syval='';
1.620     albertel 11347:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  11348:         my $targetfn = $thisfn;
1.609     banghart 11349:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  11350:             $targetfn = 'adm/wrapper/'.$thisfn;
                   11351:         }
1.687     albertel 11352: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   11353: 	    $targetfn=$1;
                   11354: 	}
1.620     albertel 11355:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11356:                       &GDBM_READER(),0640)) {
1.481     raeburn  11357: 	    $syval=$hash{$targetfn};
1.37      www      11358:             untie(%hash);
                   11359:         }
                   11360: # ---------------------------------------------------------- There was an entry
                   11361:         if ($syval) {
1.601     albertel 11362: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 11363: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  11364: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11365: 		    #return $env{$cache_str}='';
1.601     albertel 11366: 		#}    
                   11367: 		#$syval.=$1;
                   11368: 	    #}
1.37      www      11369:         } else {
                   11370: # ------------------------------------------------------- Was not in symb table
1.620     albertel 11371:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11372:                             &GDBM_READER(),0640)) {
1.37      www      11373: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      11374:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      11375:               unless ($ids) { 
                   11376:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      11377:               }
                   11378:               unless ($ids) {
                   11379: # alias?
                   11380: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      11381:               }
1.37      www      11382:               if ($ids) {
                   11383: # ------------------------------------------------------------------- Has ID(s)
                   11384:                  my @possibilities=split(/\,/,$ids);
1.39      www      11385:                  if ($#possibilities==0) {
                   11386: # ----------------------------------------------- There is only one possibility
1.37      www      11387: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 11388: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11389: 						    $resid,$thisfn);
1.1172.2.66  raeburn  11390:                      if (ref($possibles) eq 'HASH') {
                   11391:                          $possibles->{$syval} = 1;
                   11392:                      }
                   11393:                      if ($checkforblock) {
                   11394:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   11395:                          if (@blockers) {
                   11396:                              $syval = '';
                   11397:                              return;
                   11398:                          }
                   11399:                      }
                   11400:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39      www      11401: # ------------------------------------------ There is more than one possibility
                   11402:                      my $realpossible=0;
1.800     albertel 11403:                      foreach my $id (@possibilities) {
                   11404: 			 my $file=$bighash{'src_'.$id};
1.1172.2.66  raeburn  11405:                          my $canaccess;
                   11406:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   11407:                              $canaccess = 1;
                   11408:                          } else {
                   11409:                              $canaccess = &allowed('bre',$file);
                   11410:                          }
                   11411:                          if ($canaccess) {
                   11412:          		     my ($mapid,$resid)=split(/\./,$id);
                   11413:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   11414:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11415:                                                              $resid,$thisfn);
                   11416:                                  if (ref($possibles) eq 'HASH') {
                   11417:                                      $possibles->{$syval} = 1;
                   11418:                                  }
                   11419:                                  if ($checkforblock) {
                   11420:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   11421:                                      unless (@blockers > 0) {
                   11422:                                          $syval = $poss_syval;
                   11423:                                          $realpossible++;
                   11424:                                      }
                   11425:                                  } else {
                   11426:                                      $syval = $poss_syval;
                   11427:                                      $realpossible++;
                   11428:                                  }
                   11429:                              }
1.39      www      11430: 			 }
1.191     harris41 11431:                      }
1.39      www      11432: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      11433:                  } else {
                   11434:                      $syval='';
1.37      www      11435:                  }
                   11436: 	      }
1.1172.2.66  raeburn  11437:               untie(%bighash);
1.481     raeburn  11438:            }
1.31      www      11439:         }
1.62      www      11440:         if ($syval) {
1.620     albertel 11441: 	    return $env{$cache_str}=$syval;
1.62      www      11442:         }
1.31      www      11443:     }
1.949     raeburn  11444:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11445:     return $env{$cache_str}='';
1.31      www      11446: }
                   11447: 
                   11448: # ---------------------------------------------------------- Return random seed
                   11449: 
1.32      www      11450: sub numval {
                   11451:     my $txt=shift;
                   11452:     $txt=~tr/A-J/0-9/;
                   11453:     $txt=~tr/a-j/0-9/;
                   11454:     $txt=~tr/K-T/0-9/;
                   11455:     $txt=~tr/k-t/0-9/;
                   11456:     $txt=~tr/U-Z/0-5/;
                   11457:     $txt=~tr/u-z/0-5/;
                   11458:     $txt=~s/\D//g;
1.564     albertel 11459:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      11460:     return int($txt);
1.368     albertel 11461: }
                   11462: 
1.484     albertel 11463: sub numval2 {
                   11464:     my $txt=shift;
                   11465:     $txt=~tr/A-J/0-9/;
                   11466:     $txt=~tr/a-j/0-9/;
                   11467:     $txt=~tr/K-T/0-9/;
                   11468:     $txt=~tr/k-t/0-9/;
                   11469:     $txt=~tr/U-Z/0-5/;
                   11470:     $txt=~tr/u-z/0-5/;
                   11471:     $txt=~s/\D//g;
                   11472:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11473:     my $total;
                   11474:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 11475:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 11476:     return int($total);
                   11477: }
                   11478: 
1.575     albertel 11479: sub numval3 {
                   11480:     use integer;
                   11481:     my $txt=shift;
                   11482:     $txt=~tr/A-J/0-9/;
                   11483:     $txt=~tr/a-j/0-9/;
                   11484:     $txt=~tr/K-T/0-9/;
                   11485:     $txt=~tr/k-t/0-9/;
                   11486:     $txt=~tr/U-Z/0-5/;
                   11487:     $txt=~tr/u-z/0-5/;
                   11488:     $txt=~s/\D//g;
                   11489:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11490:     my $total;
                   11491:     foreach my $val (@txts) { $total+=$val; }
                   11492:     if ($_64bit) { $total=(($total<<32)>>32); }
                   11493:     return $total;
                   11494: }
                   11495: 
1.675     albertel 11496: sub digest {
                   11497:     my ($data)=@_;
                   11498:     my $digest=&Digest::MD5::md5($data);
                   11499:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   11500:     my ($e,$f);
                   11501:     {
                   11502:         use integer;
                   11503:         $e=($a+$b);
                   11504:         $f=($c+$d);
                   11505:         if ($_64bit) {
                   11506:             $e=(($e<<32)>>32);
                   11507:             $f=(($f<<32)>>32);
                   11508:         }
                   11509:     }
                   11510:     if (wantarray) {
                   11511: 	return ($e,$f);
                   11512:     } else {
                   11513: 	my $g;
                   11514: 	{
                   11515: 	    use integer;
                   11516: 	    $g=($e+$f);
                   11517: 	    if ($_64bit) {
                   11518: 		$g=(($g<<32)>>32);
                   11519: 	    }
                   11520: 	}
                   11521: 	return $g;
                   11522:     }
                   11523: }
                   11524: 
1.368     albertel 11525: sub latest_rnd_algorithm_id {
1.675     albertel 11526:     return '64bit5';
1.366     albertel 11527: }
1.32      www      11528: 
1.503     albertel 11529: sub get_rand_alg {
                   11530:     my ($courseid)=@_;
1.790     albertel 11531:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 11532:     if ($courseid) {
1.620     albertel 11533: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 11534:     }
                   11535:     return &latest_rnd_algorithm_id();
                   11536: }
                   11537: 
1.562     albertel 11538: sub validCODE {
                   11539:     my ($CODE)=@_;
                   11540:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   11541:     return 0;
                   11542: }
                   11543: 
1.491     albertel 11544: sub getCODE {
1.620     albertel 11545:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 11546:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   11547: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   11548: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 11549: 	return $Apache::lonhomework::history{'resource.CODE'};
                   11550:     }
                   11551:     return undef;
                   11552: }
1.1133    foxr     11553: #
                   11554: #  Determines the random seed for a specific context:
                   11555: #
                   11556: # parameters:
                   11557: #   symb      - in course context the symb for the seed.
                   11558: #   course_id - The course id of the form domain_coursenum.
                   11559: #   domain    - Domain for the user.
                   11560: #   course    - Course for the user.
                   11561: #   cenv      - environment of the course.
                   11562: #
                   11563: # NOTE:
                   11564: #   All parameters are picked out of the environment if missing
                   11565: #   or not defined.
                   11566: #   If a symb cannot be determined the current time is used instead.
                   11567: #
                   11568: #  For a given well defined symb, courside, domain, username,
                   11569: #  and course environment, the seed is reproducible.
                   11570: #
1.31      www      11571: sub rndseed {
1.1133    foxr     11572:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 11573:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 11574:     if (!defined($symb)) {
1.366     albertel 11575: 	unless ($symb=$wsymb) { return time; }
                   11576:     }
1.1146    foxr     11577:     if (!defined $courseid) { 
                   11578: 	$courseid=$wcourseid; 
                   11579:     }
                   11580:     if (!defined $domain) { $domain=$wdomain; }
                   11581:     if (!defined $username) { $username=$wusername }
1.1133    foxr     11582: 
                   11583:     my $which;
                   11584:     if (defined($cenv->{'rndseed'})) {
                   11585: 	$which = $cenv->{'rndseed'};
                   11586:     } else {
                   11587: 	$which =&get_rand_alg($courseid);
                   11588:     }
1.491     albertel 11589:     if (defined(&getCODE())) {
1.675     albertel 11590: 	if ($which eq '64bit5') {
                   11591: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   11592: 	} elsif ($which eq '64bit4') {
1.575     albertel 11593: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   11594: 	} else {
                   11595: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   11596: 	}
1.675     albertel 11597:     } elsif ($which eq '64bit5') {
                   11598: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 11599:     } elsif ($which eq '64bit4') {
                   11600: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 11601:     } elsif ($which eq '64bit3') {
                   11602: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 11603:     } elsif ($which eq '64bit2') {
                   11604: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 11605:     } elsif ($which eq '64bit') {
                   11606: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   11607:     }
                   11608:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   11609: }
                   11610: 
                   11611: sub rndseed_32bit {
                   11612:     my ($symb,$courseid,$domain,$username)=@_;
                   11613:     {
                   11614: 	use integer;
                   11615: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   11616: 	my $symbseed=numval($symb) << 22;
                   11617: 	my $namechck=unpack("%32C*",$username) << 17;
                   11618: 	my $nameseed=numval($username) << 12;
                   11619: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   11620: 	my $courseseed=unpack("%32C*",$courseid);
                   11621: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 11622: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11623: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 11624: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 11625: 	return $num;
                   11626:     }
                   11627: }
                   11628: 
                   11629: sub rndseed_64bit {
                   11630:     my ($symb,$courseid,$domain,$username)=@_;
                   11631:     {
                   11632: 	use integer;
                   11633: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   11634: 	my $symbseed=numval($symb) << 10;
                   11635: 	my $namechck=unpack("%32S*",$username);
                   11636: 	
                   11637: 	my $nameseed=numval($username) << 21;
                   11638: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   11639: 	my $courseseed=unpack("%32S*",$courseid);
                   11640: 	
                   11641: 	my $num1=$symbchck+$symbseed+$namechck;
                   11642: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11643: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11644: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 11645: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 11646: 	return "$num1,$num2";
1.155     albertel 11647:     }
1.366     albertel 11648: }
                   11649: 
1.443     albertel 11650: sub rndseed_64bit2 {
                   11651:     my ($symb,$courseid,$domain,$username)=@_;
                   11652:     {
                   11653: 	use integer;
                   11654: 	# strings need to be an even # of cahracters long, it it is odd the
                   11655:         # last characters gets thrown away
                   11656: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11657: 	my $symbseed=numval($symb) << 10;
                   11658: 	my $namechck=unpack("%32S*",$username.' ');
                   11659: 	
                   11660: 	my $nameseed=numval($username) << 21;
1.501     albertel 11661: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11662: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11663: 	
                   11664: 	my $num1=$symbchck+$symbseed+$namechck;
                   11665: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11666: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11667: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 11668: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 11669: 	return "$num1,$num2";
                   11670:     }
                   11671: }
                   11672: 
                   11673: sub rndseed_64bit3 {
                   11674:     my ($symb,$courseid,$domain,$username)=@_;
                   11675:     {
                   11676: 	use integer;
                   11677: 	# strings need to be an even # of cahracters long, it it is odd the
                   11678:         # last characters gets thrown away
                   11679: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11680: 	my $symbseed=numval2($symb) << 10;
                   11681: 	my $namechck=unpack("%32S*",$username.' ');
                   11682: 	
                   11683: 	my $nameseed=numval2($username) << 21;
1.443     albertel 11684: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11685: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11686: 	
                   11687: 	my $num1=$symbchck+$symbseed+$namechck;
                   11688: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11689: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11690: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 11691: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11692: 	
1.503     albertel 11693: 	return "$num1:$num2";
1.443     albertel 11694:     }
                   11695: }
                   11696: 
1.575     albertel 11697: sub rndseed_64bit4 {
                   11698:     my ($symb,$courseid,$domain,$username)=@_;
                   11699:     {
                   11700: 	use integer;
                   11701: 	# strings need to be an even # of cahracters long, it it is odd the
                   11702:         # last characters gets thrown away
                   11703: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11704: 	my $symbseed=numval3($symb) << 10;
                   11705: 	my $namechck=unpack("%32S*",$username.' ');
                   11706: 	
                   11707: 	my $nameseed=numval3($username) << 21;
                   11708: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11709: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11710: 	
                   11711: 	my $num1=$symbchck+$symbseed+$namechck;
                   11712: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11713: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11714: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 11715: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11716: 	
1.575     albertel 11717: 	return "$num1:$num2";
                   11718:     }
                   11719: }
                   11720: 
1.675     albertel 11721: sub rndseed_64bit5 {
                   11722:     my ($symb,$courseid,$domain,$username)=@_;
                   11723:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   11724:     return "$num1:$num2";
                   11725: }
                   11726: 
1.366     albertel 11727: sub rndseed_CODE_64bit {
                   11728:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 11729:     {
1.366     albertel 11730: 	use integer;
1.443     albertel 11731: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 11732: 	my $symbseed=numval2($symb);
1.491     albertel 11733: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11734: 	my $CODEseed=numval(&getCODE());
1.443     albertel 11735: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 11736: 	my $num1=$symbseed+$CODEchck;
                   11737: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11738: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11739: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 11740: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11741: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 11742: 	return "$num1:$num2";
1.366     albertel 11743:     }
                   11744: }
                   11745: 
1.575     albertel 11746: sub rndseed_CODE_64bit4 {
                   11747:     my ($symb,$courseid,$domain,$username)=@_;
                   11748:     {
                   11749: 	use integer;
                   11750: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   11751: 	my $symbseed=numval3($symb);
                   11752: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11753: 	my $CODEseed=numval3(&getCODE());
                   11754: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11755: 	my $num1=$symbseed+$CODEchck;
                   11756: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11757: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11758: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 11759: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11760: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   11761: 	return "$num1:$num2";
                   11762:     }
                   11763: }
                   11764: 
1.675     albertel 11765: sub rndseed_CODE_64bit5 {
                   11766:     my ($symb,$courseid,$domain,$username)=@_;
                   11767:     my $code = &getCODE();
                   11768:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   11769:     return "$num1:$num2";
                   11770: }
                   11771: 
1.366     albertel 11772: sub setup_random_from_rndseed {
                   11773:     my ($rndseed)=@_;
1.503     albertel 11774:     if ($rndseed =~/([,:])/) {
1.1172.2.51  raeburn  11775: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   11776:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   11777:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   11778:         } else {
                   11779:             &Math::Random::random_set_seed($num1,$num2);
                   11780:         }
1.366     albertel 11781:     } else {
                   11782: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 11783:     }
1.36      albertel 11784: }
                   11785: 
1.474     albertel 11786: sub latest_receipt_algorithm_id {
1.835     albertel 11787:     return 'receipt3';
1.474     albertel 11788: }
                   11789: 
1.480     www      11790: sub recunique {
                   11791:     my $fucourseid=shift;
                   11792:     my $unique;
1.835     albertel 11793:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   11794: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11795: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      11796:     } else {
                   11797: 	$unique=$perlvar{'lonReceipt'};
                   11798:     }
                   11799:     return unpack("%32C*",$unique);
                   11800: }
                   11801: 
                   11802: sub recprefix {
                   11803:     my $fucourseid=shift;
                   11804:     my $prefix;
1.835     albertel 11805:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   11806: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11807: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      11808:     } else {
                   11809: 	$prefix=$perlvar{'lonHostID'};
                   11810:     }
                   11811:     return unpack("%32C*",$prefix);
                   11812: }
                   11813: 
1.76      www      11814: sub ireceipt {
1.474     albertel 11815:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 11816: 
                   11817:     my $return =&recprefix($fucourseid).'-';
                   11818: 
                   11819:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   11820: 	$env{'request.state'} eq 'construct') {
                   11821: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   11822: 	return $return;
                   11823:     }
                   11824: 
1.76      www      11825:     my $cuname=unpack("%32C*",$funame);
                   11826:     my $cudom=unpack("%32C*",$fudom);
                   11827:     my $cucourseid=unpack("%32C*",$fucourseid);
                   11828:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      11829:     my $cunique=&recunique($fucourseid);
1.474     albertel 11830:     my $cpart=unpack("%32S*",$part);
1.835     albertel 11831:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   11832: 
1.790     albertel 11833: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 11834: 			       
                   11835: 	$return.= ($cunique%$cuname+
                   11836: 		   $cunique%$cudom+
                   11837: 		   $cusymb%$cuname+
                   11838: 		   $cusymb%$cudom+
                   11839: 		   $cucourseid%$cuname+
                   11840: 		   $cucourseid%$cudom+
                   11841: 		   $cpart%$cuname+
                   11842: 		   $cpart%$cudom);
                   11843:     } else {
                   11844: 	$return.= ($cunique%$cuname+
                   11845: 		   $cunique%$cudom+
                   11846: 		   $cusymb%$cuname+
                   11847: 		   $cusymb%$cudom+
                   11848: 		   $cucourseid%$cuname+
                   11849: 		   $cucourseid%$cudom);
                   11850:     }
                   11851:     return $return;
1.76      www      11852: }
                   11853: 
                   11854: sub receipt {
1.474     albertel 11855:     my ($part)=@_;
1.790     albertel 11856:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 11857:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      11858: }
1.260     ng       11859: 
1.790     albertel 11860: sub whichuser {
                   11861:     my ($passedsymb)=@_;
                   11862:     my ($symb,$courseid,$domain,$name,$publicuser);
                   11863:     if (defined($env{'form.grade_symb'})) {
                   11864: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   11865: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   11866: 	if (!$allowed &&
                   11867: 	    exists($env{'request.course.sec'}) &&
                   11868: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   11869: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   11870: 			      '/'.$env{'request.course.sec'});
                   11871: 	}
                   11872: 	if ($allowed) {
                   11873: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   11874: 	    $courseid=$tmp_courseid;
                   11875: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   11876: 	    ($name)=&get_env_multiple('form.grade_username');
                   11877: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   11878: 	}
                   11879:     }
                   11880:     if (!$passedsymb) {
                   11881: 	$symb=&symbread();
                   11882:     } else {
                   11883: 	$symb=$passedsymb;
                   11884:     }
                   11885:     $courseid=$env{'request.course.id'};
                   11886:     $domain=$env{'user.domain'};
                   11887:     $name=$env{'user.name'};
                   11888:     if ($name eq 'public' && $domain eq 'public') {
                   11889: 	if (!defined($env{'form.username'})) {
                   11890: 	    $env{'form.username'}.=time.rand(10000000);
                   11891: 	}
                   11892: 	$name.=$env{'form.username'};
                   11893:     }
                   11894:     return ($symb,$courseid,$domain,$name,$publicuser);
                   11895: 
                   11896: }
                   11897: 
1.36      albertel 11898: # ------------------------------------------------------------ Serves up a file
1.472     albertel 11899: # returns either the contents of the file or 
                   11900: # -1 if the file doesn't exist
1.481     raeburn  11901: #
                   11902: # if the target is a file that was uploaded via DOCS, 
                   11903: # a check will be made to see if a current copy exists on the local server,
                   11904: # if it does this will be served, otherwise a copy will be retrieved from
                   11905: # the home server for the course and stored in /home/httpd/html/userfiles on
                   11906: # the local server.   
1.472     albertel 11907: 
1.36      albertel 11908: sub getfile {
1.538     albertel 11909:     my ($file) = @_;
1.609     banghart 11910:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 11911:     &repcopy($file);
                   11912:     return &readfile($file);
                   11913: }
                   11914: 
                   11915: sub repcopy_userfile {
                   11916:     my ($file)=@_;
1.1142    raeburn  11917:     my $londocroot = $perlvar{'lonDocRoot'};
                   11918:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  11919:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 11920:     my ($cdom,$cnum,$filename) = 
1.811     albertel 11921: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 11922:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   11923:     if (-e "$file") {
1.828     www      11924: # we already have a local copy, check it out
1.538     albertel 11925: 	my @fileinfo = stat($file);
1.828     www      11926: 	my $rtncode;
                   11927: 	my $info;
1.538     albertel 11928: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 11929: 	if ($lwpresp ne 'ok') {
1.828     www      11930: # there is no such file anymore, even though we had a local copy
1.482     albertel 11931: 	    if ($rtncode eq '404') {
1.538     albertel 11932: 		unlink($file);
1.482     albertel 11933: 	    }
                   11934: 	    return -1;
                   11935: 	}
                   11936: 	if ($info < $fileinfo[9]) {
1.828     www      11937: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  11938: 	    return 'ok';
1.828     www      11939: 	} else {
                   11940: # the file is outdated, get rid of it
                   11941: 	    unlink($file);
1.482     albertel 11942: 	}
1.828     www      11943:     }
                   11944: # one way or the other, at this point, we don't have the file
                   11945: # construct the correct path for the file
                   11946:     my @parts = ($cdom,$cnum); 
                   11947:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   11948: 	push @parts, split(/\//,$1);
                   11949:     }
                   11950:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   11951:     foreach my $part (@parts) {
                   11952: 	$path .= '/'.$part;
                   11953: 	if (!-e $path) {
                   11954: 	    mkdir($path,0770);
1.482     albertel 11955: 	}
                   11956:     }
1.828     www      11957: # now the path exists for sure
                   11958: # get a user agent
                   11959:     my $ua=new LWP::UserAgent;
                   11960:     my $transferfile=$file.'.in.transfer';
                   11961: # FIXME: this should flock
                   11962:     if (-e $transferfile) { return 'ok'; }
                   11963:     my $request;
                   11964:     $uri=~s/^\///;
1.980     raeburn  11965:     my $homeserver = &homeserver($cnum,$cdom);
                   11966:     my $protocol = $protocol{$homeserver};
                   11967:     $protocol = 'http' if ($protocol ne 'https');
                   11968:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      11969:     my $response=$ua->request($request,$transferfile);
                   11970: # did it work?
                   11971:     if ($response->is_error()) {
                   11972: 	unlink($transferfile);
                   11973: 	&logthis("Userfile repcopy failed for $uri");
                   11974: 	return -1;
                   11975:     }
                   11976: # worked, rename the transfer file
                   11977:     rename($transferfile,$file);
1.607     raeburn  11978:     return 'ok';
1.481     raeburn  11979: }
                   11980: 
1.517     albertel 11981: sub tokenwrapper {
                   11982:     my $uri=shift;
1.980     raeburn  11983:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 11984:     $uri=~s|^/||;
1.620     albertel 11985:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 11986:     my $token=$1;
1.552     albertel 11987:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   11988:     if ($udom && $uname && $file) {
                   11989: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  11990:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  11991:         my $homeserver = &homeserver($uname,$udom);
                   11992:         my $protocol = $protocol{$homeserver};
                   11993:         $protocol = 'http' if ($protocol ne 'https');
                   11994:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 11995:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   11996:                                '&tokenissued='.$perlvar{'lonHostID'};
                   11997:     } else {
                   11998:         return '/adm/notfound.html';
                   11999:     }
                   12000: }
                   12001: 
1.828     www      12002: # call with reqtype HEAD: get last modification time
                   12003: # call with reqtype GET: get the file contents
                   12004: # Do not call this with reqtype GET for large files! It loads everything into memory
                   12005: #
1.481     raeburn  12006: sub getuploaded {
                   12007:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   12008:     $uri=~s/^\///;
1.980     raeburn  12009:     my $homeserver = &homeserver($cnum,$cdom);
                   12010:     my $protocol = $protocol{$homeserver};
                   12011:     $protocol = 'http' if ($protocol ne 'https');
                   12012:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  12013:     my $ua=new LWP::UserAgent;
                   12014:     my $request=new HTTP::Request($reqtype,$uri);
                   12015:     my $response=$ua->request($request);
                   12016:     $$rtncode = $response->code;
1.482     albertel 12017:     if (! $response->is_success()) {
                   12018: 	return 'failed';
                   12019:     }      
                   12020:     if ($reqtype eq 'HEAD') {
1.486     www      12021: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 12022:     } elsif ($reqtype eq 'GET') {
                   12023: 	$$info = $response->content;
1.472     albertel 12024:     }
1.482     albertel 12025:     return 'ok';
1.36      albertel 12026: }
                   12027: 
1.481     raeburn  12028: sub readfile {
                   12029:     my $file = shift;
                   12030:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   12031:     my $fh;
                   12032:     open($fh,"<$file");
                   12033:     my $a='';
1.800     albertel 12034:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  12035:     return $a;
                   12036: }
                   12037: 
1.36      albertel 12038: sub filelocation {
1.590     banghart 12039:     my ($dir,$file) = @_;
                   12040:     my $location;
                   12041:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 12042: 
                   12043:     if ($file =~ m-^/adm/-) {
                   12044: 	$file=~s-^/adm/wrapper/-/-;
                   12045: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   12046:     }
1.882     albertel 12047: 
1.1139    www      12048:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  12049:         $location = $file;
1.609     banghart 12050:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 12051:         my ($udom,$uname,$filename)=
1.811     albertel 12052:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 12053:         my $home=&homeserver($uname,$udom);
                   12054:         my $is_me=0;
                   12055:         my @ids=&current_machine_ids();
                   12056:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   12057:         if ($is_me) {
1.1117    foxr     12058:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 12059:         } else {
                   12060:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   12061:   	      $udom.'/'.$uname.'/'.$filename;
                   12062:         }
1.882     albertel 12063:     } elsif ($file =~ m-^/adm/-) {
                   12064: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 12065:     } else {
                   12066:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      12067:         $file=~s:^/(res|priv)/:/:;
                   12068:         my $space=$1;
1.590     banghart 12069:         if ( !( $file =~ m:^/:) ) {
                   12070:             $location = $dir. '/'.$file;
                   12071:         } else {
1.1142    raeburn  12072:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 12073:         }
1.59      albertel 12074:     }
1.590     banghart 12075:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 12076:     while ($location=~m{/\.\./}) {
                   12077: 	if ($location =~ m{/[^/]+/\.\./}) {
                   12078: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   12079: 	} else {
                   12080: 	    $location=~ s{/\.\./}{/}g;
                   12081: 	}
                   12082:     } #remove dir/..
1.590     banghart 12083:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   12084:     return $location;
1.46      www      12085: }
1.36      albertel 12086: 
1.46      www      12087: sub hreflocation {
                   12088:     my ($dir,$file)=@_;
1.980     raeburn  12089:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 12090: 	$file=filelocation($dir,$file);
1.700     albertel 12091:     } elsif ($file=~m-^/adm/-) {
                   12092: 	$file=~s-^/adm/wrapper/-/-;
                   12093: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 12094:     }
                   12095:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   12096: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   12097:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  12098: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   12099: 	        {/uploaded/$1/$2/}x;
1.46      www      12100:     }
1.913     albertel 12101:     if ($file=~ m{^/userfiles/}) {
                   12102: 	$file =~ s{^/userfiles/}{/uploaded/};
                   12103:     }
1.462     albertel 12104:     return $file;
1.465     albertel 12105: }
                   12106: 
1.1139    www      12107: 
                   12108: 
                   12109: 
                   12110: 
1.465     albertel 12111: sub current_machine_domains {
1.853     albertel 12112:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   12113: }
                   12114: 
                   12115: sub machine_domains {
                   12116:     my ($hostname) = @_;
1.465     albertel 12117:     my @domains;
1.838     albertel 12118:     my %hostname = &all_hostnames();
1.465     albertel 12119:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  12120: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 12121: 	if ($hostname eq $name) {
1.844     albertel 12122: 	    push(@domains,&host_domain($id));
1.465     albertel 12123: 	}
                   12124:     }
                   12125:     return @domains;
                   12126: }
                   12127: 
                   12128: sub current_machine_ids {
1.853     albertel 12129:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   12130: }
                   12131: 
                   12132: sub machine_ids {
                   12133:     my ($hostname) = @_;
                   12134:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 12135:     my @ids;
1.888     albertel 12136:     my %name_to_host = &all_names();
1.889     albertel 12137:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   12138: 	return @{ $name_to_host{$hostname} };
                   12139:     }
                   12140:     return;
1.31      www      12141: }
                   12142: 
1.824     raeburn  12143: sub additional_machine_domains {
                   12144:     my @domains;
                   12145:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   12146:     while( my $line = <$fh>) {
                   12147:         $line =~ s/\s//g;
                   12148:         push(@domains,$line);
                   12149:     }
                   12150:     return @domains;
                   12151: }
                   12152: 
                   12153: sub default_login_domain {
                   12154:     my $domain = $perlvar{'lonDefDomain'};
                   12155:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   12156:     foreach my $posdom (&current_machine_domains(),
                   12157:                         &additional_machine_domains()) {
                   12158:         if (lc($posdom) eq lc($testdomain)) {
                   12159:             $domain=$posdom;
                   12160:             last;
                   12161:         }
                   12162:     }
                   12163:     return $domain;
                   12164: }
                   12165: 
1.31      www      12166: # ------------------------------------------------------------- Declutters URLs
                   12167: 
                   12168: sub declutter {
                   12169:     my $thisfn=shift;
1.569     albertel 12170:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49  raeburn  12171:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   12172:         $thisfn=~s{^/home/httpd/html}{};
                   12173:     }
1.31      www      12174:     $thisfn=~s/^\///;
1.697     albertel 12175:     $thisfn=~s|^adm/wrapper/||;
                   12176:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      12177:     $thisfn=~s/^res\///;
1.1172    bisitz   12178:     $thisfn=~s/^priv\///;
1.1032    raeburn  12179:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   12180:         $thisfn=~s/\?.+$//;
                   12181:     }
1.268     www      12182:     return $thisfn;
                   12183: }
                   12184: 
                   12185: # ------------------------------------------------------------- Clutter up URLs
                   12186: 
                   12187: sub clutter {
                   12188:     my $thisfn='/'.&declutter(shift);
1.887     albertel 12189:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 12190: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      12191:        $thisfn='/res'.$thisfn; 
                   12192:     }
1.1031    raeburn  12193:     if ($thisfn !~m|^/adm|) {
                   12194: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 12195: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 12196: 	} else {
                   12197: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   12198: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 12199: 	    if ($embstyle eq 'ssi'
                   12200: 		|| ($embstyle eq 'hdn')
                   12201: 		|| ($embstyle eq 'rat')
                   12202: 		|| ($embstyle eq 'prv')
                   12203: 		|| ($embstyle eq 'ign')) {
                   12204: 		#do nothing with these
                   12205: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 12206: 		|| ($embstyle eq 'emb')
                   12207: 		|| ($embstyle eq 'wrp')) {
                   12208: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 12209: 	    } elsif ($embstyle eq 'unk'
                   12210: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 12211: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 12212: 	    } else {
1.718     www      12213: #		&logthis("Got a blank emb style");
1.695     albertel 12214: 	    }
1.694     albertel 12215: 	}
                   12216:     }
1.31      www      12217:     return $thisfn;
1.12      www      12218: }
                   12219: 
1.787     albertel 12220: sub clutter_with_no_wrapper {
                   12221:     my $uri = &clutter(shift);
                   12222:     if ($uri =~ m-^/adm/-) {
                   12223: 	$uri =~ s-^/adm/wrapper/-/-;
                   12224: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   12225:     }
                   12226:     return $uri;
                   12227: }
                   12228: 
1.557     albertel 12229: sub freeze_escape {
                   12230:     my ($value)=@_;
                   12231:     if (ref($value)) {
                   12232: 	$value=&nfreeze($value);
                   12233: 	return '__FROZEN__'.&escape($value);
                   12234:     }
                   12235:     return &escape($value);
                   12236: }
                   12237: 
1.11      www      12238: 
1.557     albertel 12239: sub thaw_unescape {
                   12240:     my ($value)=@_;
                   12241:     if ($value =~ /^__FROZEN__/) {
                   12242: 	substr($value,0,10,undef);
                   12243: 	$value=&unescape($value);
                   12244: 	return &thaw($value);
                   12245:     }
                   12246:     return &unescape($value);
                   12247: }
                   12248: 
1.436     albertel 12249: sub correct_line_ends {
                   12250:     my ($result)=@_;
                   12251:     $$result =~s/\r\n/\n/mg;
                   12252:     $$result =~s/\r/\n/mg;
1.415     albertel 12253: }
1.1       albertel 12254: # ================================================================ Main Program
                   12255: 
1.184     www      12256: sub goodbye {
1.204     albertel 12257:    &logthis("Starting Shut down");
1.443     albertel 12258: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 12259:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 12260: #converted
1.599     albertel 12261: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 12262:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   12263: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   12264: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 12265: #1.1 only
1.870     albertel 12266: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   12267: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   12268: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   12269: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   12270:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 12271:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   12272:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      12273:    &flushcourselogs();
                   12274:    &logthis("Shutting down");
                   12275: }
                   12276: 
1.852     albertel 12277: sub get_dns {
1.1172.2.17  raeburn  12278:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 12279:     if (!$ignore_cache) {
                   12280: 	my ($content,$cached)=
                   12281: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   12282: 	if ($cached) {
1.1172.2.17  raeburn  12283: 	    &$func($content,$hashref);
1.869     albertel 12284: 	    return;
                   12285: 	}
                   12286:     }
                   12287: 
                   12288:     my %alldns;
1.852     albertel 12289:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   12290:     foreach my $dns (<$config>) {
                   12291: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  12292:         my $line = $1;
                   12293:         my ($host,$protocol) = split(/:/,$line);
                   12294:         if ($protocol ne 'https') {
                   12295:             $protocol = 'http';
                   12296:         }
                   12297: 	$alldns{$host} = $protocol;
1.869     albertel 12298:     }
                   12299:     while (%alldns) {
1.1172.2.52  raeburn  12300: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 12301: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  12302:         $ua->timeout(30);
1.979     raeburn  12303: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 12304: 	my $response=$ua->request($request);
1.979     raeburn  12305:         delete($alldns{$dns});
1.852     albertel 12306: 	next if ($response->is_error());
                   12307: 	my @content = split("\n",$response->content);
1.1172.2.17  raeburn  12308:         unless ($nocache) {
1.1172.2.23  raeburn  12309: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  12310:         }
                   12311: 	&$func(\@content,$hashref);
1.869     albertel 12312: 	return;
1.852     albertel 12313:     }
                   12314:     close($config);
1.871     albertel 12315:     my $which = (split('/',$url))[3];
                   12316:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   12317:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 12318:     my @content = <$config>;
1.1172.2.17  raeburn  12319:     &$func(\@content,$hashref);
                   12320:     return;
                   12321: }
                   12322: 
                   12323: # ------------------------------------------------------Get DNS checksums file
                   12324: sub parse_dns_checksums_tab {
                   12325:     my ($lines,$hashref) = @_;
1.1172.2.53  raeburn  12326:     my $lonhost = $perlvar{'lonHostID'};
                   12327:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17  raeburn  12328:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53  raeburn  12329:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   12330:     my $webconfdir = '/etc/httpd/conf';
                   12331:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   12332:         $webconfdir = '/etc/apache2';
                   12333:     } elsif ($distro =~ /^sles(\d+)$/) {
                   12334:         if ($1 >= 10) {
                   12335:             $webconfdir = '/etc/apache2';
                   12336:         }
                   12337:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   12338:         if ($1 >= 10.0) {
                   12339:             $webconfdir = '/etc/apache2';
                   12340:         }
                   12341:     }
1.1172.2.17  raeburn  12342:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   12343:     my (%chksum,%revnum);
                   12344:     if (ref($lines) eq 'ARRAY') {
                   12345:         chomp(@{$lines});
1.1172.2.34  raeburn  12346:         my $version = shift(@{$lines});
                   12347:         if ($version eq $release) {
1.1172.2.17  raeburn  12348:             foreach my $line (@{$lines}) {
1.1172.2.34  raeburn  12349:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53  raeburn  12350:                 if ($file =~ m{^/etc/httpd/conf}) {
                   12351:                     if ($webconfdir eq '/etc/apache2') {
                   12352:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   12353:                     }
                   12354:                 }
1.1172.2.34  raeburn  12355:                 $chksum{$file} = $shasum;
                   12356:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  12357:             }
                   12358:             if (ref($hashref) eq 'HASH') {
                   12359:                 %{$hashref} = (
                   12360:                                 sums     => \%chksum,
                   12361:                                 versions => \%revnum,
                   12362:                               );
                   12363:             }
                   12364:         }
                   12365:     }
1.869     albertel 12366:     return;
1.852     albertel 12367: }
1.1172.2.17  raeburn  12368: 
                   12369: sub fetch_dns_checksums {
                   12370:     my %checksums;
1.1172.2.34  raeburn  12371:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48  raeburn  12372:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34  raeburn  12373:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   12374:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  12375:              \%checksums);
                   12376:     return \%checksums;
                   12377: }
                   12378: 
1.327     albertel 12379: # ------------------------------------------------------------ Read domain file
                   12380: {
1.852     albertel 12381:     my $loaded;
1.846     albertel 12382:     my %domain;
                   12383: 
1.852     albertel 12384:     sub parse_domain_tab {
                   12385: 	my ($lines) = @_;
                   12386: 	foreach my $line (@$lines) {
                   12387: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      12388: 
1.846     albertel 12389: 	    chomp($line);
1.852     albertel 12390: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 12391: 	    my %this_domain;
                   12392: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   12393: 			       'lang_def', 'city', 'longi', 'lati',
                   12394: 			       'primary') {
                   12395: 		$this_domain{$field} = shift(@elements);
                   12396: 	    }
                   12397: 	    $domain{$name} = \%this_domain;
1.852     albertel 12398: 	}
                   12399:     }
1.864     albertel 12400: 
                   12401:     sub reset_domain_info {
                   12402: 	undef($loaded);
                   12403: 	undef(%domain);
                   12404:     }
                   12405: 
1.852     albertel 12406:     sub load_domain_tab {
1.1172.2.70  raeburn  12407: 	my ($ignore_cache,$nocache) = @_;
                   12408: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 12409: 	my $fh;
                   12410: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   12411: 	    my @lines = <$fh>;
                   12412: 	    &parse_domain_tab(\@lines);
1.448     albertel 12413: 	}
1.852     albertel 12414: 	close($fh);
                   12415: 	$loaded = 1;
1.327     albertel 12416:     }
1.846     albertel 12417: 
                   12418:     sub domain {
1.852     albertel 12419: 	&load_domain_tab() if (!$loaded);
                   12420: 
1.846     albertel 12421: 	my ($name,$what) = @_;
                   12422: 	return if ( !exists($domain{$name}) );
                   12423: 
                   12424: 	if (!$what) {
                   12425: 	    return $domain{$name}{'description'};
                   12426: 	}
                   12427: 	return $domain{$name}{$what};
                   12428:     }
1.974     raeburn  12429: 
                   12430:     sub domain_info {
                   12431:         &load_domain_tab() if (!$loaded);
                   12432:         return %domain;
                   12433:     }
                   12434: 
1.327     albertel 12435: }
                   12436: 
                   12437: 
1.1       albertel 12438: # ------------------------------------------------------------- Read hosts file
                   12439: {
1.838     albertel 12440:     my %hostname;
1.844     albertel 12441:     my %hostdom;
1.845     albertel 12442:     my %libserv;
1.852     albertel 12443:     my $loaded;
1.888     albertel 12444:     my %name_to_host;
1.1074    raeburn  12445:     my %internetdom;
1.1107    raeburn  12446:     my %LC_dns_serv;
1.852     albertel 12447: 
                   12448:     sub parse_hosts_tab {
                   12449: 	my ($file) = @_;
                   12450: 	foreach my $configline (@$file) {
                   12451: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  12452:             chomp($configline);
                   12453: 	    if ($configline =~ /^\^/) {
                   12454:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   12455:                     $LC_dns_serv{$1} = 1;
                   12456:                 }
                   12457:                 next;
                   12458:             }
1.1074    raeburn  12459: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 12460: 	    $name=~s/\s//g;
                   12461: 	    if ($id && $domain && $role && $name) {
                   12462: 		$hostname{$id}=$name;
1.888     albertel 12463: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 12464: 		$hostdom{$id}=$domain;
                   12465: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  12466:                 if (defined($protocol)) {
                   12467:                     if ($protocol eq 'https') {
                   12468:                         $protocol{$id} = $protocol;
                   12469:                     } else {
                   12470:                         $protocol{$id} = 'http'; 
                   12471:                     }
1.968     raeburn  12472:                 } else {
1.969     raeburn  12473:                     $protocol{$id} = 'http';
1.968     raeburn  12474:                 }
1.1074    raeburn  12475:                 if (defined($intdom)) {
                   12476:                     $internetdom{$id} = $intdom;
                   12477:                 }
1.852     albertel 12478: 	    }
                   12479: 	}
                   12480:     }
1.864     albertel 12481:     
                   12482:     sub reset_hosts_info {
1.897     albertel 12483: 	&purge_remembered();
1.864     albertel 12484: 	&reset_domain_info();
                   12485: 	&reset_hosts_ip_info();
1.892     albertel 12486: 	undef(%name_to_host);
1.864     albertel 12487: 	undef(%hostname);
                   12488: 	undef(%hostdom);
                   12489: 	undef(%libserv);
                   12490: 	undef($loaded);
                   12491:     }
1.1       albertel 12492: 
1.852     albertel 12493:     sub load_hosts_tab {
1.1172.2.70  raeburn  12494: 	my ($ignore_cache,$nocache) = @_;
                   12495: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.852     albertel 12496: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   12497: 	my @config = <$config>;
                   12498: 	&parse_hosts_tab(\@config);
                   12499: 	close($config);
                   12500: 	$loaded=1;
1.1       albertel 12501:     }
1.852     albertel 12502: 
1.838     albertel 12503:     sub hostname {
1.852     albertel 12504: 	&load_hosts_tab() if (!$loaded);
                   12505: 
1.838     albertel 12506: 	my ($lonid) = @_;
                   12507: 	return $hostname{$lonid};
                   12508:     }
1.845     albertel 12509: 
1.838     albertel 12510:     sub all_hostnames {
1.852     albertel 12511: 	&load_hosts_tab() if (!$loaded);
                   12512: 
1.838     albertel 12513: 	return %hostname;
                   12514:     }
1.845     albertel 12515: 
1.888     albertel 12516:     sub all_names {
1.1172.2.70  raeburn  12517:         my ($ignore_cache,$nocache) = @_;
                   12518: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 12519: 
                   12520: 	return %name_to_host;
                   12521:     }
                   12522: 
1.974     raeburn  12523:     sub all_host_domain {
                   12524:         &load_hosts_tab() if (!$loaded);
                   12525:         return %hostdom;
                   12526:     }
                   12527: 
1.845     albertel 12528:     sub is_library {
1.852     albertel 12529: 	&load_hosts_tab() if (!$loaded);
                   12530: 
1.845     albertel 12531: 	return exists($libserv{$_[0]});
                   12532:     }
                   12533: 
                   12534:     sub all_library {
1.852     albertel 12535: 	&load_hosts_tab() if (!$loaded);
                   12536: 
1.845     albertel 12537: 	return %libserv;
                   12538:     }
                   12539: 
1.1062    droeschl 12540:     sub unique_library {
                   12541: 	#2x reverse removes all hostnames that appear more than once
                   12542:         my %unique = reverse &all_library();
                   12543:         return reverse %unique;
                   12544:     }
                   12545: 
1.841     albertel 12546:     sub get_servers {
1.852     albertel 12547: 	&load_hosts_tab() if (!$loaded);
                   12548: 
1.841     albertel 12549: 	my ($domain,$type) = @_;
                   12550: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   12551: 	                                          : %hostname;
                   12552: 	my %result;
1.842     albertel 12553: 	if (ref($domain) eq 'ARRAY') {
                   12554: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 12555: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 12556: 		    $result{$host} = $hostname;
                   12557: 		}
                   12558: 	    }
                   12559: 	} else {
                   12560: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   12561: 		if ($hostdom{$host} eq $domain) {
                   12562: 		    $result{$host} = $hostname;
                   12563: 		}
1.841     albertel 12564: 	    }
                   12565: 	}
                   12566: 	return %result;
                   12567:     }
1.845     albertel 12568: 
1.1062    droeschl 12569:     sub get_unique_servers {
                   12570:         my %unique = reverse &get_servers(@_);
                   12571: 	return reverse %unique;
                   12572:     }
                   12573: 
1.844     albertel 12574:     sub host_domain {
1.852     albertel 12575: 	&load_hosts_tab() if (!$loaded);
                   12576: 
1.844     albertel 12577: 	my ($lonid) = @_;
                   12578: 	return $hostdom{$lonid};
                   12579:     }
                   12580: 
1.841     albertel 12581:     sub all_domains {
1.852     albertel 12582: 	&load_hosts_tab() if (!$loaded);
                   12583: 
1.841     albertel 12584: 	my %seen;
                   12585: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   12586: 	return @uniq;
                   12587:     }
1.1074    raeburn  12588: 
                   12589:     sub internet_dom {
                   12590:         &load_hosts_tab() if (!$loaded);
                   12591: 
                   12592:         my ($lonid) = @_;
                   12593:         return $internetdom{$lonid};
                   12594:     }
1.1107    raeburn  12595: 
                   12596:     sub is_LC_dns {
                   12597:         &load_hosts_tab() if (!$loaded);
                   12598: 
                   12599:         my ($hostname) = @_;
                   12600:         return exists($LC_dns_serv{$hostname});
                   12601:     }
                   12602: 
1.1       albertel 12603: }
                   12604: 
1.847     albertel 12605: { 
                   12606:     my %iphost;
1.856     albertel 12607:     my %name_to_ip;
                   12608:     my %lonid_to_ip;
1.869     albertel 12609: 
1.847     albertel 12610:     sub get_hosts_from_ip {
                   12611: 	my ($ip) = @_;
                   12612: 	my %iphosts = &get_iphost();
                   12613: 	if (ref($iphosts{$ip})) {
                   12614: 	    return @{$iphosts{$ip}};
                   12615: 	}
                   12616: 	return;
1.839     albertel 12617:     }
1.864     albertel 12618:     
                   12619:     sub reset_hosts_ip_info {
                   12620: 	undef(%iphost);
                   12621: 	undef(%name_to_ip);
                   12622: 	undef(%lonid_to_ip);
                   12623:     }
1.856     albertel 12624: 
                   12625:     sub get_host_ip {
                   12626: 	my ($lonid) = @_;
                   12627: 	if (exists($lonid_to_ip{$lonid})) {
                   12628: 	    return $lonid_to_ip{$lonid};
                   12629: 	}
                   12630: 	my $name=&hostname($lonid);
                   12631:    	my $ip = gethostbyname($name);
                   12632: 	return if (!$ip || length($ip) ne 4);
                   12633: 	$ip=inet_ntoa($ip);
                   12634: 	$name_to_ip{$name}   = $ip;
                   12635: 	$lonid_to_ip{$lonid} = $ip;
                   12636: 	return $ip;
                   12637:     }
1.847     albertel 12638:     
                   12639:     sub get_iphost {
1.1172.2.70  raeburn  12640: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 12641: 
1.869     albertel 12642: 	if (!$ignore_cache) {
                   12643: 	    if (%iphost) {
                   12644: 		return %iphost;
                   12645: 	    }
                   12646: 	    my ($ip_info,$cached)=
                   12647: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   12648: 	    if ($cached) {
                   12649: 		%iphost      = %{$ip_info->[0]};
                   12650: 		%name_to_ip  = %{$ip_info->[1]};
                   12651: 		%lonid_to_ip = %{$ip_info->[2]};
                   12652: 		return %iphost;
                   12653: 	    }
                   12654: 	}
1.894     albertel 12655: 
                   12656: 	# get yesterday's info for fallback
                   12657: 	my %old_name_to_ip;
                   12658: 	my ($ip_info,$cached)=
                   12659: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   12660: 	if ($cached) {
                   12661: 	    %old_name_to_ip = %{$ip_info->[1]};
                   12662: 	}
                   12663: 
1.1172.2.70  raeburn  12664: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 12665: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 12666: 	    my $ip;
                   12667: 	    if (!exists($name_to_ip{$name})) {
                   12668: 		$ip = gethostbyname($name);
                   12669: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 12670: 		    if (defined($old_name_to_ip{$name})) {
                   12671: 			$ip = $old_name_to_ip{$name};
                   12672: 			&logthis("Can't find $name defaulting to old $ip");
                   12673: 		    } else {
                   12674: 			&logthis("Name $name no IP found");
                   12675: 			next;
                   12676: 		    }
                   12677: 		} else {
                   12678: 		    $ip=inet_ntoa($ip);
1.847     albertel 12679: 		}
                   12680: 		$name_to_ip{$name} = $ip;
                   12681: 	    } else {
                   12682: 		$ip = $name_to_ip{$name};
1.653     albertel 12683: 	    }
1.888     albertel 12684: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   12685: 		$lonid_to_ip{$id} = $ip;
                   12686: 	    }
                   12687: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 12688: 	}
1.1172.2.70  raeburn  12689:         unless ($nocache) {
                   12690: 	    &do_cache_new('iphost','iphost',
                   12691: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   12692: 		          48*60*60);
                   12693:         }
1.869     albertel 12694: 
1.847     albertel 12695: 	return %iphost;
1.598     albertel 12696:     }
                   12697: 
1.992     raeburn  12698:     #
                   12699:     #  Given a DNS returns the loncapa host name for that DNS 
                   12700:     # 
                   12701:     sub host_from_dns {
                   12702:         my ($dns) = @_;
                   12703:         my @hosts;
                   12704:         my $ip;
                   12705: 
1.993     raeburn  12706:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  12707:             $ip = $name_to_ip{$dns};
                   12708:         }
                   12709:         if (!$ip) {
                   12710:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   12711:             if (length($ip) == 4) { 
                   12712: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   12713:             }
                   12714:         }
                   12715:         if ($ip) {
                   12716: 	    @hosts = get_hosts_from_ip($ip);
                   12717: 	    return $hosts[0];
                   12718:         }
                   12719:         return undef;
1.986     foxr     12720:     }
1.992     raeburn  12721: 
1.1074    raeburn  12722:     sub get_internet_names {
                   12723:         my ($lonid) = @_;
                   12724:         return if ($lonid eq '');
                   12725:         my ($idnref,$cached)=
                   12726:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   12727:         if ($cached) {
                   12728:             return $idnref;
                   12729:         }
                   12730:         my $ip = &get_host_ip($lonid);
                   12731:         my @hosts = &get_hosts_from_ip($ip);
                   12732:         my %iphost = &get_iphost();
                   12733:         my (@idns,%seen);
                   12734:         foreach my $id (@hosts) {
                   12735:             my $dom = &host_domain($id);
                   12736:             my $prim_id = &domain($dom,'primary');
                   12737:             my $prim_ip = &get_host_ip($prim_id);
                   12738:             next if ($seen{$prim_ip});
                   12739:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   12740:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   12741:                     my $intdom = &internet_dom($id);
                   12742:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   12743:                         push(@idns,$intdom);
                   12744:                     }
                   12745:                 }
                   12746:             }
                   12747:             $seen{$prim_ip} = 1;
                   12748:         }
1.1172.2.23  raeburn  12749:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  12750:     }
                   12751: 
1.986     foxr     12752: }
                   12753: 
1.1079    raeburn  12754: sub all_loncaparevs {
1.1172.2.39  raeburn  12755:     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  12756: }
                   12757: 
1.1172.2.27  raeburn  12758: # ------------------------------------------------------- Read loncaparev table
                   12759: {
                   12760:     sub load_loncaparevs {
                   12761:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   12762:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   12763:                 while (my $configline=<$config>) {
                   12764:                     chomp($configline);
                   12765:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   12766:                     $loncaparevs{$hostid}=$loncaparev;
                   12767:                 }
                   12768:                 close($config);
                   12769:             }
                   12770:         }
                   12771:     }
                   12772: }
                   12773: 
                   12774: # ----------------------------------------------------- Read serverhostID table
                   12775: {
                   12776:     sub load_serverhomeIDs {
                   12777:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   12778:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   12779:                 while (my $configline=<$config>) {
                   12780:                     chomp($configline);
                   12781:                     my ($name,$id)=split(/:/,$configline);
                   12782:                     $serverhomeIDs{$name}=$id;
                   12783:                 }
                   12784:                 close($config);
                   12785:             }
                   12786:         }
                   12787:     }
                   12788: }
                   12789: 
                   12790: 
1.862     albertel 12791: BEGIN {
                   12792: 
                   12793: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   12794:     unless ($readit) {
                   12795: {
                   12796:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   12797:     %perlvar = (%perlvar,%{$configvars});
                   12798: }
                   12799: 
                   12800: 
1.1       albertel 12801: # ------------------------------------------------------ Read spare server file
                   12802: {
1.448     albertel 12803:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 12804: 
                   12805:     while (my $configline=<$config>) {
                   12806:        chomp($configline);
1.284     matthew  12807:        if ($configline) {
1.784     albertel 12808: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 12809: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 12810: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 12811:        }
                   12812:     }
1.448     albertel 12813:     close($config);
1.1       albertel 12814: }
1.11      www      12815: # ------------------------------------------------------------ Read permissions
                   12816: {
1.448     albertel 12817:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      12818: 
                   12819:     while (my $configline=<$config>) {
1.448     albertel 12820: 	chomp($configline);
                   12821: 	if ($configline) {
                   12822: 	    my ($role,$perm)=split(/ /,$configline);
                   12823: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   12824: 	}
1.11      www      12825:     }
1.448     albertel 12826:     close($config);
1.11      www      12827: }
                   12828: 
                   12829: # -------------------------------------------- Read plain texts for permissions
                   12830: {
1.448     albertel 12831:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      12832: 
                   12833:     while (my $configline=<$config>) {
1.448     albertel 12834: 	chomp($configline);
                   12835: 	if ($configline) {
1.742     raeburn  12836: 	    my ($short,@plain)=split(/:/,$configline);
                   12837:             %{$prp{$short}} = ();
                   12838: 	    if (@plain > 0) {
                   12839:                 $prp{$short}{'std'} = $plain[0];
                   12840:                 for (my $i=1; $i<@plain; $i++) {
                   12841:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   12842:                 }
                   12843:             }
1.448     albertel 12844: 	}
1.135     www      12845:     }
1.448     albertel 12846:     close($config);
1.135     www      12847: }
                   12848: 
                   12849: # ---------------------------------------------------------- Read package table
                   12850: {
1.448     albertel 12851:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      12852: 
                   12853:     while (my $configline=<$config>) {
1.483     albertel 12854: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 12855: 	chomp($configline);
                   12856: 	my ($short,$plain)=split(/:/,$configline);
                   12857: 	my ($pack,$name)=split(/\&/,$short);
                   12858: 	if ($plain ne '') {
                   12859: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   12860: 	    $packagetab{$short}=$plain; 
                   12861: 	}
1.11      www      12862:     }
1.448     albertel 12863:     close($config);
1.329     matthew  12864: }
                   12865: 
1.1172.2.27  raeburn  12866: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  12867: 
1.1172.2.27  raeburn  12868: &load_loncaparevs();
                   12869: 
                   12870: # ------------------------------------------------------- Read serverhostID table
                   12871: 
                   12872: &load_serverhomeIDs();
1.1074    raeburn  12873: 
1.1172.2.27  raeburn  12874: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  12875: {
                   12876:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   12877:     if (-e $file) {
                   12878:         my $parser = HTML::LCParser->new($file);
                   12879:         while (my $token = $parser->get_token()) {
                   12880:             if ($token->[0] eq 'S') {
                   12881:                 my $item = $token->[1];
                   12882:                 my $name = $token->[2]{'name'};
                   12883:                 my $value = $token->[2]{'value'};
                   12884:                 if ($item ne '' && $name ne '' && $value ne '') {
                   12885:                     my $release = $parser->get_text();
                   12886:                     $release =~ s/(^\s*|\s*$ )//gx;
                   12887:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   12888:                 }
                   12889:             }
                   12890:         }
                   12891:     }
1.1073    raeburn  12892: }
                   12893: 
1.1138    raeburn  12894: # ---------------------------------------------------------- Read managers table
                   12895: {
                   12896:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   12897:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   12898:             while (my $configline=<$config>) {
                   12899:                 chomp($configline);
                   12900:                 next if ($configline =~ /^\#/);
                   12901:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   12902:                     $managerstab{$configline} = 1;
                   12903:                 }
                   12904:             }
                   12905:             close($config);
                   12906:         }
                   12907:     }
                   12908: }
                   12909: 
1.329     matthew  12910: # ------------- set up temporary directory
                   12911: {
1.1117    foxr     12912:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  12913: 
1.11      www      12914: }
                   12915: 
1.794     albertel 12916: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   12917: 				'compress_threshold'=> 20_000,
                   12918:  			        });
1.185     www      12919: 
1.281     www      12920: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      12921: $dumpcount=0;
1.958     www      12922: $locknum=0;
1.22      www      12923: 
1.163     harris41 12924: &logtouch();
1.672     albertel 12925: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      12926: $readit=1;
1.564     albertel 12927:     {
                   12928: 	use integer;
                   12929: 	my $test=(2**32)+1;
1.568     albertel 12930: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 12931: 	&logthis(" Detected 64bit platform ($_64bit)");
                   12932:     }
1.195     www      12933: }
1.1       albertel 12934: }
1.179     www      12935: 
1.1       albertel 12936: 1;
1.191     harris41 12937: __END__
                   12938: 
1.243     albertel 12939: =pod
                   12940: 
1.191     harris41 12941: =head1 NAME
                   12942: 
1.243     albertel 12943: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 12944: 
                   12945: =head1 SYNOPSIS
                   12946: 
1.243     albertel 12947: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 12948: 
                   12949:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   12950: 
1.243     albertel 12951: Common parameters:
                   12952: 
                   12953: =over 4
                   12954: 
                   12955: =item *
                   12956: 
                   12957: $uname : an internal username (if $cname expecting a course Id specifically)
                   12958: 
                   12959: =item *
                   12960: 
                   12961: $udom : a domain (if $cdom expecting a course's domain specifically)
                   12962: 
                   12963: =item *
                   12964: 
                   12965: $symb : a resource instance identifier
                   12966: 
                   12967: =item *
                   12968: 
                   12969: $namespace : the name of a .db file that contains the data needed or
                   12970: being set.
                   12971: 
                   12972: =back
                   12973: 
1.394     bowersj2 12974: =head1 OVERVIEW
1.191     harris41 12975: 
1.394     bowersj2 12976: lonnet provides subroutines which interact with the
                   12977: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   12978: about classes, users, and resources.
1.243     albertel 12979: 
                   12980: For many of these objects you can also use this to store data about
                   12981: them or modify them in various ways.
1.191     harris41 12982: 
1.394     bowersj2 12983: =head2 Symbs
1.191     harris41 12984: 
1.394     bowersj2 12985: To identify a specific instance of a resource, LON-CAPA uses symbols
                   12986: or "symbs"X<symb>. These identifiers are built from the URL of the
                   12987: map, the resource number of the resource in the map, and the URL of
                   12988: the resource itself. The latter is somewhat redundant, but might help
                   12989: if maps change.
                   12990: 
                   12991: An example is
                   12992: 
                   12993:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   12994: 
                   12995: The respective map entry is
                   12996: 
                   12997:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   12998:   title="Problem 2">
                   12999:  </resource>
                   13000: 
                   13001: Symbs are used by the random number generator, as well as to store and
                   13002: restore data specific to a certain instance of for example a problem.
                   13003: 
                   13004: =head2 Storing And Retrieving Data
                   13005: 
                   13006: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   13007: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   13008: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   13009: is is the non-critical message twin of cstore. These functions are for
                   13010: handlers to store a perl hash to a user's permanent data space in an
                   13011: easy manner, and to retrieve it again on another call. It is expected
                   13012: that a handler would use this once at the beginning to retrieve data,
                   13013: and then again once at the end to send only the new data back.
                   13014: 
                   13015: The data is stored in the user's data directory on the user's
                   13016: homeserver under the ID of the course.
                   13017: 
                   13018: The hash that is returned by restore will have all of the previous
                   13019: value for all of the elements of the hash.
                   13020: 
                   13021: Example:
                   13022: 
                   13023:  #creating a hash
                   13024:  my %hash;
                   13025:  $hash{'foo'}='bar';
                   13026: 
                   13027:  #storing it
                   13028:  &Apache::lonnet::cstore(\%hash);
                   13029: 
                   13030:  #changing a value
                   13031:  $hash{'foo'}='notbar';
                   13032: 
                   13033:  #adding a new value
                   13034:  $hash{'bar'}='foo';
                   13035:  &Apache::lonnet::cstore(\%hash);
                   13036: 
                   13037:  #retrieving the hash
                   13038:  my %history=&Apache::lonnet::restore();
                   13039: 
                   13040:  #print the hash
                   13041:  foreach my $key (sort(keys(%history))) {
                   13042:    print("\%history{$key} = $history{$key}");
                   13043:  }
                   13044: 
                   13045: Will print out:
1.191     harris41 13046: 
1.394     bowersj2 13047:  %history{1:foo} = bar
                   13048:  %history{1:keys} = foo:timestamp
                   13049:  %history{1:timestamp} = 990455579
                   13050:  %history{2:bar} = foo
                   13051:  %history{2:foo} = notbar
                   13052:  %history{2:keys} = foo:bar:timestamp
                   13053:  %history{2:timestamp} = 990455580
                   13054:  %history{bar} = foo
                   13055:  %history{foo} = notbar
                   13056:  %history{timestamp} = 990455580
                   13057:  %history{version} = 2
                   13058: 
                   13059: Note that the special hash entries C<keys>, C<version> and
                   13060: C<timestamp> were added to the hash. C<version> will be equal to the
                   13061: total number of versions of the data that have been stored. The
                   13062: C<timestamp> attribute will be the UNIX time the hash was
                   13063: stored. C<keys> is available in every historical section to list which
                   13064: keys were added or changed at a specific historical revision of a
                   13065: hash.
                   13066: 
                   13067: B<Warning>: do not store the hash that restore returns directly. This
                   13068: will cause a mess since it will restore the historical keys as if the
                   13069: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 13070: 
1.394     bowersj2 13071: Calling convention:
1.191     harris41 13072: 
1.1172.2.27  raeburn  13073:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64  raeburn  13074:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 13075: 
1.394     bowersj2 13076: For more detailed information, see lonnet specific documentation.
1.191     harris41 13077: 
1.394     bowersj2 13078: =head1 RETURN MESSAGES
1.191     harris41 13079: 
1.394     bowersj2 13080: =over 4
1.191     harris41 13081: 
1.394     bowersj2 13082: =item * B<con_lost>: unable to contact remote host
1.191     harris41 13083: 
1.394     bowersj2 13084: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   13085: when the connection is brought back up
1.191     harris41 13086: 
1.394     bowersj2 13087: =item * B<con_failed>: unable to contact remote host and unable to save message
                   13088: for later delivery
1.191     harris41 13089: 
1.967     bisitz   13090: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 13091: 
1.394     bowersj2 13092: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 13093: that was requested
1.191     harris41 13094: 
1.243     albertel 13095: =back
1.191     harris41 13096: 
1.243     albertel 13097: =head1 PUBLIC SUBROUTINES
1.191     harris41 13098: 
1.243     albertel 13099: =head2 Session Environment Functions
1.191     harris41 13100: 
1.243     albertel 13101: =over 4
1.191     harris41 13102: 
1.394     bowersj2 13103: =item * 
                   13104: X<appenv()>
1.949     raeburn  13105: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 13106: the user envirnoment file, and will be restored for each access this
1.620     albertel 13107: user makes during this session, also modifies the %env for the current
1.949     raeburn  13108: process. Optional rolesarrayref - if defined contains a reference to an array
                   13109: of roles which are exempt from the restriction on modifying user.role entries 
                   13110: in the user's environment.db and in %env.    
1.191     harris41 13111: 
                   13112: =item *
1.394     bowersj2 13113: X<delenv()>
1.987     raeburn  13114: B<delenv($delthis,$regexp)>: removes all items from the session
                   13115: environment file that begin with $delthis. If the 
                   13116: optional second arg - $regexp - is true, $delthis is treated as a 
                   13117: regular expression, otherwise \Q$delthis\E is used. 
                   13118: The values are also deleted from the current processes %env.
1.191     harris41 13119: 
1.795     albertel 13120: =item * get_env_multiple($name) 
                   13121: 
                   13122: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   13123: values may be defined and end up as an array ref.
                   13124: 
                   13125: returns an array of values
                   13126: 
1.243     albertel 13127: =back
                   13128: 
                   13129: =head2 User Information
1.191     harris41 13130: 
1.243     albertel 13131: =over 4
1.191     harris41 13132: 
                   13133: =item *
1.394     bowersj2 13134: X<queryauthenticate()>
                   13135: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 13136: authentication scheme
                   13137: 
                   13138: =item *
1.394     bowersj2 13139: X<authenticate()>
1.1073    raeburn  13140: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 13141: authenticate user from domain's lib servers (first use the current
                   13142: one). C<$upass> should be the users password.
1.1073    raeburn  13143: $checkdefauth is optional (value is 1 if a check should be made to
                   13144:    authenticate user using default authentication method, and allow
                   13145:    account creation if username does not have account in the domain).
                   13146: $clientcancheckhost is optional (value is 1 if checking whether the
                   13147:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 13148: 
                   13149: =item *
1.394     bowersj2 13150: X<homeserver()>
                   13151: B<homeserver($uname,$udom)>: find the server which has
                   13152: the user's directory and files (there must be only one), this caches
                   13153: the answer, and also caches if there is a borken connection.
1.191     harris41 13154: 
                   13155: =item *
1.394     bowersj2 13156: X<idget()>
                   13157: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   13158: (IDs are a unique resource in a domain, there must be only 1 ID per
                   13159: username, and only 1 username per ID in a specific domain) (returns
                   13160: hash: id=>name,id=>name)
1.191     harris41 13161: 
                   13162: =item *
1.394     bowersj2 13163: X<idrget()>
                   13164: B<idrget($udom,@unames)>: find the IDs behind a list of
                   13165: usernames (returns hash: name=>id,name=>id)
1.191     harris41 13166: 
                   13167: =item *
1.394     bowersj2 13168: X<idput()>
                   13169: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 13170: 
                   13171: =item *
1.394     bowersj2 13172: X<rolesinit()>
1.1169    droeschl 13173: B<rolesinit($udom,$username)>: get user privileges.
                   13174: returns user role, first access and timer interval hashes
1.243     albertel 13175: 
                   13176: =item *
1.1171    droeschl 13177: X<privileged()>
                   13178: B<privileged($username,$domain)>: returns a true if user has a
                   13179: privileged and active role (i.e. su or dc), false otherwise.
                   13180: 
                   13181: =item *
1.551     albertel 13182: X<getsection()>
                   13183: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 13184: course $cname, return section name/number or '' for "not in course"
                   13185: and '-1' for "no section"
                   13186: 
                   13187: =item *
1.394     bowersj2 13188: X<userenvironment()>
                   13189: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 13190: passed in @what from the requested user's environment, returns a hash
                   13191: 
1.858     raeburn  13192: =item * 
                   13193: X<userlog_query()>
1.859     albertel 13194: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   13195: activity.log file. %filters defines filters applied when parsing the
                   13196: log file. These can be start or end timestamps, or the type of action
                   13197: - log to look for Login or Logout events, check for Checkin or
                   13198: Checkout, role for role selection. The response is in the form
                   13199: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   13200: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  13201: 
1.243     albertel 13202: =back
                   13203: 
                   13204: =head2 User Roles
                   13205: 
                   13206: =over 4
                   13207: 
                   13208: =item *
                   13209: 
1.1172.2.65  raeburn  13210: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   13211: returns codes for allowed actions.
                   13212: 
                   13213: The first argument is required, all others are optional.
                   13214: 
                   13215: $priv is the privilege being checked.
                   13216: $uri contains additional information about what is being checked for access (e.g.,
                   13217: URL, course ID etc.).
                   13218: $symb is the unique resource instance identifier in a course; if needed,
                   13219: but not provided, it will be retrieved via a call to &symbread().
                   13220: $role is the role for which a priv is being checked (only used if priv is evb).
                   13221: $clientip is the user's IP address (only used when checking for access to portfolio
                   13222: files).
                   13223: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
                   13224: prevents recursive calls to &allowed.
                   13225: 
1.243     albertel 13226:  F: full access
                   13227:  U,I,K: authentication modes (cxx only)
                   13228:  '': forbidden
                   13229:  1: user needs to choose course
                   13230:  2: browse allowed
1.766     albertel 13231:  A: passphrase authentication needed
1.1172.2.65  raeburn  13232:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 13233: 
                   13234: =item *
                   13235: 
1.1172.2.13  raeburn  13236: constructaccess($url,$setpriv) : check for access to construction space URL
                   13237: 
                   13238: See if the owner domain and name in the URL match those in the
                   13239: expected environment.  If so, return three element list
                   13240: ($ownername,$ownerdomain,$ownerhome).
                   13241: 
                   13242: Otherwise return the null string.
                   13243: 
                   13244: If second argument 'setpriv' is true, it assigns the privileges,
                   13245: and returns the same three element list, unless the owner has
                   13246: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   13247: in which case the null string is returned.
                   13248: 
                   13249: =item *
                   13250: 
1.1172.2.84  raeburn  13251: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   13252: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   13253: for system, domain, and course level. $uname and $udom are optional (current
                   13254: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 13255: 
                   13256: =item *
                   13257: 
1.988     raeburn  13258: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   13259: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  13260: $type is Course (default) or Community.
1.988     raeburn  13261: If $forcedefault evaluates to true, text returned will be default 
                   13262: text for $type. Otherwise, if this is a course, the text returned 
                   13263: will be a custom name for the role (if defined in the course's 
                   13264: environment).  If no custom name is defined the default is returned.
                   13265:    
1.832     raeburn  13266: =item *
                   13267: 
1.1172.2.23  raeburn  13268: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  13269: All arguments are optional. Returns a hash of a roles, either for
                   13270: co-author/assistant author roles for a user's Construction Space
1.906     albertel 13271: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  13272: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   13273: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   13274: For each key, value is set to colon-separated start and end times for
                   13275: the role.  If no username and domain are specified, will default to
1.934     raeburn  13276: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  13277: of role statuses (active, future or previous), roles 
                   13278: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   13279: to restrict the list of roles reported. If no array ref is 
                   13280: provided for types, will default to return only active roles.
1.834     albertel 13281: 
1.1172.2.13  raeburn  13282: =item *
                   13283: 
                   13284: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   13285: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   13286: 
                   13287: Additional optional arguments are: $type (if role checking is to be restricted
                   13288: to certain user status types -- previous (expired roles), active (currently
                   13289: available roles) or future (roles available in the future), and
                   13290: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  13291: have active Domain Coordinator role in course's domain or in additional
                   13292: domains (specified in 'Domains to check for privileged users' in course
                   13293: environment -- set via:  Course Settings -> Classlists and staff listing).
                   13294: 
                   13295: =item *
                   13296: 
                   13297: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   13298: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   13299: $possdomains and $possroles are optional array refs -- to domains to check and
                   13300: roles to check.  If $possdomains is not specified, a dump will be done of the
                   13301: users' roles.db to check for a dc or su role in any domain. This can be
                   13302: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   13303: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   13304: this then allows &privileged_by_domain() to be used, which caches the identity
                   13305: of privileged users, eliminating the need for repeated calls to &dump().
                   13306: 
                   13307: =item *
                   13308: 
                   13309: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   13310: where the outer hash keys are domains specified in the $possdomains array ref,
                   13311: next inner hash keys are privileged roles specified in the $roles array ref,
                   13312: and the innermost hash contains key = value pairs for username:domain = end:start
                   13313: for active or future "privileged" users with that role in that domain. To avoid
                   13314: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   13315: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  13316: 
1.243     albertel 13317: =back
                   13318: 
                   13319: =head2 User Modification
                   13320: 
                   13321: =over 4
                   13322: 
                   13323: =item *
                   13324: 
1.957     raeburn  13325: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 13326: user for the level given by URL.  Optional start and end dates (leave empty
                   13327: string or zero for "no date")
1.191     harris41 13328: 
                   13329: =item *
                   13330: 
1.243     albertel 13331: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   13332: change a users, password, possible return values are: ok,
                   13333: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   13334: refused
1.191     harris41 13335: 
                   13336: =item *
                   13337: 
1.243     albertel 13338: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 13339: 
                   13340: =item *
                   13341: 
1.1058    raeburn  13342: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   13343:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   13344: 
                   13345: will update user information (firstname,middlename,lastname,generation,
                   13346: permanentemail), and if forceid is true, student/employee ID also.
                   13347: A user's institutional affiliation(s) can also be updated.
                   13348: User information fields will not be overwritten with empty entries 
                   13349: unless the field is included in the $candelete array reference.
                   13350: This array is included when a single user is modified via "Manage Users",
                   13351: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 13352: 
                   13353: =item *
                   13354: 
1.286     matthew  13355: modifystudent
                   13356: 
1.957     raeburn  13357: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  13358: The course id is resolved based on the current user's environment.  
                   13359: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  13360: associated with a course.
                   13361: 
1.297     matthew  13362: This call is essentially a wrapper for lonnet::modifyuser and
                   13363: lonnet::modify_student_enrollment
1.286     matthew  13364: 
                   13365: Inputs: 
                   13366: 
                   13367: =over 4
                   13368: 
1.957     raeburn  13369: =item B<$udom> Student's loncapa domain
1.286     matthew  13370: 
1.957     raeburn  13371: =item B<$uname> Student's loncapa login name
1.286     matthew  13372: 
1.964     bisitz   13373: =item B<$uid> Student/Employee ID
1.286     matthew  13374: 
1.957     raeburn  13375: =item B<$umode> Student's authentication mode
1.286     matthew  13376: 
1.957     raeburn  13377: =item B<$upass> Student's password
1.286     matthew  13378: 
1.957     raeburn  13379: =item B<$first> Student's first name
1.286     matthew  13380: 
1.957     raeburn  13381: =item B<$middle> Student's middle name
1.286     matthew  13382: 
1.957     raeburn  13383: =item B<$last> Student's last name
1.286     matthew  13384: 
1.957     raeburn  13385: =item B<$gene> Student's generation
1.286     matthew  13386: 
1.957     raeburn  13387: =item B<$usec> Student's section in course
1.286     matthew  13388: 
                   13389: =item B<$end> Unix time of the roles expiration
                   13390: 
                   13391: =item B<$start> Unix time of the roles start date
                   13392: 
                   13393: =item B<$forceid> If defined, allow $uid to be changed
                   13394: 
                   13395: =item B<$desiredhome> server to use as home server for student
                   13396: 
1.957     raeburn  13397: =item B<$email> Student's permanent e-mail address
                   13398: 
                   13399: =item B<$type> Type of enrollment (auto or manual)
                   13400: 
1.963     raeburn  13401: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   13402: 
                   13403: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  13404: 
1.963     raeburn  13405: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  13406: 
1.963     raeburn  13407: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  13408: 
1.1172.2.19  raeburn  13409: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   13410: 
                   13411: =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  13412: 
1.286     matthew  13413: =back
1.297     matthew  13414: 
                   13415: =item *
                   13416: 
                   13417: modify_student_enrollment
                   13418: 
1.1172.2.31  raeburn  13419: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  13420: 'role.request.course' must be defined for this function to proceed.
                   13421: 
                   13422: Inputs:
                   13423: 
                   13424: =over 4
                   13425: 
1.1172.2.31  raeburn  13426: =item $udom, student's domain
1.297     matthew  13427: 
1.1172.2.31  raeburn  13428: =item $uname, student's name
1.297     matthew  13429: 
1.1172.2.31  raeburn  13430: =item $uid, student's user id
1.297     matthew  13431: 
1.1172.2.31  raeburn  13432: =item $first, student's first name
1.297     matthew  13433: 
                   13434: =item $middle
                   13435: 
                   13436: =item $last
                   13437: 
                   13438: =item $gene
                   13439: 
                   13440: =item $usec
                   13441: 
                   13442: =item $end
                   13443: 
                   13444: =item $start
                   13445: 
1.957     raeburn  13446: =item $type
                   13447: 
                   13448: =item $locktype
                   13449: 
                   13450: =item $cid
                   13451: 
                   13452: =item $selfenroll
                   13453: 
                   13454: =item $context
                   13455: 
1.1172.2.19  raeburn  13456: =item $credits, number of credits student will earn from this class
                   13457: 
1.1172.2.76  raeburn  13458: =item $instsec, institutional course section code for student
                   13459: 
1.297     matthew  13460: =back
                   13461: 
1.191     harris41 13462: 
                   13463: =item *
                   13464: 
1.243     albertel 13465: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   13466: custom role; give a custom role to a user for the level given by URL.  Specify
                   13467: name and domain of role author, and role name
1.191     harris41 13468: 
                   13469: =item *
                   13470: 
1.243     albertel 13471: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 13472: 
                   13473: =item *
                   13474: 
1.243     albertel 13475: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   13476: 
                   13477: =back
                   13478: 
                   13479: =head2 Course Infomation
                   13480: 
                   13481: =over 4
1.191     harris41 13482: 
                   13483: =item *
                   13484: 
1.1118    foxr     13485: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 13486: specified course id, including all environment settings for the
                   13487: course, the description of the course will be in the hash under the
                   13488: key 'description'
1.191     harris41 13489: 
1.1118    foxr     13490: $options is an optional parameter that if supplied is a hash reference that controls
                   13491: what how this function works.  It has the following key/values:
                   13492: 
                   13493: =over 4
                   13494: 
                   13495: =item freshen_cache
                   13496: 
                   13497: If defined, and the environment cache for the course is valid, it is 
                   13498: returned in the returned hash.
                   13499: 
                   13500: =item one_time
                   13501: 
                   13502: If defined, the last cache time is set to _now_
                   13503: 
                   13504: =item user
                   13505: 
                   13506: If defined, the supplied username is used instead of the current user.
                   13507: 
                   13508: 
                   13509: =back
                   13510: 
1.191     harris41 13511: =item *
                   13512: 
1.624     albertel 13513: resdata($name,$domain,$type,@which) : request for current parameter
                   13514: setting for a specific $type, where $type is either 'course' or 'user',
                   13515: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  13516: answers for 10 minutes.
1.243     albertel 13517: 
1.877     foxr     13518: =item *
                   13519: 
                   13520: get_courseresdata($courseid, $domain) : dump the entire course resource
                   13521: data base, returning a hash that is keyed by the resource name and has
                   13522: values that are the resource value.  I believe that the timestamps and
                   13523: versions are also returned.
                   13524: 
1.1172.2.31  raeburn  13525: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   13526: supplemental content area. This routine caches the number of files for
                   13527: 10 minutes.
                   13528: 
1.243     albertel 13529: =back
                   13530: 
                   13531: =head2 Course Modification
                   13532: 
                   13533: =over 4
1.191     harris41 13534: 
                   13535: =item *
                   13536: 
1.243     albertel 13537: writecoursepref($courseid,%prefs) : write preferences (environment
                   13538: database) for a course
1.191     harris41 13539: 
                   13540: =item *
                   13541: 
1.1011    raeburn  13542: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   13543: 
                   13544: =item *
                   13545: 
1.1038    raeburn  13546: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 13547: 
1.1167    droeschl 13548: =item *
                   13549: 
                   13550: is_course($courseid), is_course($cdom, $cnum)
                   13551: 
                   13552: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   13553: two component version $cdom, $cnum. It checks if the specified course exists.
                   13554: 
                   13555: Returns:
                   13556:     undef if the course doesn't exist, otherwise
                   13557:     in scalar context the combined courseid.
                   13558:     in list context the two components of the course identifier, domain and 
                   13559:     courseid.    
                   13560: 
1.243     albertel 13561: =back
                   13562: 
                   13563: =head2 Resource Subroutines
                   13564: 
                   13565: =over 4
1.191     harris41 13566: 
                   13567: =item *
                   13568: 
1.243     albertel 13569: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 13570: 
                   13571: =item *
                   13572: 
1.243     albertel 13573: repcopy($filename) : subscribes to the requested file, and attempts to
                   13574: replicate from the owning library server, Might return
1.607     raeburn  13575: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   13576: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 13577: resource. Expects the local filesystem pathname
                   13578: (/home/httpd/html/res/....)
                   13579: 
                   13580: =back
                   13581: 
                   13582: =head2 Resource Information
                   13583: 
                   13584: =over 4
1.191     harris41 13585: 
                   13586: =item *
                   13587: 
1.1172.2.28  raeburn  13588: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   13589: and returns the value of a variety of different possible values,
                   13590: $varname should be a request string, and the other parameters can be
                   13591: used to specify who and what one is asking about. Ordinarily, $cid 
                   13592: does not need to be specified, as it is retrived from 
                   13593: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   13594: within lonuserstate::loadmap() when initializing a course, before
                   13595: $env{'request.course.id'} has been set, so it needs to be provided
                   13596: in that one case.
1.243     albertel 13597: 
                   13598: Possible values for $varname are environment.lastname (or other item
                   13599: from the envirnment hash), user.name (or someother aspect about the
                   13600: user), resource.0.maxtries (or some other part and parameter of a
                   13601: resource)
1.204     albertel 13602: 
                   13603: =item *
                   13604: 
1.243     albertel 13605: directcondval($number) : get current value of a condition; reads from a state
                   13606: string
1.204     albertel 13607: 
                   13608: =item *
                   13609: 
1.243     albertel 13610: condval($condidx) : value of condition index based on state
1.204     albertel 13611: 
                   13612: =item *
                   13613: 
1.243     albertel 13614: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   13615: resource's metadata, $what should be either a specific key, or either
                   13616: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   13617: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   13618: 
                   13619: this function automatically caches all requests
1.191     harris41 13620: 
                   13621: =item *
                   13622: 
1.243     albertel 13623: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   13624: network of library servers; returns file handle of where SQL and regex results
                   13625: will be stored for query
1.191     harris41 13626: 
                   13627: =item *
                   13628: 
1.1172.2.66  raeburn  13629: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
                   13630: return symbolic list entry (all arguments optional).
                   13631: 
                   13632: Args: filename is the filename (including path) for the file for which a symb
                   13633: is required; donotrecurse, if true will prevent calls to allowed() being made
                   13634: to check access status if more than one resource was found in the bighash
                   13635: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
                   13636: a randompick); ignorecachednull, if true will prevent a symb of '' being
                   13637: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   13638: cause possible symbs to be checked to determine if they are subject to content
                   13639: blocking, if so they will not be included as possible symbs; possibles is a
                   13640: ref to a hash, which, as a side effect, will be populated with all possible
                   13641: symbs (content blocking not tested).
                   13642: 
1.243     albertel 13643: returns the data handle
1.191     harris41 13644: 
                   13645: =item *
                   13646: 
1.1172.2.17  raeburn  13647: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  13648: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 13649: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  13650: on failure, user must be in a course, as it assumes the existence of
                   13651: the course initial hash, and uses $env('request.course.id'}.  The third
                   13652: arg is an optional reference to a scalar.  If this arg is passed in the
                   13653: call to symbverify, it will be set to 1 if the symb has been set to be 
                   13654: encrypted; otherwise it will be null.
1.243     albertel 13655: 
1.191     harris41 13656: =item *
                   13657: 
1.243     albertel 13658: symbclean($symb) : removes versions numbers from a symb, returns the
                   13659: cleaned symb
1.191     harris41 13660: 
                   13661: =item *
                   13662: 
1.243     albertel 13663: is_on_map($uri) : checks if the $uri is somewhere on the current
                   13664: course map, user must be in a course for it to work.
1.191     harris41 13665: 
                   13666: =item *
                   13667: 
1.243     albertel 13668: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 13669: 
                   13670: =item *
                   13671: 
1.243     albertel 13672: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   13673: a random seed, all arguments are optional, if they aren't sent it uses the
                   13674: environment to derive them. Note: if symb isn't sent and it can't get one
                   13675: from &symbread it will use the current time as its return value
1.191     harris41 13676: 
                   13677: =item *
                   13678: 
1.243     albertel 13679: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   13680: unfakeable, receipt
1.191     harris41 13681: 
                   13682: =item *
                   13683: 
1.620     albertel 13684: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 13685: 
                   13686: =item *
                   13687: 
1.243     albertel 13688: countacc($url) : count the number of accesses to a given URL
1.191     harris41 13689: 
                   13690: =item *
                   13691: 
1.243     albertel 13692: 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 13693: 
                   13694: =item *
                   13695: 
1.243     albertel 13696: 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 13697: 
                   13698: =item *
                   13699: 
1.243     albertel 13700: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 13701: 
                   13702: =item *
                   13703: 
1.243     albertel 13704: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   13705: forcing spreadsheet to reevaluate the resource scores next time.
                   13706: 
1.1172.2.13  raeburn  13707: =item *
                   13708: 
                   13709: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   13710: when viewing in course context.
                   13711: 
                   13712:  input: six args -- filename (decluttered), course number, course domain,
                   13713:                     url, symb (if registered) and group (if this is a
                   13714:                     group item -- e.g., bulletin board, group page etc.).
                   13715: 
                   13716:  output: array of five scalars --
                   13717:          $cfile -- url for file editing if editable on current server
                   13718:          $home -- homeserver of resource (i.e., for author if published,
                   13719:                                           or course if uploaded.).
                   13720:          $switchserver --  1 if server switch will be needed.
                   13721:          $forceedit -- 1 if icon/link should be to go to edit mode
                   13722:          $forceview -- 1 if icon/link should be to go to view mode
                   13723: 
                   13724: =item *
                   13725: 
                   13726: is_course_upload($file,$cnum,$cdom)
                   13727: 
                   13728: Used in course context to determine if current file was uploaded to
                   13729: the course (i.e., would be found in /userfiles/docs on the course's
                   13730: homeserver.
                   13731: 
                   13732:   input: 3 args -- filename (decluttered), course number and course domain.
                   13733:   output: boolean -- 1 if file was uploaded.
                   13734: 
1.243     albertel 13735: =back
                   13736: 
                   13737: =head2 Storing/Retreiving Data
                   13738: 
                   13739: =over 4
1.191     harris41 13740: 
                   13741: =item *
                   13742: 
1.1172.2.64  raeburn  13743: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
                   13744: permanently for this url; hashref needs to be given and should be a \%hashname;
                   13745: the remaining args aren't required and if they aren't passed or are '' they will
                   13746: be derived from the env (with the exception of $laststore, which is an
                   13747: optional arg used when a user's submission is stored in grading).
                   13748: $laststore is $version=$timestamp, where $version is the most recent version
                   13749: number retrieved for the corresponding $symb in the $namespace db file, and
                   13750: $timestamp is the timestamp for that transaction (UNIX time).
                   13751: $laststore is currently only passed when cstore() is called by
                   13752: structuretags::finalize_storage().
1.191     harris41 13753: 
                   13754: =item *
                   13755: 
1.1172.2.64  raeburn  13756: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
                   13757: but uses critical subroutine
1.191     harris41 13758: 
                   13759: =item *
                   13760: 
1.243     albertel 13761: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   13762: all args are optional
1.191     harris41 13763: 
                   13764: =item *
                   13765: 
1.717     albertel 13766: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   13767: dumps the complete (or key matching regexp) namespace into a hash
                   13768: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   13769: normally &store()ed into
                   13770: 
                   13771: $range should be either an integer '100' (give me the first 100
                   13772:                                            matching records)
                   13773:               or be  two integers sperated by a - with no spaces
                   13774:                  '30-50' (give me the 30th through the 50th matching
                   13775:                           records)
                   13776: 
                   13777: 
                   13778: =item *
                   13779: 
1.1172.2.59  raeburn  13780: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 13781: replaces a &store() version of data with a replacement set of data
                   13782: for a particular resource in a namespace passed in the $storehash hash 
1.1172.2.59  raeburn  13783: reference. If $tolog is true, the transaction is logged in the courselog
                   13784: with an action=PUTSTORE.
1.717     albertel 13785: 
                   13786: =item *
                   13787: 
1.243     albertel 13788: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   13789: works very similar to store/cstore, but all data is stored in a
                   13790: temporary location and can be reset using tmpreset, $storehash should
                   13791: be a hash reference, returns nothing on success
1.191     harris41 13792: 
                   13793: =item *
                   13794: 
1.243     albertel 13795: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   13796: similar to restore, but all data is stored in a temporary location and
                   13797: can be reset using tmpreset. Returns a hash of values on success,
                   13798: error string otherwise.
1.191     harris41 13799: 
                   13800: =item *
                   13801: 
1.243     albertel 13802: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   13803: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 13804: 
                   13805: =item *
                   13806: 
1.243     albertel 13807: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13808: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 13809: 
                   13810: =item *
                   13811: 
1.243     albertel 13812: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   13813: namesp ($udom and $uname are optional)
1.191     harris41 13814: 
                   13815: =item *
                   13816: 
1.702     albertel 13817: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 13818: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 13819: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  13820: 
1.702     albertel 13821: $range should be either an integer '100' (give me the first 100
                   13822:                                            matching records)
                   13823:               or be  two integers sperated by a - with no spaces
                   13824:                  '30-50' (give me the 30th through the 50th matching
                   13825:                           records)
1.449     matthew  13826: =item *
                   13827: 
                   13828: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   13829: $store can be a scalar, an array reference, or if the amount to be 
                   13830: incremented is > 1, a hash reference.
                   13831: 
                   13832: ($udom and $uname are optional)
1.191     harris41 13833: 
                   13834: =item *
                   13835: 
1.243     albertel 13836: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   13837: ($udom and $uname are optional)
1.191     harris41 13838: 
                   13839: =item *
                   13840: 
1.243     albertel 13841: cput($namespace,$storehash,$udom,$uname) : critical put
                   13842: ($udom and $uname are optional)
1.191     harris41 13843: 
                   13844: =item *
                   13845: 
1.748     albertel 13846: newput($namespace,$storehash,$udom,$uname) :
                   13847: 
                   13848: Attempts to store the items in the $storehash, but only if they don't
                   13849: currently exist, if this succeeds you can be certain that you have 
                   13850: successfully created a new key value pair in the $namespace db.
                   13851: 
                   13852: 
                   13853: Args:
                   13854:  $namespace: name of database to store values to
                   13855:  $storehash: hashref to store to the db
                   13856:  $udom: (optional) domain of user containing the db
                   13857:  $uname: (optional) name of user caontaining the db
                   13858: 
                   13859: Returns:
                   13860:  'ok' -> succeeded in storing all keys of $storehash
                   13861:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   13862:                         least <key> already existed in the db (other
                   13863:                         requested keys may also already exist)
1.967     bisitz   13864:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 13865:  'con_lost' -> unable to contact request server
                   13866:  'refused' -> action was not allowed by remote machine
                   13867: 
                   13868: 
                   13869: =item *
                   13870: 
1.243     albertel 13871: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13872: reference filled in from namesp (encrypts the return communication)
                   13873: ($udom and $uname are optional)
1.191     harris41 13874: 
                   13875: =item *
                   13876: 
1.243     albertel 13877: log($udom,$name,$home,$message) : write to permanent log for user; use
                   13878: critical subroutine
                   13879: 
1.806     raeburn  13880: =item *
                   13881: 
1.860     raeburn  13882: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   13883: array reference filled in from namespace found in domain level on either
                   13884: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  13885: 
                   13886: =item *
                   13887: 
1.860     raeburn  13888: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   13889: domain level either on specified domain server ($uhome) or primary domain 
                   13890: server ($udom and $uhome are optional)
1.806     raeburn  13891: 
1.943     raeburn  13892: =item * 
                   13893: 
1.1172.2.35  raeburn  13894: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
                   13895: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   13896: the target domain.
                   13897: 
                   13898: May also include additional key => value pairs for the following groups:
                   13899: 
                   13900: =over
                   13901: 
                   13902: =item
                   13903: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   13904: 
                   13905: =over
                   13906: 
                   13907: =item defaultquota, authorquota
                   13908: 
                   13909: =back
                   13910: 
                   13911: =item
                   13912: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   13913: portfolio for users).
                   13914: 
                   13915: =over
                   13916: 
                   13917: =item
                   13918: aboutme, blog, webdav, portfolio
                   13919: 
                   13920: =back
                   13921: 
                   13922: =item
                   13923: requestcourses: ability to request courses, and how requests are processed.
                   13924: 
                   13925: =over
                   13926: 
                   13927: =item
1.1172.2.37  raeburn  13928: official, unofficial, community, textbook
1.1172.2.35  raeburn  13929: 
                   13930: =back
                   13931: 
                   13932: =item
                   13933: inststatus: types of institutional affiliation, and order in which they are displayed.
                   13934: 
                   13935: =over
                   13936: 
                   13937: =item
1.1172.2.44  raeburn  13938: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35  raeburn  13939: 
                   13940: =back
                   13941: 
                   13942: =item
                   13943: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   13944: for course's uploaded content.
                   13945: 
                   13946: =over
                   13947: 
                   13948: =item
1.1172.2.68  raeburn  13949: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
                   13950: communityquota, textbookquota
1.1172.2.35  raeburn  13951: 
                   13952: =back
                   13953: 
                   13954: =item
                   13955: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   13956: on your servers.
                   13957: 
                   13958: =over
                   13959: 
                   13960: =item
                   13961: remotesessions, hostedsessions
                   13962: 
                   13963: =back
                   13964: 
                   13965: =back
                   13966: 
                   13967: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   13968: utility to create a configuration.db file on a domain's primary library server
                   13969: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   13970: -- corresponding values are authentication type (internal, krb4, krb5,
                   13971: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
                   13972: will be available. Values are retrieved from cache (if current), unless the
                   13973: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   13974: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   13975: 
                   13976: Typical usage:
1.943     raeburn  13977: 
1.1172.2.35  raeburn  13978: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  13979: 
1.243     albertel 13980: =back
                   13981: 
                   13982: =head2 Network Status Functions
                   13983: 
                   13984: =over 4
1.191     harris41 13985: 
                   13986: =item *
                   13987: 
1.1137    raeburn  13988: dirlist() : return directory list based on URI (first arg).
                   13989: 
                   13990: Inputs: 1 required, 5 optional.
                   13991: 
                   13992: =over
                   13993: 
                   13994: =item 
                   13995: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   13996: 
                   13997: =item
                   13998: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   13999: 
                   14000: =item
                   14001: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   14002: 
                   14003: =item
                   14004: $getpropath - boolean: 1 if prepend path using &propath(). 
                   14005: 
                   14006: =item
                   14007: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   14008: 
                   14009: =item 
                   14010: $alternateRoot - path to prepend in place of path from $uri.
                   14011: 
                   14012: =back
                   14013: 
                   14014: Returns: Array of up to two items.
                   14015: 
                   14016: =over
                   14017: 
                   14018: a reference to an array of files/subdirectories
                   14019: 
                   14020: =over
                   14021: 
                   14022: Each element in the array of files/subdirectories is a & separated list of
                   14023: item name and the result of running stat on the item.  If dirlist was requested
                   14024: for a file instead of a directory, the item name will be ''. For a directory 
                   14025: listing, if the item is a metadata file, the element will end &N&M 
                   14026: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   14027: default copyright set (1).  
                   14028: 
                   14029: =back
                   14030: 
                   14031: a scalar containing error condition (if encountered).
                   14032: 
                   14033: =over
                   14034: 
                   14035: =item 
                   14036: no_host (no homeserver identified for $username:$domain).
                   14037: 
                   14038: =item 
                   14039: no_such_host (server contacted for listing not identified as valid host).
                   14040: 
                   14041: =item 
                   14042: con_lost (connection to remote server failed).
                   14043: 
                   14044: =item 
                   14045: refused (invalid $username:$domain received on lond side).
                   14046: 
                   14047: =item 
                   14048: no_such_dir (directory at specified path on lond side does not exist). 
                   14049: 
                   14050: =item 
                   14051: empty (directory at specified path on lond side is empty).
                   14052: 
                   14053: =over
                   14054: 
                   14055: This is currently not encountered because the &ls3, &ls2, 
                   14056: &ls (_handler) routines on the lond side do not filter out
                   14057: . and .. from a directory listing. 
                   14058: 
                   14059: =back
                   14060: 
                   14061: =back
                   14062: 
                   14063: =back
1.191     harris41 14064: 
                   14065: =item *
                   14066: 
1.243     albertel 14067: spareserver() : find server with least workload from spare.tab
                   14068: 
1.986     foxr     14069: 
                   14070: =item *
                   14071: 
                   14072: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   14073: if there is no corresponding loncapa host.
                   14074: 
1.243     albertel 14075: =back
                   14076: 
1.986     foxr     14077: 
1.243     albertel 14078: =head2 Apache Request
                   14079: 
                   14080: =over 4
1.191     harris41 14081: 
                   14082: =item *
                   14083: 
1.243     albertel 14084: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   14085: localhost, posts hash
                   14086: 
                   14087: =back
                   14088: 
                   14089: =head2 Data to String to Data
                   14090: 
                   14091: =over 4
1.191     harris41 14092: 
                   14093: =item *
                   14094: 
1.243     albertel 14095: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   14096: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 14097: 
                   14098: =item *
                   14099: 
1.243     albertel 14100: hashref2str($hashref) : convert a hashref into a string complete with
                   14101: escaping and '=' and '&' separators, supports elements that are
                   14102: arrayrefs and hashrefs
1.191     harris41 14103: 
                   14104: =item *
                   14105: 
1.243     albertel 14106: arrayref2str($arrayref) : convert an arrayref into a string complete
                   14107: with escaping and '&' separators, supports elements that are arrayrefs
                   14108: and hashrefs
1.191     harris41 14109: 
                   14110: =item *
                   14111: 
1.243     albertel 14112: str2hash($string) : convert string to hash using unescaping and
                   14113: splitting on '=' and '&', supports elements that are arrayrefs and
                   14114: hashrefs
1.191     harris41 14115: 
                   14116: =item *
                   14117: 
1.243     albertel 14118: str2array($string) : convert string to hash using unescaping and
                   14119: splitting on '&', supports elements that are arrayrefs and hashrefs
                   14120: 
                   14121: =back
                   14122: 
                   14123: =head2 Logging Routines
                   14124: 
                   14125: 
                   14126: These routines allow one to make log messages in the lonnet.log and
                   14127: lonnet.perm logfiles.
1.191     harris41 14128: 
1.1119    foxr     14129: =over 4
                   14130: 
1.191     harris41 14131: =item *
                   14132: 
1.243     albertel 14133: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 14134: 
                   14135: =item *
                   14136: 
1.243     albertel 14137: logthis() : append message to the normal lonnet.log file, it gets
                   14138: preiodically rolled over and deleted.
1.191     harris41 14139: 
                   14140: =item *
                   14141: 
1.243     albertel 14142: logperm() : append a permanent message to lonnet.perm.log, this log
                   14143: file never gets deleted by any automated portion of the system, only
                   14144: messages of critical importance should go in here.
                   14145: 
1.1119    foxr     14146: 
1.243     albertel 14147: =back
                   14148: 
                   14149: =head2 General File Helper Routines
                   14150: 
                   14151: =over 4
1.191     harris41 14152: 
                   14153: =item *
                   14154: 
1.481     raeburn  14155: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   14156: (a) files in /uploaded
                   14157:   (i) If a local copy of the file exists - 
                   14158:       compares modification date of local copy with last-modified date for 
                   14159:       definitive version stored on home server for course. If local copy is 
                   14160:       stale, requests a new version from the home server and stores it. 
                   14161:       If the original has been removed from the home server, then local copy 
                   14162:       is unlinked.
                   14163:   (ii) If local copy does not exist -
                   14164:       requests the file from the home server and stores it. 
                   14165:   
                   14166:   If $caller is 'uploadrep':  
                   14167:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   14168:     for request for files originally uploaded via DOCS. 
                   14169:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   14170:   
                   14171:   Otherwise:
                   14172:      This indicates a call from the content generation phase of the request.
                   14173:      -  returns the entire contents of the file or -1.
                   14174:      
                   14175: (b) files in /res
                   14176:    - returns the entire contents of a file or -1; 
                   14177:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 14178: 
1.712     albertel 14179: 
                   14180: =item *
                   14181: 
                   14182: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   14183:                   reference
                   14184: 
                   14185: returns either a stat() list of data about the file or an empty list
                   14186: if the file doesn't exist or couldn't find out about it (connection
                   14187: problems or user unknown)
                   14188: 
1.191     harris41 14189: =item *
                   14190: 
1.243     albertel 14191: filelocation($dir,$file) : returns file system location of a file
                   14192: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   14193: directory that relative $file lookups are to looked in ($dir of /a/dir
                   14194: and a file of ../bob will become /a/bob)
1.191     harris41 14195: 
                   14196: =item *
                   14197: 
                   14198: hreflocation($dir,$file) : returns file system location or a URL; same as
                   14199: filelocation except for hrefs
                   14200: 
                   14201: =item *
                   14202: 
1.1172.2.49  raeburn  14203: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   14204: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 14205: 
1.243     albertel 14206: =back
                   14207: 
1.608     albertel 14208: =head2 Usererfile file routines (/uploaded*)
                   14209: 
                   14210: =over 4
                   14211: 
                   14212: =item *
                   14213: 
                   14214: userfileupload(): main rotine for putting a file in a user or course's
                   14215:                   filespace, arguments are,
                   14216: 
1.620     albertel 14217:  formname - required - this is the name of the element in $env where the
1.608     albertel 14218:            filename, and the contents of the file to create/modifed exist
1.620     albertel 14219:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   14220:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  14221:  context - if coursedoc, store the file in the course of the active role
                   14222:              of the current user; 
                   14223:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   14224:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 14225:  subdir - required - subdirectory to put the file in under ../userfiles/
                   14226:          if undefined, it will be placed in "unknown"
                   14227: 
                   14228:  (This routine calls clean_filename() to remove any dangerous
                   14229:  characters from the filename, and then calls finuserfileupload() to
                   14230:  complete the transaction)
                   14231: 
                   14232:  returns either the url of the uploaded file (/uploaded/....) if successful
                   14233:  and /adm/notfound.html if unsuccessful
                   14234: 
                   14235: =item *
                   14236: 
                   14237: clean_filename(): routine for cleaing a filename up for storage in
                   14238:                  userfile space, argument is:
                   14239: 
                   14240:  filename - proposed filename
                   14241: 
                   14242: returns: the new clean filename
                   14243: 
                   14244: =item *
                   14245: 
1.1090    raeburn  14246: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 14247: userspace, probably shouldn't be called directly
                   14248: 
                   14249:   docuname: username or courseid of destination for the file
                   14250:   docudom: domain of user/course of destination for the file
                   14251:   formname: same as for userfileupload()
1.1090    raeburn  14252:   fname: filename (including subdirectories) for the file
                   14253:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   14254:   allfiles: reference to hash used to store objects found by parser
                   14255:   codebase: reference to hash used for codebases of java objects found by parser
                   14256:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   14257:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   14258:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   14259:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   14260:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   14261:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  14262:   mimetype: reference to scalar to accommodate mime type determined
                   14263:             from File::MMagic if $parser = parse.
1.608     albertel 14264: 
                   14265:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  14266:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   14267:  was 'overwrite').
                   14268:  
1.608     albertel 14269: 
                   14270: =item *
                   14271: 
                   14272: renameuserfile(): renames an existing userfile to a new name
                   14273: 
                   14274:   Args:
                   14275:    docuname: username or courseid of destination for the file
                   14276:    docudom: domain of user/course of destination for the file
                   14277:    old: current file name (including any subdirs under userfiles)
                   14278:    new: desired file name (including any subdirs under userfiles)
                   14279: 
                   14280: =item *
                   14281: 
                   14282: mkdiruserfile(): creates a directory is a userfiles dir
                   14283: 
                   14284:   Args:
                   14285:    docuname: username or courseid of destination for the file
                   14286:    docudom: domain of user/course of destination for the file
                   14287:    dir: dir to create (including any subdirs under userfiles)
                   14288: 
                   14289: =item *
                   14290: 
                   14291: removeuserfile(): removes a file that exists in userfiles
                   14292: 
                   14293:   Args:
                   14294:    docuname: username or courseid of destination for the file
                   14295:    docudom: domain of user/course of destination for the file
                   14296:    fname: filname to delete (including any subdirs under userfiles)
                   14297: 
                   14298: =item *
                   14299: 
                   14300: removeuploadedurl(): convience function for removeuserfile()
                   14301: 
                   14302:   Args:
                   14303:    url:  a full /uploaded/... url to delete
                   14304: 
1.747     albertel 14305: =item * 
                   14306: 
                   14307: get_portfile_permissions():
                   14308:   Args:
                   14309:     domain: domain of user or course contain the portfolio files
                   14310:     user: name of user or num of course contain the portfolio files
                   14311:   Returns:
                   14312:     hashref of a dump of the proper file_permissions.db
                   14313:    
                   14314: 
                   14315: =item * 
                   14316: 
                   14317: get_access_controls():
                   14318: 
                   14319: Args:
                   14320:   current_permissions: the hash ref returned from get_portfile_permissions()
                   14321:   group: (optional) the group you want the files associated with
                   14322:   file: (optional) the file you want access info on
                   14323: 
                   14324: Returns:
1.749     raeburn  14325:     a hash (keys are file names) of hashes containing
                   14326:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   14327:         values are XML containing access control settings (see below) 
1.747     albertel 14328: 
                   14329: Internal notes:
                   14330: 
1.749     raeburn  14331:  access controls are stored in file_permissions.db as key=value pairs.
                   14332:     key -> path to file/file_name\0uniqueID:scope_end_start
                   14333:         where scope -> public,guest,course,group,domains or users.
                   14334:               end -> UNIX time for end of access (0 -> no end date)
                   14335:               start -> UNIX time for start of access
                   14336: 
                   14337:     value -> XML description of access control
                   14338:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   14339:             <start></start>
                   14340:             <end></end>
                   14341: 
                   14342:             <password></password>  for scope type = guest
                   14343: 
                   14344:             <domain></domain>     for scope type = course or group
                   14345:             <number></number>
                   14346:             <roles id="">
                   14347:              <role></role>
                   14348:              <access></access>
                   14349:              <section></section>
                   14350:              <group></group>
                   14351:             </roles>
                   14352: 
                   14353:             <dom></dom>         for scope type = domains
                   14354: 
                   14355:             <users>             for scope type = users
                   14356:              <user>
                   14357:               <uname></uname>
                   14358:               <udom></udom>
                   14359:              </user>
                   14360:             </users>
                   14361:            </scope> 
                   14362:               
                   14363:  Access data is also aggregated for each file in an additional key=value pair:
                   14364:  key -> path to file/file_name\0accesscontrol 
                   14365:  value -> reference to hash
                   14366:           hash contains key = value pairs
                   14367:           where key = uniqueID:scope_end_start
                   14368:                 value = UNIX time record was last updated
                   14369: 
                   14370:           Used to improve speed of look-ups of access controls for each file.  
                   14371:  
                   14372:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   14373: 
1.1172.2.13  raeburn  14374: =item *
                   14375: 
1.749     raeburn  14376: modify_access_controls():
                   14377: 
                   14378: Modifies access controls for a portfolio file
                   14379: Args
                   14380: 1. file name
                   14381: 2. reference to hash of required changes,
                   14382: 3. domain
                   14383: 4. username
                   14384:   where domain,username are the domain of the portfolio owner 
                   14385:   (either a user or a course) 
                   14386: 
                   14387: Returns:
                   14388: 1. result of additions or updates ('ok' or 'error', with error message). 
                   14389: 2. result of deletions ('ok' or 'error', with error message).
                   14390: 3. reference to hash of any new or updated access controls.
                   14391: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   14392:    key = integer (inbound ID)
1.1172.2.13  raeburn  14393:    value = uniqueID
                   14394: 
                   14395: =item *
                   14396: 
                   14397: get_timebased_id():
                   14398: 
                   14399: Attempts to get a unique timestamp-based suffix for use with items added to a
                   14400: course via the Course Editor (e.g., folders, composite pages,
                   14401: group bulletin boards).
                   14402: 
                   14403: Args: (first three required; six others optional)
                   14404: 
                   14405: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   14406:    docssequence, or name of group
                   14407: 
                   14408: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   14409:    e.g., num, boardids
                   14410: 
                   14411: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   14412:    file will be named nohist_namespace.db
                   14413: 
                   14414: 4. cdom: domain of course; default is current course domain from %env
                   14415: 
                   14416: 5. cnum: course number; default is current course number from %env
                   14417: 
                   14418: 6. idtype: set to concat if an additional digit is to be appended to the
                   14419:    unix timestamp to form the suffix, if the plain timestamp is already
                   14420:    in use.  Default is to not do this, but simply increment the unix
                   14421:    timestamp by 1 until a unique key is obtained.
                   14422: 
                   14423: 7. who: holder of locking key; defaults to user:domain for user.
                   14424: 
                   14425: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   14426:    retrying); default is 3.
                   14427: 
                   14428: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   14429: 
                   14430: Returns:
                   14431: 
                   14432: 1. suffix obtained (numeric)
                   14433: 
                   14434: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   14435: 
                   14436: 3. error: contains (localized) error message if an error occurred.
                   14437: 
1.747     albertel 14438: 
1.608     albertel 14439: =back
                   14440: 
1.243     albertel 14441: =head2 HTTP Helper Routines
                   14442: 
                   14443: =over 4
                   14444: 
1.191     harris41 14445: =item *
                   14446: 
                   14447: escape() : unpack non-word characters into CGI-compatible hex codes
                   14448: 
                   14449: =item *
                   14450: 
                   14451: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   14452: 
1.243     albertel 14453: =back
                   14454: 
                   14455: =head1 PRIVATE SUBROUTINES
                   14456: 
                   14457: =head2 Underlying communication routines (Shouldn't call)
                   14458: 
                   14459: =over 4
                   14460: 
                   14461: =item *
                   14462: 
                   14463: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   14464: 
                   14465: =item *
                   14466: 
                   14467: reply() : uses subreply to send a message to remote machine, logs all failures
                   14468: 
                   14469: =item *
                   14470: 
                   14471: critical() : passes a critical message to another server; if cannot
                   14472: get through then place message in connection buffer directory and
                   14473: returns con_delayed, if incapable of saving message, returns
                   14474: con_failed
                   14475: 
                   14476: =item *
                   14477: 
                   14478: reconlonc() : tries to reconnect lonc client processes.
                   14479: 
                   14480: =back
                   14481: 
                   14482: =head2 Resource Access Logging
                   14483: 
                   14484: =over 4
                   14485: 
                   14486: =item *
                   14487: 
                   14488: flushcourselogs() : flush (save) buffer logs and access logs
                   14489: 
                   14490: =item *
                   14491: 
                   14492: courselog($what) : save message for course in hash
                   14493: 
                   14494: =item *
                   14495: 
                   14496: courseacclog($what) : save message for course using &courselog().  Perform
                   14497: special processing for specific resource types (problems, exams, quizzes, etc).
                   14498: 
1.191     harris41 14499: =item *
                   14500: 
                   14501: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   14502: as a PerlChildExitHandler
1.243     albertel 14503: 
                   14504: =back
                   14505: 
                   14506: =head2 Other
                   14507: 
                   14508: =over 4
                   14509: 
                   14510: =item *
                   14511: 
                   14512: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 14513: 
                   14514: =back
                   14515: 
                   14516: =cut
1.877     foxr     14517: 

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