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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.35! raeburn     4: # $Id: lonnet.pm,v 1.1172.2.34 2013/09/02 14:41:53 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.18  raeburn    78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $apache
1.1138    raeburn    79:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
                     80:             %managerstab);
1.871     albertel   81: 
                     82: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     83:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     84:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        85:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        86: 
1.1       albertel   87: use IO::Socket;
1.31      www        88: use GDBM_File;
1.208     albertel   89: use HTML::LCParser;
1.88      www        90: use Fcntl qw(:flock);
1.870     albertel   91: use Storable qw(thaw nfreeze);
1.539     albertel   92: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   93: use Cache::Memcached;
1.676     albertel   94: use Digest::MD5;
1.790     albertel   95: use Math::Random;
1.1024    raeburn    96: use File::MMagic;
1.807     albertel   97: use LONCAPA qw(:DEFAULT :match);
1.740     www        98: use LONCAPA::Configuration;
1.1160    www        99: use LONCAPA::lonmetadata;
1.1172.2.22  raeburn   100: use LONCAPA::Lond;
1.1117    foxr      101: 
1.1090    raeburn   102: use File::Copy;
1.676     albertel  103: 
1.195     www       104: my $readit;
1.550     foxr      105: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel  106: 
1.619     albertel  107: require Exporter;
                    108: 
                    109: our @ISA = qw (Exporter);
                    110: our @EXPORT = qw(%env);
                    111: 
1.1172.2.9  raeburn   112: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729     www       113: {
                    114:     my $logid;
1.1172.2.9  raeburn   115:     sub write_log {
                    116: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    117:         if ($context eq 'course') {
                    118:             if (($cnum eq '') || ($cdom eq '')) {
                    119:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    120:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    121:             }
1.957     raeburn   122:         }
1.1172.2.13  raeburn   123: 	$logid ++;
1.957     raeburn   124:         my $now = time();
                    125: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.1172.2.9  raeburn   126:         my $logentry = {
                    127:                          $id => {
                    128:                                   'exe_uname' => $env{'user.name'},
                    129:                                   'exe_udom'  => $env{'user.domain'},
                    130:                                   'exe_time'  => $now,
                    131:                                   'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    132:                                   'delflag'   => $delflag,
                    133:                                   'logentry'  => $storehash,
                    134:                                   'uname'     => $uname,
                    135:                                   'udom'      => $udom,
                    136:                                 }
                    137:                        };
                    138:         return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729     www       139:     }
                    140: }
1.1       albertel  141: 
1.163     harris41  142: sub logtouch {
                    143:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  144:     unless (-e "$execdir/logs/lonnet.log") {	
                    145: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  146: 	close $fh;
                    147:     }
                    148:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    149:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    150: }
                    151: 
1.1       albertel  152: sub logthis {
                    153:     my $message=shift;
                    154:     my $execdir=$perlvar{'lonDaemons'};
                    155:     my $now=time;
                    156:     my $local=localtime($now);
1.448     albertel  157:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986     foxr      158: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    159: 	print $fh $logstring;
1.448     albertel  160: 	close($fh);
                    161:     }
1.1       albertel  162:     return 1;
                    163: }
                    164: 
                    165: sub logperm {
                    166:     my $message=shift;
                    167:     my $execdir=$perlvar{'lonDaemons'};
                    168:     my $now=time;
                    169:     my $local=localtime($now);
1.448     albertel  170:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    171: 	print $fh "$now:$message:$local\n";
                    172: 	close($fh);
                    173:     }
1.1       albertel  174:     return 1;
                    175: }
                    176: 
1.850     albertel  177: sub create_connection {
1.853     albertel  178:     my ($hostname,$lonid) = @_;
1.851     albertel  179:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  180: 				     Type    => SOCK_STREAM,
                    181: 				     Timeout => 10);
                    182:     return 0 if (!$client);
1.890     albertel  183:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  184:     my $result = <$client>;
                    185:     chomp($result);
                    186:     return 1 if ($result eq 'done');
                    187:     return 0;
                    188: }
                    189: 
1.983     raeburn   190: sub get_server_timezone {
                    191:     my ($cnum,$cdom) = @_;
                    192:     my $home=&homeserver($cnum,$cdom);
                    193:     if ($home ne 'no_host') {
                    194:         my $cachetime = 24*3600;
                    195:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    196:         if (defined($cached)) {
                    197:             return $timezone;
                    198:         } else {
                    199:             my $timezone = &reply('servertimezone',$home);
                    200:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    201:         }
                    202:     }
                    203: }
1.850     albertel  204: 
1.1106    raeburn   205: sub get_server_distarch {
                    206:     my ($lonhost,$ignore_cache) = @_;
                    207:     if (defined($lonhost)) {
                    208:         if (!defined(&hostname($lonhost))) {
                    209:             return;
                    210:         }
                    211:         my $cachetime = 12*3600;
                    212:         if (!$ignore_cache) {
                    213:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    214:             if (defined($cached)) {
                    215:                 return $distarch;
                    216:             }
                    217:         }
                    218:         my $rep = &reply('serverdistarch',$lonhost);
                    219:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    220:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    221:                 $rep eq '') {
                    222:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    223:         }
                    224:     }
                    225:     return;
                    226: }
                    227: 
1.993     raeburn   228: sub get_server_loncaparev {
1.1073    raeburn   229:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   230:     if (defined($lonhost)) {
                    231:         if (!defined(&hostname($lonhost))) {
                    232:             undef($lonhost);
                    233:         }
                    234:     }
                    235:     if (!defined($lonhost)) {
                    236:         if (defined(&domain($dom,'primary'))) {
                    237:             $lonhost=&domain($dom,'primary');
                    238:             if ($lonhost eq 'no_host') {
                    239:                 undef($lonhost);
                    240:             }
                    241:         }
                    242:     }
                    243:     if (defined($lonhost)) {
1.1073    raeburn   244:         my $cachetime = 12*3600;
                    245:         if (!$ignore_cache) {
                    246:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    247:             if (defined($cached)) {
                    248:                 return $loncaparev;
                    249:             }
                    250:         }
                    251:         my ($answer,$loncaparev);
                    252:         my @ids=&current_machine_ids();
                    253:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    254:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   255:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   256:                 $loncaparev = $1;
                    257:             }
                    258:         } else {
                    259:             $answer = &reply('serverloncaparev',$lonhost);
                    260:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    261:                 if ($caller eq 'loncron') {
                    262:                     my $ua=new LWP::UserAgent;
1.1082    raeburn   263:                     $ua->timeout(4);
1.1073    raeburn   264:                     my $protocol = $protocol{$lonhost};
                    265:                     $protocol = 'http' if ($protocol ne 'https');
                    266:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
                    267:                     my $request=new HTTP::Request('GET',$url);
                    268:                     my $response=$ua->request($request);
                    269:                     unless ($response->is_error()) {
                    270:                         my $content = $response->content;
1.1081    raeburn   271:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   272:                             $loncaparev = $1;
                    273:                         }
                    274:                     }
                    275:                 } else {
                    276:                     $loncaparev = $loncaparevs{$lonhost};
                    277:                 }
1.1081    raeburn   278:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   279:                 $loncaparev = $1;
                    280:             }
1.993     raeburn   281:         }
1.1073    raeburn   282:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   283:     }
                    284: }
                    285: 
1.1074    raeburn   286: sub get_server_homeID {
                    287:     my ($hostname,$ignore_cache,$caller) = @_;
                    288:     unless ($ignore_cache) {
                    289:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    290:         if (defined($cached)) {
                    291:             return $serverhomeID;
                    292:         }
                    293:     }
                    294:     my $cachetime = 12*3600;
                    295:     my $serverhomeID;
                    296:     if ($caller eq 'loncron') { 
                    297:         my @machine_ids = &machine_ids($hostname);
                    298:         foreach my $id (@machine_ids) {
                    299:             my $response = &reply('serverhomeID',$id);
                    300:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    301:                 $serverhomeID = $response;
                    302:                 last;
                    303:             }
                    304:         }
                    305:         if ($serverhomeID eq '') {
                    306:             $serverhomeID = $machine_ids[-1];
                    307:         }
                    308:     } else {
                    309:         $serverhomeID = $serverhomeIDs{$hostname};
                    310:     }
                    311:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    312: }
                    313: 
1.1121    raeburn   314: sub get_remote_globals {
                    315:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   316:     my ($result,%returnhash,%whatneeded);
                    317:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   318:         foreach my $what (sort(keys(%{$whathash}))) {
                    319:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   320:             my ($response,$cached);
1.1121    raeburn   321:             unless ($ignore_cache) {
1.1125    raeburn   322:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   323:             }
                    324:             if (defined($cached)) {
1.1125    raeburn   325:                 $returnhash{$what} = $response;
1.1121    raeburn   326:             } else {
1.1125    raeburn   327:                 $whatneeded{$what} = 1;
1.1121    raeburn   328:             }
                    329:         }
1.1125    raeburn   330:         if (keys(%whatneeded) == 0) {
                    331:             $result = 'ok';
                    332:         } else {
1.1121    raeburn   333:             my $requested = &freeze_escape(\%whatneeded);
                    334:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   335:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    336:                 ($rep eq 'unknown_cmd')) {
                    337:                 $result = $rep;
                    338:             } else {
                    339:                 $result = 'ok';
1.1121    raeburn   340:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   341:                 foreach my $item (@pairs) {
                    342:                     my ($key,$value)=split(/=/,$item,2);
                    343:                     my $what = &unescape($key);
                    344:                     my $hashid = $lonhost.'-'.$what;
                    345:                     $returnhash{$what}=&thaw_unescape($value);
                    346:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   347:                 }
                    348:             }
                    349:         }
                    350:     }
1.1125    raeburn   351:     return ($result,\%returnhash);
1.1121    raeburn   352: }
                    353: 
1.1124    raeburn   354: sub remote_devalidate_cache {
1.1172.2.35! raeburn   355:     my ($lonhost,$cachekeys) = @_;
        !           356:     my $items;
        !           357:     return unless (ref($cachekeys) eq 'ARRAY');
        !           358:     my $cachestr = join('&',@{$cachekeys});
        !           359:     return &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124    raeburn   360: }
                    361: 
1.1       albertel  362: # -------------------------------------------------- Non-critical communication
                    363: sub subreply {
                    364:     my ($cmd,$server)=@_;
1.838     albertel  365:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      366:     #
                    367:     #  With loncnew process trimming, there's a timing hole between lonc server
                    368:     #  process exit and the master server picking up the listen on the AF_UNIX
                    369:     #  socket.  In that time interval, a lock file will exist:
                    370: 
                    371:     my $lockfile=$peerfile.".lock";
                    372:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    373: 	sleep(1);
                    374:     }
                    375:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      376:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      377:     #
1.550     foxr      378:     #   We'll give the connection a few tries before abandoning it.  If
                    379:     #   connection is not possible, we'll con_lost back to the client.
                    380:     #   
                    381:     my $client;
                    382:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    383: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    384: 				      Type    => SOCK_STREAM,
                    385: 				      Timeout => 10);
1.869     albertel  386: 	if ($client) {
1.550     foxr      387: 	    last;		# Connected!
1.850     albertel  388: 	} else {
1.853     albertel  389: 	    &create_connection(&hostname($server),$server);
1.550     foxr      390: 	}
1.850     albertel  391:         sleep(1);		# Try again later if failed connection.
1.550     foxr      392:     }
                    393:     my $answer;
                    394:     if ($client) {
1.704     albertel  395: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      396: 	$answer=<$client>;
                    397: 	if (!$answer) { $answer="con_lost"; }
                    398: 	chomp($answer);
                    399:     } else {
                    400: 	$answer = 'con_lost';	# Failed connection.
                    401:     }
1.1       albertel  402:     return $answer;
                    403: }
                    404: 
                    405: sub reply {
                    406:     my ($cmd,$server)=@_;
1.838     albertel  407:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  408:     my $answer=subreply($cmd,$server);
1.65      www       409:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  410:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       411:                 " $cmd to $server returned $answer</font>");
                    412:     }
1.1       albertel  413:     return $answer;
                    414: }
                    415: 
                    416: # ----------------------------------------------------------- Send USR1 to lonc
                    417: 
                    418: sub reconlonc {
1.891     albertel  419:     my ($lonid) = @_;
                    420:     my $hostname = &hostname($lonid);
                    421:     if ($lonid) {
                    422: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    423: 	if ($hostname && -e $peerfile) {
                    424: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    425: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    426: 					     Type    => SOCK_STREAM,
                    427: 					     Timeout => 10);
                    428: 	    if ($client) {
                    429: 		print $client ("reset_retries\n");
                    430: 		my $answer=<$client>;
                    431: 		#reset just this one.
                    432: 	    }
                    433: 	}
                    434: 	return;
                    435:     }
                    436: 
1.836     www       437:     &logthis("Trying to reconnect lonc");
1.1       albertel  438:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  439:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  440: 	my $loncpid=<$fh>;
                    441:         chomp($loncpid);
                    442:         if (kill 0 => $loncpid) {
                    443: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    444:             kill USR1 => $loncpid;
                    445:             sleep 1;
1.836     www       446:          } else {
1.12      www       447: 	    &logthis(
1.672     albertel  448:                "<font color=\"blue\">WARNING:".
1.12      www       449:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  450:         }
                    451:     } else {
1.836     www       452: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  453:     }
                    454: }
                    455: 
                    456: # ------------------------------------------------------ Critical communication
1.12      www       457: 
1.1       albertel  458: sub critical {
                    459:     my ($cmd,$server)=@_;
1.838     albertel  460:     unless (&hostname($server)) {
1.672     albertel  461:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       462:                " Critical message to unknown server ($server)</font>");
                    463:         return 'no_such_host';
                    464:     }
1.1       albertel  465:     my $answer=reply($cmd,$server);
                    466:     if ($answer eq 'con_lost') {
                    467: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  468: 	my $answer=reply($cmd,$server);
1.1       albertel  469:         if ($answer eq 'con_lost') {
                    470:             my $now=time;
                    471:             my $middlename=$cmd;
1.5       www       472:             $middlename=substr($middlename,0,16);
1.1       albertel  473:             $middlename=~s/\W//g;
                    474:             my $dfilename=
1.305     www       475:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    476:             $dumpcount++;
1.1       albertel  477:             {
1.448     albertel  478: 		my $dfh;
                    479: 		if (open($dfh,">$dfilename")) {
                    480: 		    print $dfh "$cmd\n"; 
                    481: 		    close($dfh);
                    482: 		}
1.1       albertel  483:             }
                    484:             sleep 2;
                    485:             my $wcmd='';
                    486:             {
1.448     albertel  487: 		my $dfh;
                    488: 		if (open($dfh,"<$dfilename")) {
                    489: 		    $wcmd=<$dfh>; 
                    490: 		    close($dfh);
                    491: 		}
1.1       albertel  492:             }
                    493:             chomp($wcmd);
1.7       www       494:             if ($wcmd eq $cmd) {
1.672     albertel  495: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       496:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  497:                 &logperm("D:$server:$cmd");
                    498: 	        return 'con_delayed';
                    499:             } else {
1.672     albertel  500:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       501:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  502:                 &logperm("F:$server:$cmd");
                    503:                 return 'con_failed';
                    504:             }
                    505:         }
                    506:     }
                    507:     return $answer;
1.405     albertel  508: }
                    509: 
1.755     albertel  510: # ------------------------------------------- check if return value is an error
                    511: 
                    512: sub error {
                    513:     my ($result) = @_;
1.756     albertel  514:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  515: 	if ($2 == 2) { return undef; }
                    516: 	return $1;
                    517:     }
                    518:     return undef;
                    519: }
                    520: 
1.783     albertel  521: sub convert_and_load_session_env {
                    522:     my ($lonidsdir,$handle)=@_;
                    523:     my @profile;
                    524:     {
1.917     albertel  525: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    526: 	if (!$opened) {
1.915     albertel  527: 	    return 0;
                    528: 	}
1.783     albertel  529: 	flock($idf,LOCK_SH);
                    530: 	@profile=<$idf>;
                    531: 	close($idf);
                    532:     }
                    533:     my %temp_env;
                    534:     foreach my $line (@profile) {
1.786     albertel  535: 	if ($line !~ m/=/) {
                    536: 	    return 0;
                    537: 	}
1.783     albertel  538: 	chomp($line);
                    539: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    540: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    541:     }
                    542:     unlink("$lonidsdir/$handle.id");
                    543:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    544: 	    0640)) {
                    545: 	%disk_env = %temp_env;
                    546: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    547: 	untie(%disk_env);
                    548:     }
1.786     albertel  549:     return 1;
1.783     albertel  550: }
                    551: 
1.374     www       552: # ------------------------------------------- Transfer profile into environment
1.780     albertel  553: my $env_loaded;
                    554: sub transfer_profile_to_env {
1.788     albertel  555:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    556:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       557: 
1.720     albertel  558:     if (!defined($lonidsdir)) {
                    559: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    560:     }
                    561:     if (!defined($handle)) {
                    562:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    563:     }
                    564: 
1.786     albertel  565:     my $convert;
                    566:     {
1.917     albertel  567:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    568: 	if (!$opened) {
1.915     albertel  569: 	    return;
                    570: 	}
1.786     albertel  571: 	flock($idf,LOCK_SH);
                    572: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    573: 		&GDBM_READER(),0640)) {
                    574: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    575: 	    untie(%disk_env);
                    576: 	} else {
                    577: 	    $convert = 1;
                    578: 	}
                    579:     }
                    580:     if ($convert) {
                    581: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    582: 	    &logthis("Failed to load session, or convert session.");
                    583: 	}
1.374     www       584:     }
1.783     albertel  585: 
1.786     albertel  586:     my %remove;
1.783     albertel  587:     while ( my $envname = each(%env) ) {
1.433     matthew   588:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    589:             if ($time < time-300) {
1.783     albertel  590:                 $remove{$key}++;
1.433     matthew   591:             }
                    592:         }
                    593:     }
1.783     albertel  594: 
1.619     albertel  595:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  596:     $env_loaded=1;
1.783     albertel  597:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   598:         &delenv($expired_key);
1.374     www       599:     }
1.1       albertel  600: }
                    601: 
1.916     albertel  602: # ---------------------------------------------------- Check for valid session 
                    603: sub check_for_valid_session {
1.1155    raeburn   604:     my ($r,$name) = @_;
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: 
                    636:     if (($r->user() eq '') && ($apache >= 2.4)) {
                    637:         if ($disk_env{'user.domain'} eq $r->dir_config('lonDefDomain')) {
                    638:             $r->user($disk_env{'user.name'});
                    639:         } else {
                    640:             $r->user($disk_env{'user.name'}.':'.$disk_env{'user.domain'});
                    641:         }
                    642:     }
                    643: 
1.916     albertel  644:     return $handle;
                    645: }
                    646: 
1.830     albertel  647: sub timed_flock {
                    648:     my ($file,$lock_type) = @_;
                    649:     my $failed=0;
                    650:     eval {
                    651: 	local $SIG{__DIE__}='DEFAULT';
                    652: 	local $SIG{ALRM}=sub {
                    653: 	    $failed=1;
                    654: 	    die("failed lock");
                    655: 	};
                    656: 	alarm(13);
                    657: 	flock($file,$lock_type);
                    658: 	alarm(0);
                    659:     };
                    660:     if ($failed) {
                    661: 	return undef;
                    662:     } else {
                    663: 	return 1;
                    664:     }
                    665: }
                    666: 
1.5       www       667: # ---------------------------------------------------------- Append Environment
                    668: 
                    669: sub appenv {
1.949     raeburn   670:     my ($newenv,$roles) = @_;
                    671:     if (ref($newenv) eq 'HASH') {
                    672:         foreach my $key (keys(%{$newenv})) {
                    673:             my $refused = 0;
                    674: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    675:                 $refused = 1;
                    676:                 if (ref($roles) eq 'ARRAY') {
                    677:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
                    678:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    679:                         $refused = 0;
                    680:                     }
                    681:                 }
                    682:             }
                    683:             if ($refused) {
                    684:                 &logthis("<font color=\"blue\">WARNING: ".
                    685:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    686:                          .'</font>');
                    687: 	        delete($newenv->{$key});
                    688:             } else {
                    689:                 $env{$key}=$newenv->{$key};
                    690:             }
                    691:         }
                    692:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    693:         if ($opened
                    694: 	    && &timed_flock($env_file,LOCK_EX)
                    695: 	    &&
                    696: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    697: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    698: 	    while (my ($key,$value) = each(%{$newenv})) {
                    699: 	        $disk_env{$key} = $value;
                    700: 	    }
                    701: 	    untie(%disk_env);
1.35      www       702:         }
1.191     harris41  703:     }
1.56      www       704:     return 'ok';
                    705: }
                    706: # ----------------------------------------------------- Delete from Environment
                    707: 
                    708: sub delenv {
1.1104    raeburn   709:     my ($delthis,$regexp,$roles) = @_;
                    710:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    711:         my $refused = 1;
                    712:         if (ref($roles) eq 'ARRAY') {
                    713:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    714:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    715:                 $refused = 0;
                    716:             }
                    717:         }
                    718:         if ($refused) {
                    719:             &logthis("<font color=\"blue\">WARNING: ".
                    720:                      "Attempt to delete from environment ".$delthis);
                    721:             return 'error';
                    722:         }
1.56      www       723:     }
1.917     albertel  724:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    725:     if ($opened
1.915     albertel  726: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  727: 	&&
                    728: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    729: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  730: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   731: 	    if ($regexp) {
                    732:                 if ($key=~/^$delthis/) {
                    733:                     delete($env{$key});
                    734:                     delete($disk_env{$key});
                    735:                 } 
                    736:             } else {
                    737:                 if ($key=~/^\Q$delthis\E/) {
                    738: 		    delete($env{$key});
                    739: 		    delete($disk_env{$key});
                    740: 	        }
                    741:             }
1.448     albertel  742: 	}
1.783     albertel  743: 	untie(%disk_env);
1.5       www       744:     }
                    745:     return 'ok';
1.369     albertel  746: }
                    747: 
1.790     albertel  748: sub get_env_multiple {
                    749:     my ($name) = @_;
                    750:     my @values;
                    751:     if (defined($env{$name})) {
                    752:         # exists is it an array
                    753:         if (ref($env{$name})) {
                    754:             @values=@{ $env{$name} };
                    755:         } else {
                    756:             $values[0]=$env{$name};
                    757:         }
                    758:     }
                    759:     return(@values);
                    760: }
                    761: 
1.958     www       762: # ------------------------------------------------------------------- Locking
                    763: 
                    764: sub set_lock {
                    765:     my ($text)=@_;
                    766:     $locknum++;
                    767:     my $id=$$.'-'.$locknum;
                    768:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    769:              'session.lock.'.$id => $text});
                    770:     return $id;
                    771: }
                    772: 
                    773: sub get_locks {
                    774:     my $num=0;
                    775:     my %texts=();
                    776:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    777:        if ($lock=~/\w/) {
                    778:           $num++;
                    779:           $texts{$lock}=$env{'session.lock.'.$lock};
                    780:        }
                    781:    }
                    782:    return ($num,%texts);
                    783: }
                    784: 
                    785: sub remove_lock {
                    786:     my ($id)=@_;
                    787:     my $newlocks='';
                    788:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    789:        if (($lock=~/\w/) && ($lock ne $id)) {
                    790:           $newlocks.=','.$lock;
                    791:        }
                    792:     }
                    793:     &appenv({'session.locks' => $newlocks});
                    794:     &delenv('session.lock.'.$id);
                    795: }
                    796: 
                    797: sub remove_all_locks {
                    798:     my $activelocks=$env{'session.locks'};
                    799:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    800:        if ($lock=~/\w/) {
                    801:           &remove_lock($lock);
                    802:        }
                    803:     }
                    804: }
                    805: 
                    806: 
1.369     albertel  807: # ------------------------------------------ Find out current server userload
                    808: sub userload {
                    809:     my $numusers=0;
                    810:     {
                    811: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    812: 	my $filename;
                    813: 	my $curtime=time;
                    814: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  815: 	    next if ($filename eq '.' || $filename eq '..');
                    816: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  817: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  818: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  819: 	}
                    820: 	closedir(LONIDS);
                    821:     }
                    822:     my $userloadpercent=0;
                    823:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    824:     if ($maxuserload) {
1.371     albertel  825: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  826:     }
1.372     albertel  827:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  828:     return $userloadpercent;
1.283     www       829: }
                    830: 
1.1       albertel  831: # ------------------------------ Find server with least workload from spare.tab
1.11      www       832: 
1.1       albertel  833: sub spareserver {
1.1083    raeburn   834:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  835:     my $spare_server;
1.370     albertel  836:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  837:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    838:                                                      :  $userloadpercent;
1.1083    raeburn   839:     my ($uint_dom,$remotesessions);
                    840:     if (($udom ne '') && (&domain($udom) ne '')) {
                    841:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    842:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    843:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    844:         $remotesessions = $udomdefaults{'remotesessions'};
                    845:     }
1.1123    raeburn   846:     my $spareshash = &this_host_spares($udom);
                    847:     if (ref($spareshash) eq 'HASH') {
                    848:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    849:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    850:                 if ($uint_dom) {
                    851:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    852:                                                  $try_server));
                    853:                 }
                    854: 	        ($spare_server, $lowest_load) =
                    855: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    856:             }
1.1083    raeburn   857:         }
1.784     albertel  858: 
1.1123    raeburn   859:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    860: 
                    861:         if (!$found_server) {
                    862:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    863: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
                    864:                     if ($uint_dom) {
                    865:                         next unless (&spare_can_host($udom,$uint_dom,
                    866:                                                      $remotesessions,$try_server));
                    867:                     }
                    868: 	            ($spare_server, $lowest_load) =
                    869: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    870:                 }
                    871: 	    }
                    872:         }
1.784     albertel  873:     }
                    874: 
                    875:     if (!$want_server_name) {
1.968     raeburn   876:         my $protocol = 'http';
                    877:         if ($protocol{$spare_server} eq 'https') {
                    878:             $protocol = $protocol{$spare_server};
                    879:         }
1.1001    raeburn   880:         if (defined($spare_server)) {
                    881:             my $hostname = &hostname($spare_server);
1.1083    raeburn   882:             if (defined($hostname)) {
1.1001    raeburn   883: 	        $spare_server = $protocol.'://'.$hostname;
                    884:             }
                    885:         }
1.784     albertel  886:     }
                    887:     return $spare_server;
                    888: }
                    889: 
                    890: sub compare_server_load {
                    891:     my ($try_server, $spare_server, $lowest_load) = @_;
                    892: 
                    893:     my $loadans     = &reply('load',    $try_server);
                    894:     my $userloadans = &reply('userload',$try_server);
                    895: 
                    896:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   897: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  898:     }
                    899: 
                    900:     my $load;
                    901:     if ($loadans =~ /\d/) {
                    902: 	if ($userloadans =~ /\d/) {
                    903: 	    #both are numbers, pick the bigger one
                    904: 	    $load = ($loadans > $userloadans) ? $loadans 
                    905: 		                              : $userloadans;
1.411     albertel  906: 	} else {
1.784     albertel  907: 	    $load = $loadans;
1.411     albertel  908: 	}
1.784     albertel  909:     } else {
                    910: 	$load = $userloadans;
                    911:     }
                    912: 
                    913:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    914: 	$spare_server = $try_server;
                    915: 	$lowest_load  = $load;
1.370     albertel  916:     }
1.784     albertel  917:     return ($spare_server,$lowest_load);
1.202     matthew   918: }
1.914     albertel  919: 
                    920: # --------------------------- ask offload servers if user already has a session
                    921: sub find_existing_session {
                    922:     my ($udom,$uname) = @_;
1.1123    raeburn   923:     my $spareshash = &this_host_spares($udom);
                    924:     if (ref($spareshash) eq 'HASH') {
                    925:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    926:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    927:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    928:             }
                    929:         }
                    930:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                    931:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                    932:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    933:             }
                    934:         }
1.914     albertel  935:     }
                    936:     return;
                    937: }
                    938: 
                    939: # -------------------------------- ask if server already has a session for user
                    940: sub has_user_session {
                    941:     my ($lonid,$udom,$uname) = @_;
                    942:     my $result = &reply(join(':','userhassession',
                    943: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    944:     return 1 if ($result eq 'ok');
                    945: 
                    946:     return 0;
                    947: }
                    948: 
1.1076    raeburn   949: # --------- determine least loaded server in a user's domain which allows login
                    950: 
                    951: sub choose_server {
1.1115    raeburn   952:     my ($udom,$checkloginvia) = @_;
1.1076    raeburn   953:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn   954:     my %servers = &get_servers($udom);
1.1076    raeburn   955:     my $lowest_load = 30000;
1.1151    raeburn   956:     my ($login_host,$hostname,$portal_path,$isredirect);
1.1076    raeburn   957:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn   958:         my $loginvia;
                    959:         if ($checkloginvia) {
                    960:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn   961:             if ($loginvia) {
                    962:                 my ($server,$path) = split(/:/,$loginvia);
                    963:                 ($login_host, $lowest_load) =
                    964:                     &compare_server_load($server, $login_host, $lowest_load);
                    965:                 if ($login_host eq $server) {
                    966:                     $portal_path = $path;
1.1151    raeburn   967:                     $isredirect = 1;
1.1116    raeburn   968:                 }
                    969:             } else {
                    970:                 ($login_host, $lowest_load) =
                    971:                     &compare_server_load($lonhost, $login_host, $lowest_load);
                    972:                 if ($login_host eq $lonhost) {
                    973:                     $portal_path = '';
1.1151    raeburn   974:                     $isredirect = ''; 
1.1116    raeburn   975:                 }
                    976:             }
                    977:         } else {
1.1076    raeburn   978:             ($login_host, $lowest_load) =
1.1116    raeburn   979:                 &compare_server_load($lonhost, $login_host, $lowest_load);
1.1076    raeburn   980:         }
                    981:     }
                    982:     if ($login_host ne '') {
1.1116    raeburn   983:         $hostname = &hostname($login_host);
1.1076    raeburn   984:     }
1.1151    raeburn   985:     return ($login_host,$hostname,$portal_path,$isredirect);
1.1076    raeburn   986: }
                    987: 
1.202     matthew   988: # --------------------------------------------- Try to change a user's password
                    989: 
                    990: sub changepass {
1.799     raeburn   991:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   992:     $currentpass = &escape($currentpass);
                    993:     $newpass     = &escape($newpass);
1.1030    raeburn   994:     my $lonhost = $perlvar{'lonHostID'};
                    995:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew   996: 		       $server);
                    997:     if (! $answer) {
                    998: 	&logthis("No reply on password change request to $server ".
                    999: 		 "by $uname in domain $udom.");
                   1000:     } elsif ($answer =~ "^ok") {
                   1001:         &logthis("$uname in $udom successfully changed their password ".
                   1002: 		 "on $server.");
                   1003:     } elsif ($answer =~ "^pwchange_failure") {
                   1004: 	&logthis("$uname in $udom was unable to change their password ".
                   1005: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1006: 		 "or pwchange");
                   1007:     } elsif ($answer =~ "^non_authorized") {
                   1008:         &logthis("$uname in $udom did not get their password correct when ".
                   1009: 		 "attempting to change it on $server.");
                   1010:     } elsif ($answer =~ "^auth_mode_error") {
                   1011:         &logthis("$uname in $udom attempted to change their password despite ".
                   1012: 		 "not being locally or internally authenticated on $server.");
                   1013:     } elsif ($answer =~ "^unknown_user") {
                   1014:         &logthis("$uname in $udom attempted to change their password ".
                   1015: 		 "on $server but were unable to because $server is not ".
                   1016: 		 "their home server.");
                   1017:     } elsif ($answer =~ "^refused") {
                   1018: 	&logthis("$server refused to change $uname in $udom password because ".
                   1019: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1020:     } elsif ($answer =~ "invalid_client") {
                   1021:         &logthis("$server refused to change $uname in $udom password because ".
                   1022:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1023:     }
                   1024:     return $answer;
1.1       albertel 1025: }
                   1026: 
1.169     harris41 1027: # ----------------------- Try to determine user's current authentication scheme
                   1028: 
                   1029: sub queryauthenticate {
                   1030:     my ($uname,$udom)=@_;
1.456     albertel 1031:     my $uhome=&homeserver($uname,$udom);
                   1032:     if (!$uhome) {
                   1033: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1034: 	return 'no_host';
                   1035:     }
                   1036:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1037:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1038: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1039:     }
1.456     albertel 1040:     return $answer;
1.169     harris41 1041: }
                   1042: 
1.1       albertel 1043: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1044: 
1.1       albertel 1045: sub authenticate {
1.1073    raeburn  1046:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1047:     $upass=&escape($upass);
                   1048:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1049:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1050:     my $newhome;
1.836     www      1051:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1052: # Maybe the machine was offline and only re-appeared again recently?
                   1053:         &reconlonc();
                   1054: # One more
1.952     raeburn  1055: 	$uhome=&homeserver($uname,$udom,1);
                   1056:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1057:             if (defined(&domain($udom,'primary'))) {
                   1058:                 $newhome=&domain($udom,'primary');
                   1059:             }
                   1060:             if ($newhome ne '') {
                   1061:                 $uhome = $newhome;
                   1062:             }
                   1063:         }
1.836     www      1064: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1065: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1066: 	    return 'no_host';
                   1067:         }
1.1       albertel 1068:     }
1.1073    raeburn  1069:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1070:     if ($answer eq 'authorized') {
1.952     raeburn  1071:         if ($newhome) {
                   1072:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1073:             return 'no_account_on_host'; 
                   1074:         } else {
                   1075:             &logthis("User $uname at $udom authorized by $uhome");
                   1076:             return $uhome;
                   1077:         }
1.471     albertel 1078:     }
                   1079:     if ($answer eq 'non_authorized') {
                   1080: 	&logthis("User $uname at $udom rejected by $uhome");
                   1081: 	return 'no_host'; 
1.9       www      1082:     }
1.471     albertel 1083:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1084:     return 'no_host';
                   1085: }
                   1086: 
1.1073    raeburn  1087: sub can_host_session {
1.1074    raeburn  1088:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1089:     my $canhost = 1;
1.1074    raeburn  1090:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1091:     if (ref($remotesessions) eq 'HASH') {
                   1092:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1093:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1094:                 $canhost = 0;
                   1095:             } else {
                   1096:                 $canhost = 1;
                   1097:             }
                   1098:         }
                   1099:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1100:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1101:                 $canhost = 1;
                   1102:             } else {
                   1103:                 $canhost = 0;
                   1104:             }
                   1105:         }
                   1106:         if ($canhost) {
                   1107:             if ($remotesessions->{'version'} ne '') {
                   1108:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1109:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1110:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1111:                         my $major = $1;
                   1112:                         my $minor = $2;
                   1113:                         if (($major < $reqmajor ) ||
                   1114:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1115:                             $canhost = 0;
                   1116:                         }
                   1117:                     } else {
                   1118:                         $canhost = 0;
                   1119:                     }
                   1120:                 }
                   1121:             }
                   1122:         }
                   1123:     }
                   1124:     if ($canhost) {
                   1125:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1126:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1127:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1128:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1129:                 if (($uint_dom ne '') && 
                   1130:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1131:                     $canhost = 0;
                   1132:                 } else {
                   1133:                     $canhost = 1;
                   1134:                 }
                   1135:             }
                   1136:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1137:                 if (($uint_dom ne '') && 
                   1138:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1139:                     $canhost = 1;
                   1140:                 } else {
                   1141:                     $canhost = 0;
                   1142:                 }
                   1143:             }
                   1144:         }
                   1145:     }
                   1146:     return $canhost;
                   1147: }
                   1148: 
1.1083    raeburn  1149: sub spare_can_host {
                   1150:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1151:     my $canhost=1;
                   1152:     my @intdoms;
                   1153:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
                   1154:     if (ref($internet_names) eq 'ARRAY') {
                   1155:         @intdoms = @{$internet_names};
                   1156:     }
                   1157:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1158:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
                   1159:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   1160:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   1161:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
                   1162:         $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1163:                                      $remotesessions,
                   1164:                                      $defdomdefaults{'hostedsessions'});
                   1165:     }
                   1166:     return $canhost;
                   1167: }
                   1168: 
1.1123    raeburn  1169: sub this_host_spares {
                   1170:     my ($dom) = @_;
1.1126    raeburn  1171:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1172:     my @hosts = &current_machine_ids();
                   1173:     foreach my $lonhost (@hosts) {
                   1174:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1175:             $dom_in_use = $dom;
                   1176:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1177:             last;
                   1178:         }
                   1179:     }
1.1126    raeburn  1180:     if ($dom_in_use ne '') {
                   1181:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1182:     }
                   1183:     if (ref($result) ne 'HASH') {
                   1184:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1185:         $dom_in_use = &host_domain($lonhost_in_use);
                   1186:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1187:         if (ref($result) ne 'HASH') {
                   1188:             $result = \%spareid;
                   1189:         }
                   1190:     }
                   1191:     return $result;
                   1192: }
                   1193: 
                   1194: sub spares_for_offload  {
                   1195:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1196:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1197:     if (defined($cached)) {
                   1198:         return $result;
                   1199:     } else {
1.1126    raeburn  1200:         my $cachetime = 60*60*24;
                   1201:         my %domconfig =
                   1202:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1203:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1204:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1205:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1206:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1207:                 }
                   1208:             }
                   1209:         }
                   1210:     }
1.1126    raeburn  1211:     return;
1.1123    raeburn  1212: }
                   1213: 
1.1129    raeburn  1214: sub get_lonbalancer_config {
                   1215:     my ($servers) = @_;
                   1216:     my ($currbalancer,$currtargets);
                   1217:     if (ref($servers) eq 'HASH') {
                   1218:         foreach my $server (keys(%{$servers})) {
                   1219:             my %what = (
                   1220:                          spareid => 1,
                   1221:                          perlvar => 1,
                   1222:                        );
                   1223:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1224:             if ($result eq 'ok') {
                   1225:                 if (ref($returnhash) eq 'HASH') {
                   1226:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1227:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1228:                             $currbalancer = $server;
                   1229:                             $currtargets = {};
                   1230:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1231:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1232:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1233:                                 }
                   1234:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1235:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1236:                                 }
                   1237:                             }
                   1238:                             last;
                   1239:                         }
                   1240:                     }
                   1241:                 }
                   1242:             }
                   1243:         }
                   1244:     }
                   1245:     return ($currbalancer,$currtargets);
                   1246: }
                   1247: 
                   1248: sub check_loadbalancing {
                   1249:     my ($uname,$udom) = @_;
1.1172.2.12  raeburn  1250:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
                   1251:         $rule_in_effect,$offloadto,$otherserver);
1.1129    raeburn  1252:     my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4  raeburn  1253:     my @hosts = &current_machine_ids();
1.1129    raeburn  1254:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1255:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1256:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1257:     my $serverhomedom = &host_domain($lonhost);
                   1258: 
                   1259:     my $cachetime = 60*60*24;
                   1260: 
                   1261:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1262:         $dom_in_use = $udom;
                   1263:         $homeintdom = 1;
                   1264:     } else {
                   1265:         $dom_in_use = $serverhomedom;
                   1266:     }
                   1267:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1268:     unless (defined($cached)) {
                   1269:         my %domconfig =
                   1270:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1271:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1272:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1273:         }
                   1274:     }
                   1275:     if (ref($result) eq 'HASH') {
1.1172.2.12  raeburn  1276:         ($is_balancer,$currtargets,$currrules) =
                   1277:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1278:         if ($is_balancer) {
                   1279:             if (ref($currrules) eq 'HASH') {
                   1280:                 if ($homeintdom) {
                   1281:                     if ($uname ne '') {
                   1282:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1283:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1284:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1285:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1286:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1287:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1288:                             }
                   1289:                         }
                   1290:                         if ($rule_in_effect eq '') {
                   1291:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1292:                             if ($userenv{'inststatus'} ne '') {
                   1293:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1294:                                 my ($othertitle,$usertypes,$types) =
                   1295:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1296:                                 if (ref($types) eq 'ARRAY') {
                   1297:                                     foreach my $type (@{$types}) {
                   1298:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1299:                                             if (exists($currrules->{$type})) {
                   1300:                                                 $rule_in_effect = $currrules->{$type};
                   1301:                                             }
                   1302:                                         }
                   1303:                                     }
                   1304:                                 }
                   1305:                             } else {
                   1306:                                 if (exists($currrules->{'default'})) {
                   1307:                                     $rule_in_effect = $currrules->{'default'};
                   1308:                                 }
                   1309:                             }
                   1310:                         }
                   1311:                     } else {
                   1312:                         if (exists($currrules->{'default'})) {
                   1313:                             $rule_in_effect = $currrules->{'default'};
                   1314:                         }
                   1315:                     }
                   1316:                 } else {
                   1317:                     if ($currrules->{'_LC_external'} ne '') {
                   1318:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1319:                     }
                   1320:                 }
                   1321:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1322:                                                        $uname,$udom);
                   1323:             }
                   1324:         }
                   1325:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35! raeburn  1326:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1327:         unless (defined($cached)) {
                   1328:             my %domconfig =
                   1329:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1330:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1331:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1332:             }
                   1333:         }
                   1334:         if (ref($result) eq 'HASH') {
1.1172.2.12  raeburn  1335:             ($is_balancer,$currtargets,$currrules) =
                   1336:                 &check_balancer_result($result,@hosts);
                   1337:             if ($is_balancer) {
1.1129    raeburn  1338:                 if (ref($currrules) eq 'HASH') {
                   1339:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1340:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1341:                     }
                   1342:                 }
                   1343:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1344:                                                        $uname,$udom);
                   1345:             }
                   1346:         } else {
                   1347:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1348:                 $is_balancer = 1;
                   1349:                 $offloadto = &this_host_spares($dom_in_use);
                   1350:             }
                   1351:         }
                   1352:     } else {
                   1353:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1354:             $is_balancer = 1;
                   1355:             $offloadto = &this_host_spares($dom_in_use);
                   1356:         }
                   1357:     }
1.1172.2.5  raeburn  1358:     if ($is_balancer) {
                   1359:         my $lowest_load = 30000;
                   1360:         if (ref($offloadto) eq 'HASH') {
                   1361:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1362:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1363:                     ($otherserver,$lowest_load) =
                   1364:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1365:                 }
1.1129    raeburn  1366:             }
1.1172.2.5  raeburn  1367:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1368: 
1.1172.2.5  raeburn  1369:             if (!$found_server) {
                   1370:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1371:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1372:                         ($otherserver,$lowest_load) =
                   1373:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1374:                     }
                   1375:                 }
                   1376:             }
                   1377:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1378:             if (@{$offloadto} == 1) {
                   1379:                 $otherserver = $offloadto->[0];
                   1380:             } elsif (@{$offloadto} > 1) {
                   1381:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1382:                     ($otherserver,$lowest_load) =
                   1383:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1384:                 }
                   1385:             }
                   1386:         }
1.1172.2.5  raeburn  1387:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1388:             $is_balancer = 0;
                   1389:             if ($uname ne '' && $udom ne '') {
                   1390:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1391: 
                   1392:                     &appenv({'user.loadbalexempt'     => $lonhost,
                   1393:                              'user.loadbalcheck.time' => time});
                   1394:                 }
1.1129    raeburn  1395:             }
                   1396:         }
                   1397:     }
                   1398:     return ($is_balancer,$otherserver);
                   1399: }
                   1400: 
1.1172.2.12  raeburn  1401: sub check_balancer_result {
                   1402:     my ($result,@hosts) = @_;
                   1403:     my ($is_balancer,$currtargets,$currrules);
                   1404:     if (ref($result) eq 'HASH') {
                   1405:         if ($result->{'lonhost'} ne '') {
                   1406:             my $currbalancer = $result->{'lonhost'};
                   1407:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1408:                 $is_balancer = 1;
                   1409:                 $currtargets = $result->{'targets'};
                   1410:                 $currrules = $result->{'rules'};
                   1411:             }
                   1412:         } else {
                   1413:             foreach my $key (keys(%{$result})) {
                   1414:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1415:                     (ref($result->{$key}) eq 'HASH')) {
                   1416:                     $is_balancer = 1;
                   1417:                     $currrules = $result->{$key}{'rules'};
                   1418:                     $currtargets = $result->{$key}{'targets'};
                   1419:                     last;
                   1420:                 }
                   1421:             }
                   1422:         }
                   1423:     }
                   1424:     return ($is_balancer,$currtargets,$currrules);
                   1425: }
                   1426: 
1.1129    raeburn  1427: sub get_loadbalancer_targets {
                   1428:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1429:     my $offloadto;
1.1172.2.4  raeburn  1430:     if ($rule_in_effect eq 'none') {
                   1431:         return [$perlvar{'lonHostID'}];
                   1432:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1433:         $offloadto = $currtargets;
                   1434:     } else {
                   1435:         if ($rule_in_effect eq 'homeserver') {
                   1436:             my $homeserver = &homeserver($uname,$udom);
                   1437:             if ($homeserver ne 'no_host') {
                   1438:                 $offloadto = [$homeserver];
                   1439:             }
                   1440:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1441:             my %domconfig =
                   1442:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1443:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1444:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1445:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1446:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1447:                     }
                   1448:                 }
                   1449:             } else {
1.1172.2.7  raeburn  1450:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1451:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1452:                 if (&hostname($remotebalancer) ne '') {
                   1453:                     $offloadto = [$remotebalancer];
                   1454:                 }
                   1455:             }
                   1456:         } elsif (&hostname($rule_in_effect) ne '') {
                   1457:             $offloadto = [$rule_in_effect];
                   1458:         }
                   1459:     }
                   1460:     return $offloadto;
                   1461: }
                   1462: 
1.1127    raeburn  1463: sub internet_dom_servers {
                   1464:     my ($dom) = @_;
                   1465:     my (%uniqservers,%servers);
                   1466:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1467:     my @machinedoms = &machine_domains($primaryserver);
                   1468:     foreach my $mdom (@machinedoms) {
                   1469:         my %currservers = %servers;
                   1470:         my %server = &get_servers($mdom);
                   1471:         %servers = (%currservers,%server);
                   1472:     }
                   1473:     my %by_hostname;
                   1474:     foreach my $id (keys(%servers)) {
                   1475:         push(@{$by_hostname{$servers{$id}}},$id);
                   1476:     }
                   1477:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1478:         if (@{$by_hostname{$hostname}} > 1) {
                   1479:             my $match = 0;
                   1480:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1481:                 if (&host_domain($id) eq $dom) {
                   1482:                     $uniqservers{$id} = $hostname;
                   1483:                     $match = 1;
                   1484:                 }
                   1485:             }
                   1486:             unless ($match) {
                   1487:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1488:             }
                   1489:         } else {
                   1490:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1491:         }
                   1492:     }
                   1493:     return %uniqservers;
                   1494: }
                   1495: 
1.1       albertel 1496: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1497: 
1.599     albertel 1498: my %homecache;
1.1       albertel 1499: sub homeserver {
1.230     stredwic 1500:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1501:     my $index="$uname:$udom";
1.426     albertel 1502: 
1.599     albertel 1503:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1504: 
                   1505:     my %servers = &get_servers($udom,'library');
                   1506:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1507:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1508: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1509: 
                   1510: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1511: 	if ($answer eq 'found') {
                   1512: 	    delete($badServerCache{$tryserver}); 
                   1513: 	    return $homecache{$index}=$tryserver;
                   1514: 	} elsif ($answer eq 'no_host') {
                   1515: 	    $badServerCache{$tryserver}=1;
                   1516: 	}
1.1       albertel 1517:     }    
                   1518:     return 'no_host';
1.70      www      1519: }
                   1520: 
                   1521: # ------------------------------------- Find the usernames behind a list of IDs
                   1522: 
                   1523: sub idget {
                   1524:     my ($udom,@ids)=@_;
                   1525:     my %returnhash=();
                   1526:     
1.841     albertel 1527:     my %servers = &get_servers($udom,'library');
                   1528:     foreach my $tryserver (keys(%servers)) {
                   1529: 	my $idlist=join('&',@ids);
                   1530: 	$idlist=~tr/A-Z/a-z/; 
                   1531: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1532: 	my @answer=();
                   1533: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1534: 	    @answer=split(/\&/,$reply);
                   1535: 	}                    ;
                   1536: 	my $i;
                   1537: 	for ($i=0;$i<=$#ids;$i++) {
                   1538: 	    if ($answer[$i]) {
                   1539: 		$returnhash{$ids[$i]}=$answer[$i];
                   1540: 	    } 
                   1541: 	}
                   1542:     } 
1.70      www      1543:     return %returnhash;
                   1544: }
                   1545: 
                   1546: # ------------------------------------- Find the IDs behind a list of usernames
                   1547: 
                   1548: sub idrget {
                   1549:     my ($udom,@unames)=@_;
                   1550:     my %returnhash=();
1.800     albertel 1551:     foreach my $uname (@unames) {
                   1552:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1553:     }
1.70      www      1554:     return %returnhash;
                   1555: }
                   1556: 
                   1557: # ------------------------------- Store away a list of names and associated IDs
                   1558: 
                   1559: sub idput {
                   1560:     my ($udom,%ids)=@_;
                   1561:     my %servers=();
1.800     albertel 1562:     foreach my $uname (keys(%ids)) {
                   1563: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1564:         my $uhom=&homeserver($uname,$udom);
1.70      www      1565:         if ($uhom ne 'no_host') {
1.800     albertel 1566:             my $id=&escape($ids{$uname});
1.70      www      1567:             $id=~tr/A-Z/a-z/;
1.800     albertel 1568:             my $esc_unam=&escape($uname);
1.70      www      1569: 	    if ($servers{$uhom}) {
1.800     albertel 1570: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1571:             } else {
1.800     albertel 1572:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1573:             }
                   1574:         }
1.191     harris41 1575:     }
1.800     albertel 1576:     foreach my $server (keys(%servers)) {
                   1577:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1578:     }
1.344     www      1579: }
                   1580: 
1.1172.2.30  raeburn  1581: # ---------------------------------------- Delete unwanted IDs from ids.db file
                   1582: 
                   1583: sub iddel {
                   1584:     my ($udom,$idshashref,$uhome)=@_;
                   1585:     my %result=();
                   1586:     unless (ref($idshashref) eq 'HASH') {
                   1587:         return %result;
                   1588:     }
                   1589:     my %servers=();
                   1590:     while (my ($id,$uname) = each(%{$idshashref})) {
                   1591:         my $uhom;
                   1592:         if ($uhome) {
                   1593:             $uhom = $uhome;
                   1594:         } else {
                   1595:             $uhom=&homeserver($uname,$udom);
                   1596:         }
                   1597:         if ($uhom ne 'no_host') {
                   1598:             if ($servers{$uhom}) {
                   1599:                 $servers{$uhom}.='&'.&escape($id);
                   1600:             } else {
                   1601:                 $servers{$uhom}=&escape($id);
                   1602:             }
                   1603:         }
                   1604:     }
                   1605:     foreach my $server (keys(%servers)) {
                   1606:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1607:     }
                   1608:     return %result;
                   1609: }
                   1610: 
1.1023    raeburn  1611: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1612: sub dump_dom {
1.1165    droeschl 1613:     my ($namespace, $udom, $regexp) = @_;
                   1614: 
                   1615:     $udom ||= $env{'user.domain'};
                   1616: 
                   1617:     return () unless $udom;
                   1618: 
                   1619:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1620: }
                   1621: 
1.1023    raeburn  1622: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1623: 
                   1624: sub get_dom {
1.860     raeburn  1625:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn  1626:     my $items='';
                   1627:     foreach my $item (@$storearr) {
                   1628:         $items.=&escape($item).'&';
                   1629:     }
                   1630:     $items=~s/\&$//;
1.860     raeburn  1631:     if (!$udom) {
                   1632:         $udom=$env{'user.domain'};
                   1633:         if (defined(&domain($udom,'primary'))) {
                   1634:             $uhome=&domain($udom,'primary');
                   1635:         } else {
1.874     albertel 1636:             undef($uhome);
1.860     raeburn  1637:         }
                   1638:     } else {
                   1639:         if (!$uhome) {
                   1640:             if (defined(&domain($udom,'primary'))) {
                   1641:                 $uhome=&domain($udom,'primary');
                   1642:             }
                   1643:         }
                   1644:     }
                   1645:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1646:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1647:         my %returnhash;
1.875     albertel 1648:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1649:             return %returnhash;
                   1650:         }
1.806     raeburn  1651:         my @pairs=split(/\&/,$rep);
                   1652:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1653:             return @pairs;
                   1654:         }
                   1655:         my $i=0;
                   1656:         foreach my $item (@$storearr) {
                   1657:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1658:             $i++;
                   1659:         }
                   1660:         return %returnhash;
                   1661:     } else {
1.880     banghart 1662:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1663:     }
                   1664: }
                   1665: 
                   1666: # -------------------------------------------- put items in domain db files 
                   1667: 
                   1668: sub put_dom {
1.860     raeburn  1669:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1670:     if (!$udom) {
                   1671:         $udom=$env{'user.domain'};
                   1672:         if (defined(&domain($udom,'primary'))) {
                   1673:             $uhome=&domain($udom,'primary');
                   1674:         } else {
1.874     albertel 1675:             undef($uhome);
1.860     raeburn  1676:         }
                   1677:     } else {
                   1678:         if (!$uhome) {
                   1679:             if (defined(&domain($udom,'primary'))) {
                   1680:                 $uhome=&domain($udom,'primary');
                   1681:             }
                   1682:         }
                   1683:     } 
                   1684:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1685:         my $items='';
                   1686:         foreach my $item (keys(%$storehash)) {
                   1687:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1688:         }
                   1689:         $items=~s/\&$//;
                   1690:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1691:     } else {
1.860     raeburn  1692:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1693:     }
                   1694: }
                   1695: 
1.1023    raeburn  1696: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1697: sub newput_dom {
1.1023    raeburn  1698:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1699:     my $result;
                   1700:     if (!$udom) {
                   1701:         $udom=$env{'user.domain'};
                   1702:     }
1.1023    raeburn  1703:     if ($udom) {
                   1704:         my $uname = &get_domainconfiguser($udom);
                   1705:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1706:     }
                   1707:     return $result;
                   1708: }
                   1709: 
1.1023    raeburn  1710: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1711: sub del_dom {
1.1023    raeburn  1712:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1713:     if (ref($storearr) eq 'ARRAY') {
                   1714:         if (!$udom) {
                   1715:             $udom=$env{'user.domain'};
                   1716:         }
1.1023    raeburn  1717:         if ($udom) {
                   1718:             my $uname = &get_domainconfiguser($udom); 
                   1719:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1720:         }
                   1721:     }
                   1722: }
                   1723: 
1.1023    raeburn  1724: # ----------------------------------construct domainconfig user for a domain 
                   1725: sub get_domainconfiguser {
                   1726:     my ($udom) = @_;
                   1727:     return $udom.'-domainconfig';
                   1728: }
                   1729: 
1.837     raeburn  1730: sub retrieve_inst_usertypes {
                   1731:     my ($udom) = @_;
                   1732:     my (%returnhash,@order);
1.989     raeburn  1733:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1734:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1735:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
                   1736:         %returnhash = %{$domdefs{'inststatustypes'}};
                   1737:         @order = @{$domdefs{'inststatusorder'}};
                   1738:     } else {
                   1739:         if (defined(&domain($udom,'primary'))) {
                   1740:             my $uhome=&domain($udom,'primary');
                   1741:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1742:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1743:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1744:                 return (\%returnhash,\@order);
                   1745:             }
                   1746:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1747:             my @pairs=split(/\&/,$hashitems);
                   1748:             foreach my $item (@pairs) {
                   1749:                 my ($key,$value)=split(/=/,$item,2);
                   1750:                 $key = &unescape($key);
                   1751:                 next if ($key =~ /^error: 2 /);
                   1752:                 $returnhash{$key}=&thaw_unescape($value);
                   1753:             }
                   1754:             my @esc_order = split(/\&/,$orderitems);
                   1755:             foreach my $item (@esc_order) {
                   1756:                 push(@order,&unescape($item));
                   1757:             }
                   1758:         } else {
                   1759:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1760:         }
                   1761:     }
                   1762:     return (\%returnhash,\@order);
                   1763: }
                   1764: 
1.868     raeburn  1765: sub is_domainimage {
                   1766:     my ($url) = @_;
                   1767:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1768:         if (&domain($1) ne '') {
                   1769:             return '1';
                   1770:         }
                   1771:     }
                   1772:     return;
                   1773: }
                   1774: 
1.899     raeburn  1775: sub inst_directory_query {
                   1776:     my ($srch) = @_;
                   1777:     my $udom = $srch->{'srchdomain'};
                   1778:     my %results;
                   1779:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1780:     my $outcome;
1.899     raeburn  1781:     if ($homeserver ne '') {
1.904     albertel 1782: 	my $queryid=&reply("querysend:instdirsearch:".
                   1783: 			   &escape($srch->{'srchby'}).':'.
                   1784: 			   &escape($srch->{'srchterm'}).':'.
                   1785: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1786: 	my $host=&hostname($homeserver);
                   1787: 	if ($queryid !~/^\Q$host\E\_/) {
                   1788: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1789: 	    return;
                   1790: 	}
                   1791: 	my $response = &get_query_reply($queryid);
                   1792: 	my $maxtries = 5;
                   1793: 	my $tries = 1;
                   1794: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1795: 	    $response = &get_query_reply($queryid);
                   1796: 	    $tries ++;
                   1797: 	}
                   1798: 
                   1799:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1800:             if ($response eq 'unavailable') {
                   1801:                 $outcome = $response;
                   1802:             } else {
                   1803:                 $outcome = 'ok';
                   1804:                 my @matches = split(/\n/,$response);
                   1805:                 foreach my $match (@matches) {
                   1806:                     my ($key,$value) = split(/=/,$match);
                   1807:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1808:                 }
1.899     raeburn  1809:             }
                   1810:         }
                   1811:     }
1.909     raeburn  1812:     return ($outcome,%results);
1.899     raeburn  1813: }
                   1814: 
                   1815: sub usersearch {
                   1816:     my ($srch) = @_;
                   1817:     my $dom = $srch->{'srchdomain'};
                   1818:     my %results;
                   1819:     my %libserv = &all_library();
                   1820:     my $query = 'usersearch';
                   1821:     foreach my $tryserver (keys(%libserv)) {
                   1822:         if (&host_domain($tryserver) eq $dom) {
                   1823:             my $host=&hostname($tryserver);
                   1824:             my $queryid=
1.911     raeburn  1825:                 &reply("querysend:".&escape($query).':'.
                   1826:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1827:                        &escape($srch->{'srchtype'}).':'.
                   1828:                        &escape($srch->{'srchterm'}),$tryserver);
                   1829:             if ($queryid !~/^\Q$host\E\_/) {
                   1830:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1831:                 next;
1.899     raeburn  1832:             }
                   1833:             my $reply = &get_query_reply($queryid);
                   1834:             my $maxtries = 1;
                   1835:             my $tries = 1;
                   1836:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1837:                 $reply = &get_query_reply($queryid);
                   1838:                 $tries ++;
                   1839:             }
                   1840:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1841:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1842:             } else {
1.911     raeburn  1843:                 my @matches;
                   1844:                 if ($reply =~ /\n/) {
                   1845:                     @matches = split(/\n/,$reply);
                   1846:                 } else {
                   1847:                     @matches = split(/\&/,$reply);
                   1848:                 }
1.899     raeburn  1849:                 foreach my $match (@matches) {
                   1850:                     my ($uname,$udom,%userhash);
1.911     raeburn  1851:                     foreach my $entry (split(/:/,$match)) {
                   1852:                         my ($key,$value) =
                   1853:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1854:                         $userhash{$key} = $value;
                   1855:                         if ($key eq 'username') {
                   1856:                             $uname = $value;
                   1857:                         } elsif ($key eq 'domain') {
                   1858:                             $udom = $value;
1.911     raeburn  1859:                         }
1.899     raeburn  1860:                     }
                   1861:                     $results{$uname.':'.$udom} = \%userhash;
                   1862:                 }
                   1863:             }
                   1864:         }
                   1865:     }
                   1866:     return %results;
                   1867: }
                   1868: 
1.912     raeburn  1869: sub get_instuser {
                   1870:     my ($udom,$uname,$id) = @_;
                   1871:     my $homeserver = &domain($udom,'primary');
                   1872:     my ($outcome,%results);
                   1873:     if ($homeserver ne '') {
                   1874:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1875:                            &escape($id).':'.&escape($udom),$homeserver);
                   1876:         my $host=&hostname($homeserver);
                   1877:         if ($queryid !~/^\Q$host\E\_/) {
                   1878:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1879:             return;
                   1880:         }
                   1881:         my $response = &get_query_reply($queryid);
                   1882:         my $maxtries = 5;
                   1883:         my $tries = 1;
                   1884:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1885:             $response = &get_query_reply($queryid);
                   1886:             $tries ++;
                   1887:         }
                   1888:         if (!&error($response) && $response ne 'refused') {
                   1889:             if ($response eq 'unavailable') {
                   1890:                 $outcome = $response;
                   1891:             } else {
                   1892:                 $outcome = 'ok';
                   1893:                 my @matches = split(/\n/,$response);
                   1894:                 foreach my $match (@matches) {
                   1895:                     my ($key,$value) = split(/=/,$match);
                   1896:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1897:                 }
                   1898:             }
                   1899:         }
                   1900:     }
                   1901:     my %userinfo;
                   1902:     if (ref($results{$uname}) eq 'HASH') {
                   1903:         %userinfo = %{$results{$uname}};
                   1904:     } 
                   1905:     return ($outcome,%userinfo);
                   1906: }
                   1907: 
                   1908: sub inst_rulecheck {
1.923     raeburn  1909:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1910:     my %returnhash;
                   1911:     if ($udom ne '') {
                   1912:         if (ref($rules) eq 'ARRAY') {
                   1913:             @{$rules} = map {&escape($_);} (@{$rules});
                   1914:             my $rulestr = join(':',@{$rules});
                   1915:             my $homeserver=&domain($udom,'primary');
                   1916:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1917:                 my $response;
                   1918:                 if ($item eq 'username') {                
                   1919:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1920:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1921:                                               $homeserver));
1.923     raeburn  1922:                 } elsif ($item eq 'id') {
                   1923:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1924:                                               ':'.&escape($id).':'.$rulestr,
                   1925:                                               $homeserver));
1.945     raeburn  1926:                 } elsif ($item eq 'selfcreate') {
                   1927:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1928:                                                &escape($udom).':'.&escape($uname).
                   1929:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1930:                 }
1.912     raeburn  1931:                 if ($response ne 'refused') {
                   1932:                     my @pairs=split(/\&/,$response);
                   1933:                     foreach my $item (@pairs) {
                   1934:                         my ($key,$value)=split(/=/,$item,2);
                   1935:                         $key = &unescape($key);
                   1936:                         next if ($key =~ /^error: 2 /);
                   1937:                         $returnhash{$key}=&thaw_unescape($value);
                   1938:                     }
                   1939:                 }
                   1940:             }
                   1941:         }
                   1942:     }
                   1943:     return %returnhash;
                   1944: }
                   1945: 
                   1946: sub inst_userrules {
1.923     raeburn  1947:     my ($udom,$check) = @_;
1.912     raeburn  1948:     my (%ruleshash,@ruleorder);
                   1949:     if ($udom ne '') {
                   1950:         my $homeserver=&domain($udom,'primary');
                   1951:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1952:             my $response;
                   1953:             if ($check eq 'id') {
                   1954:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1955:                                  $homeserver);
1.943     raeburn  1956:             } elsif ($check eq 'email') {
                   1957:                 $response=&reply('instemailrules:'.&escape($udom),
                   1958:                                  $homeserver);
1.923     raeburn  1959:             } else {
                   1960:                 $response=&reply('instuserrules:'.&escape($udom),
                   1961:                                  $homeserver);
                   1962:             }
1.912     raeburn  1963:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1964:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1965:                 ($response ne 'no_such_host')) {
                   1966:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1967:                 my @pairs=split(/\&/,$hashitems);
                   1968:                 foreach my $item (@pairs) {
                   1969:                     my ($key,$value)=split(/=/,$item,2);
                   1970:                     $key = &unescape($key);
                   1971:                     next if ($key =~ /^error: 2 /);
                   1972:                     $ruleshash{$key}=&thaw_unescape($value);
                   1973:                 }
                   1974:                 my @esc_order = split(/\&/,$orderitems);
                   1975:                 foreach my $item (@esc_order) {
                   1976:                     push(@ruleorder,&unescape($item));
                   1977:                 }
                   1978:             }
                   1979:         }
                   1980:     }
                   1981:     return (\%ruleshash,\@ruleorder);
                   1982: }
                   1983: 
1.976     raeburn  1984: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1985: 
                   1986: sub get_domain_defaults {
1.1172.2.35! raeburn  1987:     my ($domain,$ignore_cache) = @_;
        !          1988:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  1989:     my $cachetime = 60*60*24;
1.1172.2.35! raeburn  1990:     unless ($ignore_cache) {
        !          1991:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
        !          1992:         if (defined($cached)) {
        !          1993:             if (ref($result) eq 'HASH') {
        !          1994:                 return %{$result};
        !          1995:             }
1.943     raeburn  1996:         }
                   1997:     }
                   1998:     my %domdefaults;
                   1999:     my %domconfig =
1.989     raeburn  2000:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2001:                                   'requestcourses','inststatus',
1.1172.2.9  raeburn  2002:                                   'coursedefaults','usersessions',
                   2003:                                   'requestauthor'],$domain);
1.943     raeburn  2004:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2005:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2006:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2007:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2008:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2009:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2010:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943     raeburn  2011:     } else {
                   2012:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2013:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2014:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2015:     }
1.976     raeburn  2016:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2017:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2018:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2019:         } else {
                   2020:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29  raeburn  2021:         }
1.1172.2.6  raeburn  2022:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2023:         foreach my $item (@usertools) {
                   2024:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2025:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2026:             }
                   2027:         }
1.1172.2.29  raeburn  2028:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2029:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2030:         }
1.976     raeburn  2031:     }
1.985     raeburn  2032:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006    raeburn  2033:         foreach my $item ('official','unofficial','community') {
1.985     raeburn  2034:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2035:         }
                   2036:     }
1.1172.2.9  raeburn  2037:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2038:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2039:     }
1.989     raeburn  2040:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   2041:         foreach my $item ('inststatustypes','inststatusorder') {
                   2042:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2043:         }
                   2044:     }
1.1047    raeburn  2045:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.19  raeburn  2046:         if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2047:             $domdefaults{'officialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'official'};
                   2048:             $domdefaults{'unofficialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'unofficial'};
1.1047    raeburn  2049:         }
1.1172.2.30  raeburn  2050:         if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2051:             $domdefaults{'officialquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'official'};
                   2052:             $domdefaults{'unofficialquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'unofficial'};
                   2053:             $domdefaults{'communityquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'community'};
                   2054:         }
1.1047    raeburn  2055:     }
1.1073    raeburn  2056:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2057:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2058:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2059:         }
                   2060:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2061:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2062:         }
                   2063:     }
1.1172.2.23  raeburn  2064:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2065:     return %domdefaults;
                   2066: }
                   2067: 
1.344     www      2068: # --------------------------------------------------- Assign a key to a student
                   2069: 
                   2070: sub assign_access_key {
1.364     www      2071: #
                   2072: # a valid key looks like uname:udom#comments
                   2073: # comments are being appended
                   2074: #
1.498     www      2075:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2076:     $kdom=
1.620     albertel 2077:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2078:     $knum=
1.620     albertel 2079:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2080:     $cdom=
1.620     albertel 2081:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2082:     $cnum=
1.620     albertel 2083:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2084:     $udom=$env{'user.name'} unless (defined($udom));
                   2085:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2086:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2087:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2088:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2089:                                                   # assigned to this person
                   2090:                                                   # - this should not happen,
1.345     www      2091:                                                   # unless something went wrong
                   2092:                                                   # the first time around
                   2093: # ready to assign
1.364     www      2094:         $logentry=$1.'; '.$logentry;
1.496     www      2095:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2096:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2097: # key now belongs to user
1.346     www      2098: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2099:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2100:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2101:                 return 'ok';
                   2102:             } else {
                   2103:                 return 
                   2104:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2105: 	    }
                   2106:         } else {
                   2107:             return 'error: Could not assign key, try again later.';
                   2108:         }
1.364     www      2109:     } elsif (!$existing{$ckey}) {
1.345     www      2110: # the key does not exist
                   2111: 	return 'error: The key does not exist';
                   2112:     } else {
                   2113: # the key is somebody else's
                   2114: 	return 'error: The key is already in use';
                   2115:     }
1.344     www      2116: }
                   2117: 
1.364     www      2118: # ------------------------------------------ put an additional comment on a key
                   2119: 
                   2120: sub comment_access_key {
                   2121: #
                   2122: # a valid key looks like uname:udom#comments
                   2123: # comments are being appended
                   2124: #
                   2125:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2126:     $cdom=
1.620     albertel 2127:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2128:     $cnum=
1.620     albertel 2129:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2130:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2131:     if ($existing{$ckey}) {
                   2132:         $existing{$ckey}.='; '.$logentry;
                   2133: # ready to assign
1.367     www      2134:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2135:                                                  $cdom,$cnum) eq 'ok') {
                   2136: 	    return 'ok';
                   2137:         } else {
                   2138: 	    return 'error: Count not store comment.';
                   2139:         }
                   2140:     } else {
                   2141: # the key does not exist
                   2142: 	return 'error: The key does not exist';
                   2143:     }
                   2144: }
                   2145: 
1.344     www      2146: # ------------------------------------------------------ Generate a set of keys
                   2147: 
                   2148: sub generate_access_keys {
1.364     www      2149:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2150:     $cdom=
1.620     albertel 2151:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2152:     $cnum=
1.620     albertel 2153:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2154:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2155:     unless (($cdom) && ($cnum)) { return 0; }
                   2156:     if ($number>10000) { return 0; }
                   2157:     sleep(2); # make sure don't get same seed twice
                   2158:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2159:     my $total=0;
                   2160:     for (my $i=1;$i<=$number;$i++) {
                   2161:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2162:                   sprintf("%lx",int(100000*rand)).'-'.
                   2163:                   sprintf("%lx",int(100000*rand));
                   2164:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2165:        $newkey=~s/0/h/g; # and also 0 and O
                   2166:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2167:        if ($existing{$newkey}) {
                   2168:            $i--;
                   2169:        } else {
1.364     www      2170: 	  if (&put('accesskeys',
                   2171:               { $newkey => '# generated '.localtime().
1.620     albertel 2172:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2173:                            '; '.$logentry },
                   2174: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2175:               $total++;
                   2176: 	  }
                   2177:        }
                   2178:     }
1.620     albertel 2179:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2180:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2181:     return $total;
                   2182: }
                   2183: 
                   2184: # ------------------------------------------------------- Validate an accesskey
                   2185: 
                   2186: sub validate_access_key {
                   2187:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2188:     $cdom=
1.620     albertel 2189:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2190:     $cnum=
1.620     albertel 2191:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2192:     $udom=$env{'user.domain'} unless (defined($udom));
                   2193:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2194:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2195:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2196: }
                   2197: 
                   2198: # ------------------------------------- Find the section of student in a course
1.652     albertel 2199: sub devalidate_getsection_cache {
                   2200:     my ($udom,$unam,$courseid)=@_;
                   2201:     my $hashid="$udom:$unam:$courseid";
                   2202:     &devalidate_cache_new('getsection',$hashid);
                   2203: }
1.298     matthew  2204: 
1.815     albertel 2205: sub courseid_to_courseurl {
                   2206:     my ($courseid) = @_;
                   2207:     #already url style courseid
                   2208:     return $courseid if ($courseid =~ m{^/});
                   2209: 
                   2210:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2211: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2212: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2213: 	return "/$cdom/$cnum";
                   2214:     }
                   2215: 
                   2216:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2217:     if (exists($courseinfo{'num'})) {
                   2218: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2219:     }
                   2220: 
                   2221:     return undef;
                   2222: }
                   2223: 
1.298     matthew  2224: sub getsection {
                   2225:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2226:     my $cachetime=1800;
1.551     albertel 2227: 
                   2228:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2229:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2230:     if (defined($cached)) { return $result; }
                   2231: 
1.298     matthew  2232:     my %Pending; 
                   2233:     my %Expired;
                   2234:     #
                   2235:     # Each role can either have not started yet (pending), be active, 
                   2236:     #    or have expired.
                   2237:     #
                   2238:     # If there is an active role, we are done.
                   2239:     #
                   2240:     # If there is more than one role which has not started yet, 
                   2241:     #     choose the one which will start sooner
                   2242:     # If there is one role which has not started yet, return it.
                   2243:     #
                   2244:     # If there is more than one expired role, choose the one which ended last.
                   2245:     # If there is a role which has expired, return it.
                   2246:     #
1.815     albertel 2247:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2248:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2249:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2250:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2251:         my $section=$1;
                   2252:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2253:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2254:         my $now=time;
1.548     albertel 2255:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2256:             $Expired{$end}=$section;
                   2257:             next;
                   2258:         }
1.548     albertel 2259:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2260:             $Pending{$start}=$section;
                   2261:             next;
                   2262:         }
1.599     albertel 2263:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2264:     }
                   2265:     #
                   2266:     # Presumedly there will be few matching roles from the above
                   2267:     # loop and the sorting time will be negligible.
                   2268:     if (scalar(keys(%Pending))) {
                   2269:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2270:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2271:     } 
                   2272:     if (scalar(keys(%Expired))) {
                   2273:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2274:         my $time = pop(@sorted);
1.599     albertel 2275:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2276:     }
1.599     albertel 2277:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2278: }
1.70      www      2279: 
1.599     albertel 2280: sub save_cache {
                   2281:     &purge_remembered();
1.722     albertel 2282:     #&Apache::loncommon::validate_page();
1.620     albertel 2283:     undef(%env);
1.780     albertel 2284:     undef($env_loaded);
1.599     albertel 2285: }
1.452     albertel 2286: 
1.599     albertel 2287: my $to_remember=-1;
                   2288: my %remembered;
                   2289: my %accessed;
                   2290: my $kicks=0;
                   2291: my $hits=0;
1.849     albertel 2292: sub make_key {
                   2293:     my ($name,$id) = @_;
1.872     albertel 2294:     if (length($id) > 65 
                   2295: 	&& length(&escape($id)) > 200) {
                   2296: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2297:     }
1.849     albertel 2298:     return &escape($name.':'.$id);
                   2299: }
                   2300: 
1.599     albertel 2301: sub devalidate_cache_new {
                   2302:     my ($name,$id,$debug) = @_;
                   2303:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 2304:     $id=&make_key($name,$id);
1.599     albertel 2305:     $memcache->delete($id);
                   2306:     delete($remembered{$id});
                   2307:     delete($accessed{$id});
                   2308: }
                   2309: 
                   2310: sub is_cached_new {
                   2311:     my ($name,$id,$debug) = @_;
1.849     albertel 2312:     $id=&make_key($name,$id);
1.599     albertel 2313:     if (exists($remembered{$id})) {
1.1133    foxr     2314: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599     albertel 2315: 	$accessed{$id}=[&gettimeofday()];
                   2316: 	$hits++;
                   2317: 	return ($remembered{$id},1);
                   2318:     }
                   2319:     my $value = $memcache->get($id);
                   2320:     if (!(defined($value))) {
                   2321: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2322: 	return (undef,undef);
1.416     albertel 2323:     }
1.599     albertel 2324:     if ($value eq '__undef__') {
                   2325: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2326: 	$value=undef;
                   2327:     }
                   2328:     &make_room($id,$value,$debug);
                   2329:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2330:     return ($value,1);
                   2331: }
                   2332: 
                   2333: sub do_cache_new {
                   2334:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 2335:     $id=&make_key($name,$id);
1.599     albertel 2336:     my $setvalue=$value;
                   2337:     if (!defined($setvalue)) {
                   2338: 	$setvalue='__undef__';
                   2339:     }
1.623     albertel 2340:     if (!defined($time) ) {
                   2341: 	$time=600;
                   2342:     }
1.599     albertel 2343:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2344:     my $result = $memcache->set($id,$setvalue,$time);
                   2345:     if (! $result) {
1.872     albertel 2346: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2347: 	$memcache->disconnect_all();
1.872     albertel 2348:     }
1.600     albertel 2349:     # need to make a copy of $value
1.919     albertel 2350:     &make_room($id,$value,$debug);
1.599     albertel 2351:     return $value;
                   2352: }
                   2353: 
                   2354: sub make_room {
                   2355:     my ($id,$value,$debug)=@_;
1.919     albertel 2356: 
                   2357:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   2358:                                     : $value;
1.599     albertel 2359:     if ($to_remember<0) { return; }
                   2360:     $accessed{$id}=[&gettimeofday()];
                   2361:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2362:     my $to_kick;
                   2363:     my $max_time=0;
                   2364:     foreach my $other (keys(%accessed)) {
                   2365: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2366: 	    $to_kick=$other;
                   2367: 	    $max_time=&tv_interval($accessed{$other});
                   2368: 	}
                   2369:     }
                   2370:     delete($remembered{$to_kick});
                   2371:     delete($accessed{$to_kick});
                   2372:     $kicks++;
                   2373:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2374:     return;
                   2375: }
                   2376: 
1.599     albertel 2377: sub purge_remembered {
1.604     albertel 2378:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2379:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2380:     undef(%remembered);
                   2381:     undef(%accessed);
1.428     albertel 2382: }
1.70      www      2383: # ------------------------------------- Read an entry from a user's environment
                   2384: 
                   2385: sub userenvironment {
                   2386:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2387:     my $items;
                   2388:     foreach my $item (@what) {
                   2389:         $items.=&escape($item).'&';
                   2390:     }
                   2391:     $items=~s/\&$//;
1.70      www      2392:     my %returnhash=();
1.1009    raeburn  2393:     my $uhome = &homeserver($unam,$udom);
                   2394:     unless ($uhome eq 'no_host') {
                   2395:         my @answer=split(/\&/, 
                   2396:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2397:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2398:             return %returnhash;
                   2399:         }
1.1009    raeburn  2400:         my $i;
                   2401:         for ($i=0;$i<=$#what;$i++) {
                   2402: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2403:         }
1.70      www      2404:     }
                   2405:     return %returnhash;
1.1       albertel 2406: }
                   2407: 
1.617     albertel 2408: # ---------------------------------------------------------- Get a studentphoto
                   2409: sub studentphoto {
                   2410:     my ($udom,$unam,$ext) = @_;
                   2411:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2412:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2413:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2414:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2415:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2416:             } else {
                   2417:                 my ($result,$perm_reqd)=
1.707     albertel 2418: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2419:                 if ($result eq 'ok') {
                   2420:                     if (!($perm_reqd eq 'yes')) {
                   2421:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2422:                     }
                   2423:                 }
                   2424:             }
                   2425:         }
                   2426:     } else {
                   2427:         my ($result,$perm_reqd) = 
1.707     albertel 2428: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2429:         if ($result eq 'ok') {
                   2430:             if (!($perm_reqd eq 'yes')) {
                   2431:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2432:             }
                   2433:         }
                   2434:     }
                   2435:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2436: }
                   2437: 
                   2438: sub retrievestudentphoto {
                   2439:     my ($udom,$unam,$ext,$type) = @_;
                   2440:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2441:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2442:     if ($ret eq 'ok') {
                   2443:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2444:         if ($type eq 'thumbnail') {
                   2445:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2446:         }
                   2447:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2448:         return $tokenurl;
                   2449:     } else {
                   2450:         if ($type eq 'thumbnail') {
                   2451:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2452:         } else { 
                   2453:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2454:         }
1.617     albertel 2455:     }
                   2456: }
                   2457: 
1.263     www      2458: # -------------------------------------------------------------------- New chat
                   2459: 
                   2460: sub chatsend {
1.724     raeburn  2461:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2462:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2463:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2464:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2465:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2466: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2467: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2468: }
                   2469: 
                   2470: # ------------------------------------------ Find current version of a resource
                   2471: 
                   2472: sub getversion {
                   2473:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  2474:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2475:     return &currentversion(&filelocation('',$fname));
                   2476: }
                   2477: 
                   2478: sub currentversion {
                   2479:     my $fname=shift;
                   2480:     my $author=$fname;
                   2481:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2482:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2483:     my $home=&homeserver($uname,$udom);
1.292     www      2484:     if ($home eq 'no_host') { 
                   2485:         return -1; 
                   2486:     }
1.1112    www      2487:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2488:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2489: 	return -1;
                   2490:     }
1.1112    www      2491:     return $answer;
1.263     www      2492: }
                   2493: 
1.1111    www      2494: #
                   2495: # Return special version number of resource if set by override, empty otherwise
                   2496: #
                   2497: sub usedversion {
                   2498:     my $fname=shift;
                   2499:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2500:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2501:     if ($urlversion) { return $urlversion; }
                   2502:     return '';
                   2503: }
                   2504: 
1.1       albertel 2505: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2506: 
1.1       albertel 2507: sub subscribe {
                   2508:     my $fname=shift;
1.761     raeburn  2509:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2510:     $fname=~s/[\n\r]//g;
1.1       albertel 2511:     my $author=$fname;
                   2512:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2513:     my ($udom,$uname)=split(/\//,$author);
                   2514:     my $home=homeserver($uname,$udom);
1.335     albertel 2515:     if ($home eq 'no_host') {
                   2516:         return 'not_found';
1.1       albertel 2517:     }
                   2518:     my $answer=reply("sub:$fname",$home);
1.64      www      2519:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2520: 	$answer.=' by '.$home;
                   2521:     }
1.1       albertel 2522:     return $answer;
                   2523: }
                   2524:     
1.8       www      2525: # -------------------------------------------------------------- Replicate file
                   2526: 
                   2527: sub repcopy {
                   2528:     my $filename=shift;
1.23      www      2529:     $filename=~s/\/+/\//g;
1.1142    raeburn  2530:     my $londocroot = $perlvar{'lonDocRoot'};
                   2531:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2532:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2533:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2534: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2535: 	return &repcopy_userfile($filename);
                   2536:     }
1.532     albertel 2537:     $filename=~s/[\n\r]//g;
1.8       www      2538:     my $transname="$filename.in.transfer";
1.828     www      2539: # FIXME: this should flock
1.607     raeburn  2540:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2541:     my $remoteurl=subscribe($filename);
1.64      www      2542:     if ($remoteurl =~ /^con_lost by/) {
                   2543: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2544:            return 'unavailable';
1.8       www      2545:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2546: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2547: 	   return 'not_found';
1.64      www      2548:     } elsif ($remoteurl =~ /^rejected by/) {
                   2549: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2550:            return 'forbidden';
1.20      www      2551:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2552:            return 'ok';
1.8       www      2553:     } else {
1.290     www      2554:         my $author=$filename;
                   2555:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2556:         my ($udom,$uname)=split(/\//,$author);
                   2557:         my $home=homeserver($uname,$udom);
                   2558:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2559:            my @parts=split(/\//,$filename);
                   2560:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2561:            if ($path ne "$londocroot/res") {
1.8       www      2562:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2563: 	       return 'bad_request';
1.8       www      2564:            }
                   2565:            my $count;
                   2566:            for ($count=5;$count<$#parts;$count++) {
                   2567:                $path.="/$parts[$count]";
                   2568:                if ((-e $path)!=1) {
                   2569: 		   mkdir($path,0777);
                   2570:                }
                   2571:            }
                   2572:            my $ua=new LWP::UserAgent;
                   2573:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2574:            my $response=$ua->request($request,$transname);
                   2575:            if ($response->is_error()) {
                   2576: 	       unlink($transname);
                   2577:                my $message=$response->status_line;
1.672     albertel 2578:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2579:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2580:                return 'unavailable';
1.8       www      2581:            } else {
1.16      www      2582: 	       if ($remoteurl!~/\.meta$/) {
                   2583:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2584:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2585:                   if ($mresponse->is_error()) {
                   2586: 		      unlink($filename.'.meta');
                   2587:                       &logthis(
1.672     albertel 2588:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2589:                   }
                   2590: 	       }
1.8       www      2591:                rename($transname,$filename);
1.607     raeburn  2592:                return 'ok';
1.8       www      2593:            }
1.290     www      2594:        }
1.8       www      2595:     }
1.330     www      2596: }
                   2597: 
                   2598: # ------------------------------------------------ Get server side include body
                   2599: sub ssi_body {
1.381     albertel 2600:     my ($filelink,%form)=@_;
1.606     matthew  2601:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2602:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2603:     }
1.953     www      2604:     my $output='';
                   2605:     my $response;
1.980     raeburn  2606:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2607:        ($output,$response)=&externalssi($filelink);
1.953     www      2608:     } else {
1.1004    droeschl 2609:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2610:        $filelink .= 'inhibitmenu=yes';
1.953     www      2611:        ($output,$response)=&ssi($filelink,%form);
                   2612:     }
1.778     albertel 2613:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2614:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2615:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2616:     if (wantarray) {
                   2617:         return ($output, $response);
                   2618:     } else {
                   2619:         return $output;
                   2620:     }
1.8       www      2621: }
                   2622: 
1.15      www      2623: # --------------------------------------------------------- Server Side Include
                   2624: 
1.782     albertel 2625: sub absolute_url {
                   2626:     my ($host_name) = @_;
                   2627:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2628:     if ($host_name eq '') {
                   2629: 	$host_name = $ENV{'SERVER_NAME'};
                   2630:     }
                   2631:     return $protocol.$host_name;
                   2632: }
                   2633: 
1.942     foxr     2634: #
                   2635: #   Server side include.
                   2636: # Parameters:
                   2637: #  fn     Possibly encrypted resource name/id.
                   2638: #  form   Hash that describes how the rendering should be done
                   2639: #         and other things.
1.944     foxr     2640: # Returns:
1.950     raeburn  2641: #   Scalar context: The content of the response.
                   2642: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2643: #     
1.15      www      2644: sub ssi {
                   2645: 
1.944     foxr     2646:     my ($fn,%form)=@_;
1.15      www      2647:     my $ua=new LWP::UserAgent;
1.23      www      2648:     my $request;
1.711     albertel 2649: 
                   2650:     $form{'no_update_last_known'}=1;
1.895     albertel 2651:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2652:     if (%form) {
1.782     albertel 2653:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2654:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2655:     } else {
1.782     albertel 2656:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2657:     }
                   2658: 
1.15      www      2659:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.2  raeburn  2660:     my $response= $ua->request($request);
1.944     foxr     2661:     if (wantarray) {
1.1172.2.3  raeburn  2662: 	return ($response->content, $response);
1.944     foxr     2663:     } else {
1.1172.2.3  raeburn  2664: 	return $response->content;
1.942     foxr     2665:     }
1.324     www      2666: }
                   2667: 
                   2668: sub externalssi {
                   2669:     my ($url)=@_;
                   2670:     my $ua=new LWP::UserAgent;
                   2671:     my $request=new HTTP::Request('GET',$url);
                   2672:     my $response=$ua->request($request);
1.954     raeburn  2673:     if (wantarray) {
                   2674:         return ($response->content, $response);
                   2675:     } else {
                   2676:         return $response->content;
                   2677:     }
1.15      www      2678: }
1.254     www      2679: 
1.492     albertel 2680: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2681: 
                   2682: sub allowuploaded {
                   2683:     my ($srcurl,$url)=@_;
                   2684:     $url=&clutter(&declutter($url));
                   2685:     my $dir=$url;
                   2686:     $dir=~s/\/[^\/]+$//;
                   2687:     my %httpref=();
                   2688:     my $httpurl=&hreflocation('',$url);
                   2689:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2690:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2691: }
1.477     raeburn  2692: 
1.1172.2.13  raeburn  2693: #
                   2694: # Determine if the current user should be able to edit a particular resource,
                   2695: # when viewing in course context.
                   2696: # (a) When viewing resource used to determine if "Edit" item is included in
                   2697: #     Functions.
                   2698: # (b) When displaying folder contents in course editor, used to determine if
                   2699: #     "Edit" link will be displayed alongside resource.
                   2700: #
                   2701: #  input: six args -- filename (decluttered), course number, course domain,
                   2702: #                   url, symb (if registered) and group (if this is a group
                   2703: #                   item -- e.g., bulletin board, group page etc.).
                   2704: #  output: array of five scalars --
                   2705: #          $cfile -- url for file editing if editable on current server
                   2706: #          $home -- homeserver of resource (i.e., for author if published,
                   2707: #                                           or course if uploaded.).
                   2708: #          $switchserver --  1 if server switch will be needed.
                   2709: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   2710: #          $forceview -- 1 if icon/link should be to go to view mode
                   2711: #
                   2712: 
                   2713: sub can_edit_resource {
                   2714:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   2715:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   2716: #
                   2717: # For aboutme pages user can only edit his/her own.
                   2718: #
                   2719:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   2720:         my ($sdom,$sname) = ($1,$2);
                   2721:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   2722:             $home = $env{'user.home'};
                   2723:             $cfile = $resurl;
                   2724:             if ($env{'form.forceedit'}) {
                   2725:                 $forceview = 1;
                   2726:             } else {
                   2727:                 $forceedit = 1;
                   2728:             }
                   2729:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   2730:         } else {
                   2731:             return;
                   2732:         }
                   2733:     }
                   2734: 
                   2735:     if ($env{'request.course.id'}) {
                   2736:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   2737:         if ($group ne '') {
                   2738: # if this is a group homepage or group bulletin board, check group privs
                   2739:             my $allowed = 0;
                   2740:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   2741:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   2742:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   2743:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   2744:                     $allowed = 1;
                   2745:                 }
                   2746:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   2747:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   2748:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   2749:                     $allowed = 1;
                   2750:                 }
                   2751:             }
                   2752:             if ($allowed) {
                   2753:                 $home=&homeserver($cnum,$cdom);
                   2754:                 if ($env{'form.forceedit'}) {
                   2755:                     $forceview = 1;
                   2756:                 } else {
                   2757:                     $forceedit = 1;
                   2758:                 }
                   2759:                 $cfile = $resurl;
                   2760:             } else {
                   2761:                 return;
                   2762:             }
                   2763:         } else {
1.1172.2.15  raeburn  2764:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2765:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   2766:                     return;
                   2767:                 }
                   2768:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  2769: #
                   2770: # No edit allowed where CC has switched to student role.
                   2771: #
                   2772:                 return;
                   2773:             }
                   2774:         }
                   2775:     }
                   2776: 
                   2777:     if ($file ne '') {
                   2778:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   2779:             if (&is_course_upload($file,$cnum,$cdom)) {
                   2780:                 $uploaded = 1;
                   2781:                 $incourse = 1;
                   2782:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   2783:                     $cfile = &hreflocation('',$file);
                   2784:                     if ($env{'form.forceedit'}) {
                   2785:                         $forceview = 1;
                   2786:                     } else {
                   2787:                         $forceedit = 1;
                   2788:                     }
                   2789:                 }
                   2790:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   2791:                 $incourse = 1;
                   2792:                 if ($env{'form.forceedit'}) {
                   2793:                     $forceview = 1;
                   2794:                 } else {
                   2795:                     $forceedit = 1;
                   2796:                 }
                   2797:                 $cfile = $resurl;
                   2798:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   2799:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   2800:                     $incourse = 1;
                   2801:                     if ($env{'form.forceedit'}) {
                   2802:                         $forceview = 1;
                   2803:                     } else {
                   2804:                         $forceedit = 1;
                   2805:                     }
                   2806:                     $cfile = $resurl;
                   2807:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   2808:                     $incourse = 1;
                   2809:                     $cfile = $resurl.'/smpedit';
                   2810:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   2811:                     $incourse = 1;
                   2812:                     if ($env{'form.forceedit'}) {
                   2813:                         $forceview = 1;
                   2814:                     } else {
                   2815:                         $forceedit = 1;
                   2816:                     }
                   2817:                     $cfile = $resurl;
1.1172.2.15  raeburn  2818:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2819:                     $incourse = 1;
                   2820:                     if ($env{'form.forceedit'}) {
                   2821:                         $forceview = 1;
                   2822:                     } else {
                   2823:                         $forceedit = 1;
                   2824:                     }
                   2825:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  2826:                 }
                   2827:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   2828:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   2829:                 if (&is_on_map($template)) {
                   2830:                     $incourse = 1;
                   2831:                     $forceview = 1;
                   2832:                     $cfile = $template;
                   2833:                 }
                   2834:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   2835:                     $incourse = 1;
                   2836:                     if ($env{'form.forceedit'}) {
                   2837:                         $forceview = 1;
                   2838:                     } else {
                   2839:                         $forceedit = 1;
                   2840:                     }
                   2841:                     $cfile = $resurl;
                   2842:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   2843:                 $incourse = 1;
                   2844:                 $forceview = 1;
                   2845:                 if ($symb) {
                   2846:                     my ($map,$id,$res)=&decode_symb($symb);
                   2847:                     $env{'request.symb'} = $symb;
                   2848:                     $cfile = &clutter($res);
                   2849:                 } else {
                   2850:                     $cfile = $env{'form.suppurl'};
                   2851:                     $cfile =~ s{^http://}{};
                   2852:                     $cfile = '/adm/wrapper/ext/'.$cfile;
                   2853:                 }
1.1172.2.31  raeburn  2854:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2855:                 if ($env{'form.forceedit'}) {
                   2856:                     $forceview = 1;
                   2857:                 } else {
                   2858:                     $forceedit = 1;
                   2859:                 }
                   2860:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  2861:             }
                   2862:         }
                   2863:         if ($uploaded || $incourse) {
                   2864:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  2865:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  2866:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   2867:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   2868:             # Check that the user has permission to edit this resource
                   2869:             my $setpriv = 1;
                   2870:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   2871:             if (defined($cfudom)) {
                   2872:                 $home=&homeserver($cfuname,$cfudom);
                   2873:                 $cfile=$file;
                   2874:             }
                   2875:         }
                   2876:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   2877:             (($home ne '') && ($home ne 'no_host'))) {
                   2878:             my @ids=&current_machine_ids();
                   2879:             unless (grep(/^\Q$home\E$/,@ids)) {
                   2880:                 $switchserver=1;
                   2881:             }
                   2882:         }
                   2883:     }
                   2884:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   2885: }
                   2886: 
                   2887: sub is_course_upload {
                   2888:     my ($file,$cnum,$cdom) = @_;
                   2889:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   2890:     $uploadpath =~ s{^\/}{};
                   2891:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   2892:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   2893:         return 1;
                   2894:     }
                   2895:     return;
                   2896: }
                   2897: 
                   2898: sub in_course {
                   2899:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   2900:     if ($hideprivileged) {
                   2901:         my $skipuser;
1.1172.2.23  raeburn  2902:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   2903:         my @possdoms = ($cdom);
                   2904:         if ($coursehash{'checkforpriv'}) {
                   2905:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   2906:         }
                   2907:         if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13  raeburn  2908:             $skipuser = 1;
                   2909:             if ($coursehash{'nothideprivileged'}) {
                   2910:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2911:                     my $user;
                   2912:                     if ($item =~ /:/) {
                   2913:                         $user = $item;
                   2914:                     } else {
                   2915:                         $user = join(':',split(/[\@]/,$item));
                   2916:                     }
                   2917:                     if ($user eq $uname.':'.$udom) {
                   2918:                         undef($skipuser);
                   2919:                         last;
                   2920:                     }
                   2921:                 }
                   2922:             }
                   2923:             if ($skipuser) {
                   2924:                 return 0;
                   2925:             }
                   2926:         }
                   2927:     }
                   2928:     $type ||= 'any';
                   2929:     if (!defined($cdom) || !defined($cnum)) {
                   2930:         my $cid  = $env{'request.course.id'};
                   2931:         $cdom = $env{'course.'.$cid.'.domain'};
                   2932:         $cnum = $env{'course.'.$cid.'.num'};
                   2933:     }
                   2934:     my $typesref;
                   2935:     if (($type eq 'any') || ($type eq 'all')) {
                   2936:         $typesref = ['active','previous','future'];
                   2937:     } elsif ($type eq 'previous' || $type eq 'future') {
                   2938:         $typesref = [$type];
                   2939:     }
                   2940:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   2941:                               $typesref,undef,[$cdom]);
                   2942:     my ($tmp) = keys(%roles);
                   2943:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   2944:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   2945:     if (@course_roles > 0) {
                   2946:         return 1;
                   2947:     }
                   2948:     return 0;
                   2949: }
                   2950: 
1.478     albertel 2951: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2952: # input: action, courseID, current domain, intended
1.637     raeburn  2953: #        path to file, source of file, instruction to parse file for objects,
                   2954: #        ref to hash for embedded objects,
                   2955: #        ref to hash for codebase of java objects.
1.1095    raeburn  2956: #        reference to scalar to accommodate mime type determined
                   2957: #          from File::MMagic if $parser = parse.
1.637     raeburn  2958: #
1.485     raeburn  2959: # output: url to file (if action was uploaddoc), 
                   2960: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2961: #
1.478     albertel 2962: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2963: # course.
1.477     raeburn  2964: #
1.478     albertel 2965: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2966: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2967: #          course's home server.
1.477     raeburn  2968: #
1.478     albertel 2969: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2970: #          be copied from $source (current location) to 
                   2971: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2972: #         and will then be copied to
                   2973: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2974: #         course's home server.
1.485     raeburn  2975: #
1.481     raeburn  2976: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2977: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2978: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2979: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2980: #         in course's home server.
1.637     raeburn  2981: #
1.477     raeburn  2982: 
                   2983: sub process_coursefile {
1.1095    raeburn  2984:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   2985:         $mimetype)=@_;
1.477     raeburn  2986:     my $fetchresult;
1.638     albertel 2987:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2988:     if ($action eq 'propagate') {
1.638     albertel 2989:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2990: 			     $home);
1.481     raeburn  2991:     } else {
1.477     raeburn  2992:         my $fpath = '';
                   2993:         my $fname = $file;
1.478     albertel 2994:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2995:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2996:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2997:         if ($action eq 'copy') {
                   2998:             if ($source eq '') {
                   2999:                 $fetchresult = 'no source file';
                   3000:                 return $fetchresult;
                   3001:             } else {
                   3002:                 my $destination = $filepath.'/'.$fname;
                   3003:                 rename($source,$destination);
                   3004:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3005:                                  $home);
1.481     raeburn  3006:             }
                   3007:         } elsif ($action eq 'uploaddoc') {
                   3008:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 3009:             print $fh $env{'form.'.$source};
1.481     raeburn  3010:             close($fh);
1.637     raeburn  3011:             if ($parser eq 'parse') {
1.1024    raeburn  3012:                 my $mm = new File::MMagic;
1.1095    raeburn  3013:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3014:                 if ($type eq 'text/html') {
1.1024    raeburn  3015:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3016:                     unless ($parse_result eq 'ok') {
                   3017:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3018:                     }
1.637     raeburn  3019:                 }
1.1095    raeburn  3020:                 if (ref($mimetype)) {
                   3021:                     $$mimetype = $type;
                   3022:                 } 
1.637     raeburn  3023:             }
1.477     raeburn  3024:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3025:                                  $home);
1.481     raeburn  3026:             if ($fetchresult eq 'ok') {
                   3027:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3028:             } else {
                   3029:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3030:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3031:                 return '/adm/notfound.html';
                   3032:             }
1.477     raeburn  3033:         }
                   3034:     }
1.485     raeburn  3035:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3036:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3037:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3038:     }
                   3039:     return $fetchresult;
                   3040: }
                   3041: 
1.637     raeburn  3042: sub build_filepath {
                   3043:     my ($fpath) = @_;
                   3044:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3045:     unless ($fpath eq '') {
                   3046:         my @parts=split('/',$fpath);
                   3047:         foreach my $part (@parts) {
                   3048:             $filepath.= '/'.$part;
                   3049:             if ((-e $filepath)!=1) {
                   3050:                 mkdir($filepath,0777);
                   3051:             }
                   3052:         }
                   3053:     }
                   3054:     return $filepath;
                   3055: }
                   3056: 
                   3057: sub store_edited_file {
1.638     albertel 3058:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3059:     my $file = $primary_url;
                   3060:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3061:     my $fpath = '';
                   3062:     my $fname = $file;
                   3063:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3064:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3065:     my $filepath = &build_filepath($fpath);
                   3066:     open(my $fh,'>'.$filepath.'/'.$fname);
                   3067:     print $fh $content;
                   3068:     close($fh);
1.638     albertel 3069:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3070:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3071: 			  $home);
1.637     raeburn  3072:     if ($$fetchresult eq 'ok') {
                   3073:         return '/uploaded/'.$fpath.'/'.$fname;
                   3074:     } else {
1.638     albertel 3075:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3076: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3077:         return '/adm/notfound.html';
                   3078:     }
                   3079: }
                   3080: 
1.531     albertel 3081: sub clean_filename {
1.831     albertel 3082:     my ($fname,$args)=@_;
1.315     www      3083: # Replace Windows backslashes by forward slashes
1.257     www      3084:     $fname=~s/\\/\//g;
1.831     albertel 3085:     if (!$args->{'keep_path'}) {
                   3086:         # Get rid of everything but the actual filename
                   3087: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3088:     }
1.315     www      3089: # Replace spaces by underscores
                   3090:     $fname=~s/\s+/\_/g;
                   3091: # Replace all other weird characters by nothing
1.831     albertel 3092:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3093: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3094: # numbers
                   3095:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3096:     return $fname;
                   3097: }
1.1051    raeburn  3098: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3099: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3100: # image with the same aspect ratio as the original, but with dimensions which do 
                   3101: # not exceed $resizewidth and $resizeheight.
                   3102:  
1.984     neumanie 3103: sub resizeImage {
1.1051    raeburn  3104:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3105:     my $ima = Image::Magick->new;
                   3106:     my $resized;
                   3107:     if (-e $img_path) {
                   3108:         $ima->Read($img_path);
                   3109:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3110:             my $width = $ima->Get('width');
                   3111:             my $height = $ima->Get('height');
                   3112:             if ($width > $resizewidth) {
                   3113: 	        my $factor = $width/$resizewidth;
                   3114:                 my $newheight = $height/$factor;
                   3115:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3116:                 $resized = 1;
                   3117:             }
                   3118:         }
                   3119:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3120:             my $width = $ima->Get('width');
                   3121:             my $height = $ima->Get('height');
                   3122:             if ($height > $resizeheight) {
                   3123:                 my $factor = $height/$resizeheight;
                   3124:                 my $newwidth = $width/$factor;
                   3125:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3126:                 $resized = 1;
                   3127:             }
                   3128:         }
                   3129:         if ($resized) {
                   3130:             $ima->Write($img_path);
                   3131:         }
                   3132:     }
                   3133:     return;
1.977     amueller 3134: }
                   3135: 
1.608     albertel 3136: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3137: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3138: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3139: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3140: #                                    canceloverwrite, or ''. 
                   3141: #                   if 'coursedoc': upload to the current course
                   3142: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3143: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3144: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3145: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3146: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3147: #        $allfiles - reference to hash for embedded objects
                   3148: #        $codebase - reference to hash for codebase of java objects
                   3149: #        $desuname - username for permanent storage of uploaded file
                   3150: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3151: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3152: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3153: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3154: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3155: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3156: #                    from File::MMagic.
1.858     raeburn  3157: # 
1.686     albertel 3158: # output: url of file in userspace, or error: <message> 
                   3159: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3160: 
1.531     albertel 3161: sub userfileupload {
1.1090    raeburn  3162:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3163:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3164:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3165:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3166:     $fname=&clean_filename($fname);
1.1090    raeburn  3167:     # See if there is anything left
1.257     www      3168:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3169:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3170:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3171:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3172:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3173:         my $now = time;
1.1090    raeburn  3174:         my $filepath;
1.1095    raeburn  3175:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3176:              $filepath = 'tmp/helprequests/'.$now;
                   3177:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3178:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3179:                          '_'.$env{'user.domain'}.'/pending';
                   3180:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3181:             my ($docuname,$docudom);
                   3182:             if ($destudom) {
                   3183:                 $docudom = $destudom;
                   3184:             } else {
                   3185:                 $docudom = $env{'user.domain'};
                   3186:             }
                   3187:             if ($destuname) {
                   3188:                 $docuname = $destuname;
                   3189:             } else {
                   3190:                 $docuname = $env{'user.name'};
                   3191:             }
                   3192:             if (exists($env{'form.group'})) {
                   3193:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3194:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3195:             }
                   3196:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3197:             if ($context eq 'canceloverwrite') {
                   3198:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3199:                 if (-e  $tempfile) {
                   3200:                     my @info = stat($tempfile);
                   3201:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3202:                         unlink($tempfile);
                   3203:                     }
                   3204:                 }
                   3205:                 return;
1.523     raeburn  3206:             }
                   3207:         }
1.1090    raeburn  3208:         # Create the directory if not present
1.741     raeburn  3209:         my @parts=split(/\//,$filepath);
                   3210:         my $fullpath = $perlvar{'lonDaemons'};
                   3211:         for (my $i=0;$i<@parts;$i++) {
                   3212:             $fullpath .= '/'.$parts[$i];
                   3213:             if ((-e $fullpath)!=1) {
                   3214:                 mkdir($fullpath,0777);
                   3215:             }
                   3216:         }
                   3217:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   3218:         print $fh $env{'form.'.$formname};
                   3219:         close($fh);
1.1090    raeburn  3220:         if ($context eq 'existingfile') {
                   3221:             my @info = stat($fullpath.'/'.$fname);
                   3222:             return ($fullpath.'/'.$fname,$info[9]);
                   3223:         } else {
                   3224:             return $fullpath.'/'.$fname;
                   3225:         }
1.523     raeburn  3226:     }
1.995     raeburn  3227:     if ($subdir eq 'scantron') {
                   3228:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3229:     } else {
1.995     raeburn  3230:         $fname="$subdir/$fname";
                   3231:     }
1.1090    raeburn  3232:     if ($context eq 'coursedoc') {
1.638     albertel 3233: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3234: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3235:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3236:             return &finishuserfileupload($docuname,$docudom,
                   3237: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3238: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3239:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3240:         } else {
1.1172.2.21  raeburn  3241:             if ($env{'form.folder'}) {
                   3242:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3243:             }
1.638     albertel 3244:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3245: 				       $fname,$formname,$parser,
1.1095    raeburn  3246: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3247:         }
1.719     banghart 3248:     } elsif (defined($destuname)) {
                   3249:         my $docuname=$destuname;
                   3250:         my $docudom=$destudom;
1.860     raeburn  3251: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3252: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3253:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3254:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3255:     } else {
1.638     albertel 3256:         my $docuname=$env{'user.name'};
                   3257:         my $docudom=$env{'user.domain'};
1.1172.2.23  raeburn  3258:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3259:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3260:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3261:         }
1.860     raeburn  3262: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3263: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3264:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3265:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3266:     }
1.271     www      3267: }
                   3268: 
                   3269: sub finishuserfileupload {
1.860     raeburn  3270:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3271:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3272:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3273:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3274:   
1.860     raeburn  3275:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3276:     $file=$fname;
                   3277:     if ($fname=~m|/|) {
                   3278:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3279: 	$path.=$fnamepath.'/';
                   3280:     }
1.259     www      3281:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3282:     my $count;
                   3283:     for ($count=4;$count<=$#parts;$count++) {
                   3284:         $filepath.="/$parts[$count]";
                   3285:         if ((-e $filepath)!=1) {
                   3286: 	    mkdir($filepath,0777);
                   3287:         }
                   3288:     }
1.984     neumanie 3289: 
1.258     www      3290: # Save the file
                   3291:     {
1.701     albertel 3292: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   3293: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3294: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3295: 	    return '/adm/notfound.html';
                   3296: 	}
1.1090    raeburn  3297:         if ($context eq 'overwrite') {
1.1117    foxr     3298:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3299:             my $target = $filepath.'/'.$file;
                   3300:             if (-e $source) {
                   3301:                 my @info = stat($source);
                   3302:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3303:                     unless (&File::Copy::move($source,$target)) {
                   3304:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3305:                         return "Moving from $source failed";
                   3306:                     }
                   3307:                 } else {
                   3308:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3309:                 }
                   3310:             } else {
                   3311:                 return "Temporary file: $source missing";
                   3312:             }
                   3313:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3314: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3315: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3316: 	    return '/adm/notfound.html';
                   3317: 	}
1.570     albertel 3318: 	close(FH);
1.1051    raeburn  3319:         if ($resizewidth && $resizeheight) {
                   3320:             my $mm = new File::MMagic;
                   3321:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3322:             if ($mime_type =~ m{^image/}) {
                   3323: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3324:             }  
1.977     amueller 3325: 	}
1.258     www      3326:     }
1.1152    raeburn  3327:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3328:         if (ref($mimetype)) {
                   3329:             if ($$mimetype eq '') {
                   3330:                 my $mm = new File::MMagic;
                   3331:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3332:                 $$mimetype = $type;
                   3333:             }
                   3334:         }
                   3335:     }
1.637     raeburn  3336:     if ($parser eq 'parse') {
1.1152    raeburn  3337:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3338:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3339:                                                        $allfiles,$codebase);
                   3340:             unless ($parse_result eq 'ok') {
                   3341:                 &logthis('Failed to parse '.$filepath.$file.
                   3342: 	   	         ' for embedded media: '.$parse_result); 
                   3343:             }
1.637     raeburn  3344:         }
                   3345:     }
1.860     raeburn  3346:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3347:         my $input = $filepath.'/'.$file;
                   3348:         my $output = $filepath.'/'.'tn-'.$file;
                   3349:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3350:         system("convert -sample $thumbsize $input $output");
                   3351:         if (-e $filepath.'/'.'tn-'.$file) {
                   3352:             $fetchthumb  = 1; 
                   3353:         }
                   3354:     }
1.858     raeburn  3355:  
1.259     www      3356: # Notify homeserver to grep it
                   3357: #
1.984     neumanie 3358:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3359:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3360:     if ($fetchresult eq 'ok') {
1.860     raeburn  3361:         if ($fetchthumb) {
                   3362:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3363:             if ($thumbresult ne 'ok') {
                   3364:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3365:                          $docuhome.': '.$thumbresult);
                   3366:             }
                   3367:         }
1.259     www      3368: #
1.258     www      3369: # Return the URL to it
1.494     albertel 3370:         return '/uploaded/'.$path.$file;
1.263     www      3371:     } else {
1.494     albertel 3372:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3373: 		 ': '.$fetchresult);
1.263     www      3374:         return '/adm/notfound.html';
1.858     raeburn  3375:     }
1.493     albertel 3376: }
                   3377: 
1.637     raeburn  3378: sub extract_embedded_items {
1.961     raeburn  3379:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3380:     my @state = ();
1.1164    raeburn  3381:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3382:     my %javafiles = (
                   3383:                       codebase => '',
                   3384:                       code => '',
                   3385:                       archive => ''
                   3386:                     );
                   3387:     my %mediafiles = (
                   3388:                       src => '',
                   3389:                       movie => '',
                   3390:                      );
1.648     raeburn  3391:     my $p;
                   3392:     if ($content) {
                   3393:         $p = HTML::LCParser->new($content);
                   3394:     } else {
1.961     raeburn  3395:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3396:     }
1.641     albertel 3397:     while (my $t=$p->get_token()) {
1.640     albertel 3398: 	if ($t->[0] eq 'S') {
                   3399: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3400: 	    push(@state, $tagname);
1.648     raeburn  3401:             if (lc($tagname) eq 'allow') {
                   3402:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3403:             }
1.640     albertel 3404: 	    if (lc($tagname) eq 'img') {
                   3405: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3406: 	    }
1.886     albertel 3407: 	    if (lc($tagname) eq 'a') {
1.1172.2.24  raeburn  3408:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
                   3409: 		    &add_filetype($allfiles,$attr->{'href'},'href');
                   3410:                 }
1.886     albertel 3411: 	    }
1.645     raeburn  3412:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3413:                 my $src;
1.645     raeburn  3414:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3415:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3416:                 } else {
1.1164    raeburn  3417:                     if ($attr->{'src'} ne '') {
                   3418:                         $src = $attr->{'src'};
                   3419:                         &add_filetype($allfiles,$src,'src');
                   3420:                     }
                   3421:                 }
                   3422:                 my $text = $p->get_trimmed_text();
                   3423:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3424:                     my @swfargs = split(/,/,$1);
                   3425:                     foreach my $item (@swfargs) {
                   3426:                         $item =~ s/["']//g;
                   3427:                         $item =~ s/^\s+//;
                   3428:                         $item =~ s/\s+$//;
                   3429:                     }
                   3430:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3431:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3432:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3433:                         } else {
                   3434:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3435:                         }
                   3436:                     }
1.645     raeburn  3437:                 }
                   3438:             }
                   3439:             if (lc($tagname) eq 'link') {
                   3440:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3441:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3442:                 }
                   3443:             }
1.640     albertel 3444: 	    if (lc($tagname) eq 'object' ||
                   3445: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3446: 		foreach my $item (keys(%javafiles)) {
                   3447: 		    $javafiles{$item} = '';
                   3448: 		}
1.1164    raeburn  3449:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3450:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3451:                 }
1.640     albertel 3452: 	    }
                   3453: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3454: 		my $name = lc($attr->{'name'});
                   3455: 		foreach my $item (keys(%javafiles)) {
                   3456: 		    if ($name eq $item) {
                   3457: 			$javafiles{$item} = $attr->{'value'};
                   3458: 			last;
                   3459: 		    }
                   3460: 		}
1.1164    raeburn  3461:                 my $pathfrom;
1.640     albertel 3462: 		foreach my $item (keys(%mediafiles)) {
                   3463: 		    if ($name eq $item) {
1.1164    raeburn  3464:                         $pathfrom = $attr->{'value'};
                   3465:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3466: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3467: 			last;
                   3468: 		    }
                   3469: 		}
1.1164    raeburn  3470:                 if ($name eq 'flashvars') {
                   3471:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3472:                 }
                   3473:                 if ($pathfrom ne '') {
                   3474:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3475:                                          $pathfrom);
                   3476:                 }
1.640     albertel 3477: 	    }
                   3478: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3479: 		foreach my $item (keys(%javafiles)) {
                   3480: 		    if ($attr->{$item}) {
                   3481: 			$javafiles{$item} = $attr->{$item};
                   3482: 			last;
                   3483: 		    }
                   3484: 		}
                   3485: 		foreach my $item (keys(%mediafiles)) {
                   3486: 		    if ($attr->{$item}) {
                   3487: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3488: 			last;
                   3489: 		    }
                   3490: 		}
1.1164    raeburn  3491:                 if (lc($tagname) eq 'embed') {
                   3492:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3493:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3494:                                              $attr->{'src'});
                   3495:                     }
                   3496:                 }
1.640     albertel 3497: 	    }
1.1172.2.35! raeburn  3498:             if (lc($tagname) eq 'iframe') {
        !          3499:                 my $src = $attr->{'src'} ;
        !          3500:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
        !          3501:                     &add_filetype($allfiles,$src,'src');
        !          3502:                 } elsif ($src =~ m{^/}) {
        !          3503:                     if ($env{'request.course.id'}) {
        !          3504:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
        !          3505:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
        !          3506:                         my $url = &hreflocation('',$fullpath);
        !          3507:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
        !          3508:                             my $relpath = $1;
        !          3509:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
        !          3510:                                 &add_filetype($allfiles,$1,'src');
        !          3511:                             }
        !          3512:                         }
        !          3513:                     }
        !          3514:                 }
        !          3515:             }
1.1164    raeburn  3516:             if ($t->[4] =~ m{/>$}) {
1.1172.2.35! raeburn  3517:                 pop(@state);
1.1164    raeburn  3518:             }
1.640     albertel 3519: 	} elsif ($t->[0] eq 'E') {
                   3520: 	    my ($tagname) = ($t->[1]);
                   3521: 	    if ($javafiles{'codebase'} ne '') {
                   3522: 		$javafiles{'codebase'} .= '/';
                   3523: 	    }  
                   3524: 	    if (lc($tagname) eq 'applet' ||
                   3525: 		lc($tagname) eq 'object' ||
                   3526: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3527: 		) {
                   3528: 		foreach my $item (keys(%javafiles)) {
                   3529: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3530: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3531: 			&add_filetype($allfiles,$file,$item);
                   3532: 		    }
                   3533: 		}
                   3534: 	    } 
                   3535: 	    pop @state;
                   3536: 	}
                   3537:     }
1.1164    raeburn  3538:     foreach my $id (sort(keys(%flashvars))) {
                   3539:         if ($shockwave{$id} ne '') {
                   3540:             my @pairs = split(/\&/,$flashvars{$id});
                   3541:             foreach my $pair (@pairs) {
                   3542:                 my ($key,$value) = split(/\=/,$pair);
                   3543:                 if ($key eq 'thumb') {
                   3544:                     &add_filetype($allfiles,$value,$key);
                   3545:                 } elsif ($key eq 'content') {
                   3546:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3547:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3548:                     if ($ext ne '') {
                   3549:                         &add_filetype($allfiles,$path.$value,$ext);
                   3550:                     }
                   3551:                 }
                   3552:             }
                   3553:         }
                   3554:     }
1.637     raeburn  3555:     return 'ok';
                   3556: }
                   3557: 
1.639     albertel 3558: sub add_filetype {
                   3559:     my ($allfiles,$file,$type)=@_;
                   3560:     if (exists($allfiles->{$file})) {
                   3561: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3562: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3563: 	}
                   3564:     } else {
                   3565: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3566:     }
                   3567: }
                   3568: 
1.1164    raeburn  3569: sub embedded_dependency {
                   3570:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3571:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3572:         if (($identifier ne '') &&
                   3573:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3574:             ($pathfrom ne '')) {
                   3575:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3576:             foreach my $dep (@{$related->{$identifier}}) {
                   3577:                 &add_filetype($allfiles,$path.$dep,'object');
                   3578:             }
                   3579:         }
                   3580:     }
                   3581:     return;
                   3582: }
                   3583: 
1.493     albertel 3584: sub removeuploadedurl {
1.984     neumanie 3585:     my ($url)=@_;	
                   3586:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3587:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3588: }
                   3589: 
                   3590: sub removeuserfile {
                   3591:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3592:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3593:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3594:     if ($result eq 'ok') {	
1.798     raeburn  3595:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3596:             my $metafile = $fname.'.meta';
                   3597:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3598: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3599:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3600:             my $sqlresult = 
1.823     albertel 3601:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3602:                                         'portfolio_metadata',$group,
                   3603:                                         'delete');
1.798     raeburn  3604:         }
                   3605:     }
                   3606:     return $result;
1.257     www      3607: }
1.15      www      3608: 
1.530     albertel 3609: sub mkdiruserfile {
                   3610:     my ($docuname,$docudom,$dir)=@_;
                   3611:     my $home=&homeserver($docuname,$docudom);
                   3612:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3613: }
                   3614: 
1.531     albertel 3615: sub renameuserfile {
                   3616:     my ($docuname,$docudom,$old,$new)=@_;
                   3617:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3618:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3619:                         &escape("$old").':'.&escape("$new"),$home);
                   3620:     if ($result eq 'ok') {
                   3621:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3622:             my $oldmeta = $old.'.meta';
                   3623:             my $newmeta = $new.'.meta';
                   3624:             my $metaresult = 
                   3625:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3626: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3627:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3628:             my $sqlresult = 
1.823     albertel 3629:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3630:                                         'portfolio_metadata',$group,
                   3631:                                         'delete');
1.798     raeburn  3632:         }
                   3633:     }
                   3634:     return $result;
1.531     albertel 3635: }
                   3636: 
1.14      www      3637: # ------------------------------------------------------------------------- Log
                   3638: 
                   3639: sub log {
                   3640:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3641:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3642: }
                   3643: 
                   3644: # ------------------------------------------------------------------ Course Log
1.352     www      3645: #
                   3646: # This routine flushes several buffers of non-mission-critical nature
                   3647: #
1.157     www      3648: 
                   3649: sub flushcourselogs {
1.352     www      3650:     &logthis('Flushing log buffers');
                   3651: #
                   3652: # course logs
                   3653: # This is a log of all transactions in a course, which can be used
                   3654: # for data mining purposes
                   3655: #
                   3656: # It also collects the courseid database, which lists last transaction
                   3657: # times and course titles for all courseids
                   3658: #
                   3659:     my %courseidbuffer=();
1.921     raeburn  3660:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3661:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3662: 		          &escape($courselogs{$crsid}),
                   3663: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3664: 	    delete $courselogs{$crsid};
                   3665:         } else {
                   3666:             &logthis('Failed to flush log buffer for '.$crsid);
                   3667:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3668:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3669:                         " exceeded maximum size, deleting.</font>");
                   3670:                delete $courselogs{$crsid};
                   3671:             }
1.352     www      3672:         }
1.920     raeburn  3673:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3674:             'description' => $coursedescrbuf{$crsid},
                   3675:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3676:             'type'        => $coursetypebuf{$crsid},
                   3677:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3678:         };
1.191     harris41 3679:     }
1.352     www      3680: #
                   3681: # Write course id database (reverse lookup) to homeserver of courses 
                   3682: # Is used in pickcourse
                   3683: #
1.840     albertel 3684:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3685:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3686:                                     $courseidbuffer{$crs_home},
                   3687:                                     $crs_home,'timeonly');
1.352     www      3688:     }
                   3689: #
                   3690: # File accesses
                   3691: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3692: #
1.449     matthew  3693:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3694:         if ($entry =~ /___count$/) {
                   3695:             my ($dom,$name);
1.807     albertel 3696:             ($dom,$name,undef)=
1.811     albertel 3697: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3698:             if (! defined($dom) || $dom eq '' || 
                   3699:                 ! defined($name) || $name eq '') {
1.620     albertel 3700:                 my $cid = $env{'request.course.id'};
                   3701:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3702:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3703:             }
1.450     matthew  3704:             my $value = $accesshash{$entry};
                   3705:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   3706:             my %temphash=($url => $value);
1.449     matthew  3707:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   3708:             if ($result eq 'ok') {
                   3709:                 delete $accesshash{$entry};
                   3710:             }
                   3711:         } else {
1.811     albertel 3712:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      3713:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  3714:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3715:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3716:                 delete $accesshash{$entry};
                   3717:             }
1.185     www      3718:         }
1.191     harris41 3719:     }
1.352     www      3720: #
                   3721: # Roles
                   3722: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   3723: #
1.800     albertel 3724:     foreach my $entry (keys(%userrolehash)) {
1.351     www      3725:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      3726: 	    split(/\:/,$entry);
                   3727:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      3728:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      3729:                 $rudom,$runame) eq 'ok') {
                   3730: 	    delete $userrolehash{$entry};
                   3731:         }
                   3732:     }
1.662     raeburn  3733: #
                   3734: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   3735: #
                   3736:     my %domrolebuffer = ();
1.1000    raeburn  3737:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 3738:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  3739:         if ($domrolebuffer{$rudom}) {
                   3740:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   3741:                       '='.&escape($domainrolehash{$entry});
                   3742:         } else {
                   3743:             $domrolebuffer{$rudom}.=&escape($entry).
                   3744:                       '='.&escape($domainrolehash{$entry});
                   3745:         }
                   3746:         delete $domainrolehash{$entry};
                   3747:     }
                   3748:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 3749: 	my %servers = &get_servers($dom,'library');
                   3750: 	foreach my $tryserver (keys(%servers)) {
                   3751: 	    unless (&reply('domroleput:'.$dom.':'.
                   3752: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   3753: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   3754: 	    }
1.662     raeburn  3755:         }
                   3756:     }
1.186     www      3757:     $dumpcount++;
1.157     www      3758: }
                   3759: 
                   3760: sub courselog {
                   3761:     my $what=shift;
1.158     www      3762:     $what=time.':'.$what;
1.620     albertel 3763:     unless ($env{'request.course.id'}) { return ''; }
                   3764:     $coursedombuf{$env{'request.course.id'}}=
                   3765:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3766:     $coursenumbuf{$env{'request.course.id'}}=
                   3767:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   3768:     $coursehombuf{$env{'request.course.id'}}=
                   3769:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   3770:     $coursedescrbuf{$env{'request.course.id'}}=
                   3771:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   3772:     $courseinstcodebuf{$env{'request.course.id'}}=
                   3773:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   3774:     $courseownerbuf{$env{'request.course.id'}}=
                   3775:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  3776:     $coursetypebuf{$env{'request.course.id'}}=
                   3777:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 3778:     if (defined $courselogs{$env{'request.course.id'}}) {
                   3779: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      3780:     } else {
1.620     albertel 3781: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      3782:     }
1.620     albertel 3783:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      3784: 	&flushcourselogs();
                   3785:     }
1.158     www      3786: }
                   3787: 
                   3788: sub courseacclog {
                   3789:     my $fnsymb=shift;
1.620     albertel 3790:     unless ($env{'request.course.id'}) { return ''; }
                   3791:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      3792:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      3793:         $what.=':POST';
1.583     matthew  3794:         # FIXME: Probably ought to escape things....
1.800     albertel 3795: 	foreach my $key (keys(%env)) {
                   3796:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  3797:                 my $formitem = $1;
                   3798:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   3799:                     $what.=':'.$formitem.'='.$env{$key};
                   3800:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   3801:                     $what.=':'.$formitem.'='.$env{$key};
                   3802:                 }
1.158     www      3803:             }
1.191     harris41 3804:         }
1.583     matthew  3805:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   3806:         # FIXME: We should not be depending on a form parameter that someone
                   3807:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 3808:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  3809:             $what.= ':POST';
                   3810:             # FIXME: Probably ought to escape things....
                   3811:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   3812:                                  'crsdiscuss') {
1.620     albertel 3813:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  3814:             }
                   3815:         }
1.158     www      3816:     }
                   3817:     &courselog($what);
1.149     www      3818: }
                   3819: 
1.185     www      3820: sub countacc {
                   3821:     my $url=&declutter(shift);
1.458     matthew  3822:     return if (! defined($url) || $url eq '');
1.620     albertel 3823:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      3824: #
                   3825: # Mark that this url was used in this course
                   3826: #
1.620     albertel 3827:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      3828: #
                   3829: # Increase the access count for this resource in this child process
                   3830: #
1.281     www      3831:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  3832:     $accesshash{$key}++;
1.185     www      3833: }
1.349     www      3834: 
1.361     www      3835: sub linklog {
                   3836:     my ($from,$to)=@_;
                   3837:     $from=&declutter($from);
                   3838:     $to=&declutter($to);
                   3839:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   3840:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   3841: }
1.1160    www      3842: 
                   3843: sub statslog {
                   3844:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   3845:     if ($users<2) { return; }
                   3846:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   3847:             'course'       => $env{'request.course.id'},
                   3848:             'sections'     => '"all"',
                   3849:             'num_students' => $users,
                   3850:             'part'         => $part,
                   3851:             'symb'         => $symb,
                   3852:             'mean_tries'   => $av_attempts,
                   3853:             'deg_of_diff'  => $degdiff});
                   3854:     foreach my $key (keys(%dynstore)) {
                   3855:         $accesshash{$key}=$dynstore{$key};
                   3856:     }
                   3857: }
1.361     www      3858:   
1.349     www      3859: sub userrolelog {
                   3860:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 3861:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      3862:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3863:        $userrolehash
                   3864:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      3865:                     =$tend.':'.$tstart;
1.662     raeburn  3866:     }
1.1169    droeschl 3867:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 3868:        $userrolehash
                   3869:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   3870:                     =$tend.':'.$tstart;
                   3871:     }
1.1169    droeschl 3872:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662     raeburn  3873:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3874:        $domainrolehash
                   3875:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3876:                     = $tend.':'.$tstart;
                   3877:     }
1.351     www      3878: }
                   3879: 
1.957     raeburn  3880: sub courserolelog {
                   3881:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  3882:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3883:         my $cdom = $1;
                   3884:         my $cnum = $2;
                   3885:         my $sec = $3;
                   3886:         my $namespace = 'rolelog';
                   3887:         my %storehash = (
                   3888:                            role    => $trole,
                   3889:                            start   => $tstart,
                   3890:                            end     => $tend,
                   3891:                            selfenroll => $selfenroll,
                   3892:                            context    => $context,
                   3893:                         );
                   3894:         if ($trole eq 'gr') {
                   3895:             $namespace = 'groupslog';
                   3896:             $storehash{'group'} = $sec;
                   3897:         } else {
                   3898:             $storehash{'section'} = $sec;
                   3899:         }
                   3900:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   3901:                    $domain,$cnum,$cdom);
                   3902:         if (($trole ne 'st') || ($sec ne '')) {
                   3903:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  3904:         }
                   3905:     }
                   3906:     return;
                   3907: }
                   3908: 
1.1172.2.9  raeburn  3909: sub domainrolelog {
                   3910:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   3911:     if ($area =~ m{^/($match_domain)/$}) {
                   3912:         my $cdom = $1;
                   3913:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   3914:         my $namespace = 'rolelog';
                   3915:         my %storehash = (
                   3916:                            role    => $trole,
                   3917:                            start   => $tstart,
                   3918:                            end     => $tend,
                   3919:                            context => $context,
                   3920:                         );
                   3921:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   3922:                    $domain,$domconfiguser,$cdom);
                   3923:     }
                   3924:     return;
                   3925: 
                   3926: }
                   3927: 
                   3928: sub coauthorrolelog {
                   3929:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   3930:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   3931:         my $audom = $1;
                   3932:         my $auname = $2;
                   3933:         my $namespace = 'rolelog';
                   3934:         my %storehash = (
                   3935:                            role    => $trole,
                   3936:                            start   => $tstart,
                   3937:                            end     => $tend,
                   3938:                            context => $context,
                   3939:                         );
                   3940:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   3941:                    $domain,$auname,$audom);
                   3942:     }
                   3943:     return;
                   3944: }
                   3945: 
1.351     www      3946: sub get_course_adv_roles {
1.948     raeburn  3947:     my ($cid,$codes) = @_;
1.620     albertel 3948:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      3949:     my %coursehash=&coursedescription($cid);
1.988     raeburn  3950:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      3951:     my %nothide=();
1.800     albertel 3952:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  3953:         if ($user !~ /:/) {
                   3954: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   3955:         } else {
                   3956:             $nothide{$user}=1;
                   3957:         }
1.470     www      3958:     }
1.1172.2.23  raeburn  3959:     my @possdoms = ($coursehash{'domain'});
                   3960:     if ($coursehash{'checkforpriv'}) {
                   3961:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   3962:     }
1.351     www      3963:     my %returnhash=();
                   3964:     my %dumphash=
                   3965:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   3966:     my $now=time;
1.997     raeburn  3967:     my %privileged;
1.1000    raeburn  3968:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 3969: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      3970:         if (($tstart) && ($tstart<0)) { next; }
                   3971:         if (($tend) && ($tend<$now)) { next; }
                   3972:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 3973:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 3974: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  3975:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  3976:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 3977: 	if ($role eq 'cr') { next; }
1.948     raeburn  3978:         if ($codes) {
                   3979:             if ($section) { $role .= ':'.$section; }
                   3980:             if ($returnhash{$role}) {
                   3981:                 $returnhash{$role}.=','.$username.':'.$domain;
                   3982:             } else {
                   3983:                 $returnhash{$role}=$username.':'.$domain;
                   3984:             }
1.351     www      3985:         } else {
1.988     raeburn  3986:             my $key=&plaintext($role,$crstype);
1.973     bisitz   3987:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  3988:             if ($returnhash{$key}) {
                   3989: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   3990:             } else {
                   3991:                 $returnhash{$key}=$username.':'.$domain;
                   3992:             }
1.351     www      3993:         }
1.948     raeburn  3994:     }
1.400     www      3995:     return %returnhash;
                   3996: }
                   3997: 
                   3998: sub get_my_roles {
1.937     raeburn  3999:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4000:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4001:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4002:     my (%dumphash,%nothide);
1.1086    raeburn  4003:     if ($context eq 'userroles') {
1.1166    raeburn  4004:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4005:     } else {
1.1172.2.23  raeburn  4006:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4007:         if ($hidepriv) {
                   4008:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4009:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4010:                 if ($user !~ /:/) {
                   4011:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4012:                 } else {
                   4013:                     $nothide{$user} = 1;
                   4014:                 }
                   4015:             }
                   4016:         }
1.858     raeburn  4017:     }
1.400     www      4018:     my %returnhash=();
                   4019:     my $now=time;
1.999     raeburn  4020:     my %privileged;
1.800     albertel 4021:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4022:         my ($role,$tend,$tstart);
                   4023:         if ($context eq 'userroles') {
1.1149    raeburn  4024:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4025: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4026:         } else {
                   4027:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4028:         }
1.400     www      4029:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4030:         my $status = 'active';
1.939     raeburn  4031:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4032:             $status = 'previous';
                   4033:         } 
                   4034:         if (($tstart) && ($now<$tstart)) {
                   4035:             $status = 'future';
                   4036:         }
                   4037:         if (ref($types) eq 'ARRAY') {
                   4038:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4039:                 next;
                   4040:             } 
                   4041:         } else {
                   4042:             if ($status ne 'active') {
                   4043:                 next;
                   4044:             }
                   4045:         }
1.867     raeburn  4046:         my ($rolecode,$username,$domain,$section,$area);
                   4047:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  4048:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4049:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4050:         } else {
                   4051:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4052:         }
1.832     raeburn  4053:         if (ref($roledoms) eq 'ARRAY') {
                   4054:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4055:                 next;
                   4056:             }
                   4057:         }
                   4058:         if (ref($roles) eq 'ARRAY') {
                   4059:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4060:                 if ($role =~ /^cr\//) {
                   4061:                     if (!grep(/^cr$/,@{$roles})) {
                   4062:                         next;
                   4063:                     }
1.1104    raeburn  4064:                 } elsif ($role =~ /^gr\//) {
                   4065:                     if (!grep(/^gr$/,@{$roles})) {
                   4066:                         next;
                   4067:                     }
1.922     raeburn  4068:                 } else {
                   4069:                     next;
                   4070:                 }
1.832     raeburn  4071:             }
1.867     raeburn  4072:         }
1.937     raeburn  4073:         if ($hidepriv) {
1.1172.2.23  raeburn  4074:             my @privroles = ('dc','su');
1.999     raeburn  4075:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  4076:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4077:             } else {
1.1172.2.23  raeburn  4078:                 my $possdoms = [$domain];
                   4079:                 if (ref($roledoms) eq 'ARRAY') {
                   4080:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  4081:                 }
1.1172.2.23  raeburn  4082:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4083:                     if (!$nothide{$username.':'.$domain}) {
                   4084:                         next;
                   4085:                     }
                   4086:                 }
1.937     raeburn  4087:             }
                   4088:         }
1.933     raeburn  4089:         if ($withsec) {
                   4090:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4091:                 $tstart.':'.$tend;
                   4092:         } else {
                   4093:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4094:         }
1.832     raeburn  4095:     }
1.373     www      4096:     return %returnhash;
1.399     www      4097: }
                   4098: 
                   4099: # ----------------------------------------------------- Frontpage Announcements
                   4100: #
                   4101: #
                   4102: 
                   4103: sub postannounce {
                   4104:     my ($server,$text)=@_;
1.844     albertel 4105:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4106:     unless ($text=~/\w/) { $text=''; }
                   4107:     return &reply('setannounce:'.&escape($text),$server);
                   4108: }
                   4109: 
                   4110: sub getannounce {
1.448     albertel 4111: 
                   4112:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4113: 	my $announcement='';
1.800     albertel 4114: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4115: 	close($fh);
1.399     www      4116: 	if ($announcement=~/\w/) { 
                   4117: 	    return 
                   4118:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4119:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4120: 	} else {
                   4121: 	    return '';
                   4122: 	}
                   4123:     } else {
                   4124: 	return '';
                   4125:     }
1.351     www      4126: }
1.353     www      4127: 
                   4128: # ---------------------------------------------------------- Course ID routines
                   4129: # Deal with domain's nohist_courseid.db files
                   4130: #
                   4131: 
                   4132: sub courseidput {
1.921     raeburn  4133:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4134:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4135:     my $outcome;
                   4136:     if ($caller eq 'timeonly') {
                   4137:         my $cids = '';
                   4138:         foreach my $item (keys(%$storehash)) {
                   4139:             $cids.=&escape($item).'&';
                   4140:         }
                   4141:         $cids=~s/\&$//;
                   4142:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4143:                           $coursehome);       
                   4144:     } else {
                   4145:         my $items = '';
                   4146:         foreach my $item (keys(%$storehash)) {
                   4147:             $items.= &escape($item).'='.
                   4148:                      &freeze_escape($$storehash{$item}).'&';
                   4149:         }
                   4150:         $items=~s/\&$//;
                   4151:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4152:                           $coursehome);
1.918     raeburn  4153:     }
                   4154:     if ($outcome eq 'unknown_cmd') {
                   4155:         my $what;
                   4156:         foreach my $cid (keys(%$storehash)) {
                   4157:             $what .= &escape($cid).'=';
1.921     raeburn  4158:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4159:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4160:             }
                   4161:             $what =~ s/\:$/&/;
                   4162:         }
                   4163:         $what =~ s/\&$//;  
                   4164:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4165:     } else {
                   4166:         return $outcome;
                   4167:     }
1.353     www      4168: }
                   4169: 
                   4170: sub courseiddump {
1.921     raeburn  4171:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4172:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4173:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071    raeburn  4174:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  4175:     my $as_hash = 1;
                   4176:     my %returnhash;
                   4177:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4178:     my %libserv = &all_library();
                   4179:     foreach my $tryserver (keys(%libserv)) {
                   4180:         if ( (  $hostidflag == 1 
                   4181: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4182: 	     || (!defined($hostidflag)) ) {
                   4183: 
1.918     raeburn  4184: 	    if (($domfilter eq '') ||
                   4185: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  4186:                 my $rep;
                   4187:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   4188:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   4189:                         join(":", (&host_domain($tryserver), $sincefilter,
                   4190:                                 &escape($descfilter), &escape($instcodefilter),
                   4191:                                 &escape($ownerfilter), &escape($coursefilter),
                   4192:                                 &escape($typefilter), &escape($regexp_ok),
                   4193:                                 $as_hash, &escape($selfenrollonly),
                   4194:                                 &escape($catfilter), $showhidden, $caller,
                   4195:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   4196:                                 &escape($createdbefore), &escape($createdafter),
                   4197:                                 &escape($creationcontext), $domcloner)));
                   4198:                 } else {
                   4199:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4200:                              $sincefilter.':'.&escape($descfilter).':'.
                   4201:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   4202:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   4203:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   4204:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   4205:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   4206:                              &escape($cc_clone).':'.$cloneonly.':'.
                   4207:                              &escape($createdbefore).':'.&escape($createdafter).':'.
                   4208:                              &escape($creationcontext).':'.$domcloner,
                   4209:                              $tryserver);
                   4210:                 }
                   4211: 
1.918     raeburn  4212:                 my @pairs=split(/\&/,$rep);
                   4213:                 foreach my $item (@pairs) {
                   4214:                     my ($key,$value)=split(/\=/,$item,2);
                   4215:                     $key = &unescape($key);
                   4216:                     next if ($key =~ /^error: 2 /);
                   4217:                     my $result = &thaw_unescape($value);
                   4218:                     if (ref($result) eq 'HASH') {
                   4219:                         $returnhash{$key}=$result;
                   4220:                     } else {
1.921     raeburn  4221:                         my @responses = split(/:/,$value);
                   4222:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4223:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4224:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4225:                         }
1.1008    raeburn  4226:                     }
1.353     www      4227:                 }
                   4228:             }
                   4229:         }
                   4230:     }
                   4231:     return %returnhash;
                   4232: }
                   4233: 
1.1055    raeburn  4234: sub courselastaccess {
                   4235:     my ($cdom,$cnum,$hostidref) = @_;
                   4236:     my %returnhash;
                   4237:     if ($cdom && $cnum) {
                   4238:         my $chome = &homeserver($cnum,$cdom);
                   4239:         if ($chome ne 'no_host') {
                   4240:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4241:             &extract_lastaccess(\%returnhash,$rep);
                   4242:         }
                   4243:     } else {
                   4244:         if (!$cdom) { $cdom=''; }
                   4245:         my %libserv = &all_library();
                   4246:         foreach my $tryserver (keys(%libserv)) {
                   4247:             if (ref($hostidref) eq 'ARRAY') {
                   4248:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4249:             } 
                   4250:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4251:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4252:                 &extract_lastaccess(\%returnhash,$rep);
                   4253:             }
                   4254:         }
                   4255:     }
                   4256:     return %returnhash;
                   4257: }
                   4258: 
                   4259: sub extract_lastaccess {
                   4260:     my ($returnhash,$rep) = @_;
                   4261:     if (ref($returnhash) eq 'HASH') {
                   4262:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4263:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4264:                  $rep eq '') {
                   4265:             my @pairs=split(/\&/,$rep);
                   4266:             foreach my $item (@pairs) {
                   4267:                 my ($key,$value)=split(/\=/,$item,2);
                   4268:                 $key = &unescape($key);
                   4269:                 next if ($key =~ /^error: 2 /);
                   4270:                 $returnhash->{$key} = &thaw_unescape($value);
                   4271:             }
                   4272:         }
                   4273:     }
                   4274:     return;
                   4275: }
                   4276: 
1.658     raeburn  4277: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4278: 
                   4279: sub dcmailput {
1.685     raeburn  4280:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4281:     my $status = &Apache::lonnet::critical(
1.740     www      4282:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4283:        &escape($message),$server);
1.662     raeburn  4284:     return $status;
                   4285: }
                   4286: 
1.658     raeburn  4287: sub dcmaildump {
                   4288:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4289:     my %returnhash=();
1.846     albertel 4290: 
                   4291:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4292:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4293:                                                          &escape($enddate).':';
                   4294: 	my @esc_senders=map { &escape($_)} @$senders;
                   4295: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4296: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4297:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4298:             if (($key) && ($value)) {
                   4299:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4300:             }
                   4301:         }
                   4302:     }
                   4303:     return %returnhash;
                   4304: }
1.662     raeburn  4305: # ---------------------------------------------------------- Domain roles
                   4306: 
                   4307: sub get_domain_roles {
                   4308:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4309:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4310:         $startdate = '.';
                   4311:     }
1.1018    raeburn  4312:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4313:         $enddate = '.';
                   4314:     }
1.922     raeburn  4315:     my $rolelist;
                   4316:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  4317:         $rolelist = join('&',@{$roles});
1.922     raeburn  4318:     }
1.662     raeburn  4319:     my %personnel = ();
1.841     albertel 4320: 
                   4321:     my %servers = &get_servers($dom,'library');
                   4322:     foreach my $tryserver (keys(%servers)) {
                   4323: 	%{$personnel{$tryserver}}=();
                   4324: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4325: 					    &escape($startdate).':'.
                   4326: 					    &escape($enddate).':'.
                   4327: 					    &escape($rolelist), $tryserver))) {
                   4328: 	    my ($key,$value) = split(/\=/,$line,2);
                   4329: 	    if (($key) && ($value)) {
                   4330: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4331: 	    }
                   4332: 	}
1.662     raeburn  4333:     }
                   4334:     return %personnel;
                   4335: }
1.658     raeburn  4336: 
1.1057    www      4337: # ----------------------------------------------------------- Interval timing 
1.149     www      4338: 
1.1153    www      4339: {
                   4340: # Caches needed for speedup of navmaps
                   4341: # We don't want to cache this for very long at all (5 seconds at most)
                   4342: # 
                   4343: # The user for whom we cache
                   4344: my $cachedkey='';
                   4345: # The cached times for this user
                   4346: my %cachedtimes=();
                   4347: # When this was last done
                   4348: my $cachedtime=();
                   4349: 
                   4350: sub load_all_first_access {
1.1154    raeburn  4351:     my ($uname,$udom)=@_;
1.1156    www      4352:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2  raeburn  4353:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  4354:         return;
                   4355:     }
                   4356:     $cachedtime=time;
                   4357:     $cachedkey=$uname.':'.$udom;
                   4358:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4359: }
                   4360: 
1.504     albertel 4361: sub get_first_access {
1.1162    raeburn  4362:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 4363:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4364:     if ($argsymb) { $symb=$argsymb; }
                   4365:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4366:     if ($argmap) { $map = $argmap; }
1.926     albertel 4367:     if ($type eq 'course') {
                   4368: 	$res='course';
                   4369:     } elsif ($type eq 'map') {
1.588     albertel 4370: 	$res=&symbread($map);
                   4371:     } else {
                   4372: 	$res=$symb;
                   4373:     }
1.1153    www      4374:     &load_all_first_access($uname,$udom);
                   4375:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4376: }
                   4377: 
                   4378: sub set_first_access {
1.1162    raeburn  4379:     my ($type,$interval)=@_;
1.790     albertel 4380:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4381:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4382:     if ($type eq 'course') {
                   4383: 	$res='course';
                   4384:     } elsif ($type eq 'map') {
1.588     albertel 4385: 	$res=&symbread($map);
                   4386:     } else {
                   4387: 	$res=$symb;
                   4388:     }
1.1153    www      4389:     $cachedkey='';
1.1162    raeburn  4390:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4391:     if (!$firstaccess) {
1.1162    raeburn  4392:         my $start = time;
                   4393: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4394:                           $udom,$uname);
                   4395:         if ($putres eq 'ok') {
                   4396:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4397:                  $udom,$uname); 
                   4398:             &appenv(
                   4399:                      {
                   4400:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4401:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4402:                      }
                   4403:                   );
                   4404:         }
                   4405:         return $putres;
1.505     albertel 4406:     }
                   4407:     return 'already_set';
1.504     albertel 4408: }
1.1153    www      4409: }
1.1172.2.32  raeburn  4410: 
                   4411: sub checkout {
                   4412:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   4413:     my $now=time;
                   4414:     my $lonhost=$perlvar{'lonHostID'};
                   4415:     my $infostr=&escape(
                   4416:                  'CHECKOUTTOKEN&'.
                   4417:                  $tuname.'&'.
                   4418:                  $tudom.'&'.
                   4419:                  $tcrsid.'&'.
                   4420:                  $symb.'&'.
                   4421:                  $now.'&'.$ENV{'REMOTE_ADDR'});
                   4422:     my $token=&reply('tmpput:'.$infostr,$lonhost);
                   4423:     if ($token=~/^error\:/) {
                   4424:         &logthis("<font color=\"blue\">WARNING: ".
                   4425:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   4426:                  "</font>");
                   4427:         return '';
                   4428:     }
                   4429: 
                   4430:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   4431:     $token=~tr/a-z/A-Z/;
                   4432: 
                   4433:     my %infohash=('resource.0.outtoken' => $token,
                   4434:                   'resource.0.checkouttime' => $now,
                   4435:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
                   4436: 
                   4437:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   4438:        return '';
                   4439:     } else {
                   4440:         &logthis("<font color=\"blue\">WARNING: ".
                   4441:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   4442:                  "</font>");
                   4443:     }
                   4444: 
                   4445:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   4446:                          &escape('Checkout '.$infostr.' - '.
                   4447:                                                  $token)) ne 'ok') {
                   4448:         return '';
                   4449:     } else {
                   4450:         &logthis("<font color=\"blue\">WARNING: ".
                   4451:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   4452:                  "</font>");
                   4453:     }
                   4454:     return $token;
                   4455: }
                   4456: 
                   4457: # ------------------------------------------------------------ Check in an item
                   4458: 
                   4459: sub checkin {
                   4460:     my $token=shift;
                   4461:     my $now=time;
                   4462:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   4463:     $lonhost=~tr/A-Z/a-z/;
                   4464:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
                   4465:     $dtoken=~s/\W/\_/g;
                   4466:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                   4467:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   4468: 
                   4469:     unless (($tuname) && ($tudom)) {
                   4470:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   4471:         return '';
                   4472:     }
                   4473: 
                   4474:     unless (&allowed('mgr',$tcrsid)) {
                   4475:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   4476:                  $env{'user.name'}.' - '.$env{'user.domain'});
                   4477:         return '';
                   4478:     }
                   4479: 
                   4480:     my %infohash=('resource.0.intoken' => $token,
                   4481:                   'resource.0.checkintime' => $now,
                   4482:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
                   4483: 
                   4484:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   4485:        return '';
                   4486:     }
                   4487: 
                   4488:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   4489:                          &escape('Checkin - '.$token)) ne 'ok') {
                   4490:         return '';
                   4491:     }
                   4492: 
                   4493:     return ($symb,$tuname,$tudom,$tcrsid);
                   4494: }
                   4495: 
1.110     www      4496: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4497: 
                   4498: sub expirespread {
                   4499:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4500:     my $cid=$env{'request.course.id'}; 
1.110     www      4501:     if ($cid) {
                   4502:        my $now=time;
                   4503:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4504:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4505:                             $env{'course.'.$cid.'.num'}.
1.110     www      4506: 	        	    ':nohist_expirationdates:'.
                   4507:                             &escape($key).'='.$now,
1.620     albertel 4508:                             $env{'course.'.$cid.'.home'})
1.110     www      4509:     }
                   4510:     return 'ok';
1.14      www      4511: }
                   4512: 
1.109     www      4513: # ----------------------------------------------------- Devalidate Spreadsheets
                   4514: 
                   4515: sub devalidate {
1.325     www      4516:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4517:     my $cid=$env{'request.course.id'}; 
1.109     www      4518:     if ($cid) {
1.391     matthew  4519:         # delete the stored spreadsheets for
                   4520:         # - the student level sheet of this user in course's homespace
                   4521:         # - the assessment level sheet for this resource 
                   4522:         #   for this user in user's homespace
1.553     albertel 4523: 	# - current conditional state info
1.325     www      4524: 	my $key=$uname.':'.$udom.':';
1.109     www      4525:         my $status=
1.299     matthew  4526: 	    &del('nohist_calculatedsheets',
1.391     matthew  4527: 		 [$key.'studentcalc:'],
1.620     albertel 4528: 		 $env{'course.'.$cid.'.domain'},
                   4529: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4530: 		.' '.
                   4531: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4532: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4533:         unless ($status eq 'ok ok') {
                   4534:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4535:                     $uname.' at '.$udom.' for '.
1.109     www      4536: 		    $symb.': '.$status);
1.133     albertel 4537:         }
1.553     albertel 4538: 	&delenv('user.state.'.$cid);
1.109     www      4539:     }
                   4540: }
                   4541: 
1.265     albertel 4542: sub get_scalar {
                   4543:     my ($string,$end) = @_;
                   4544:     my $value;
                   4545:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4546: 	$value = $1;
                   4547:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4548: 	$value = $1;
                   4549:     }
                   4550:     return &unescape($value);
                   4551: }
                   4552: 
                   4553: sub array2str {
                   4554:   my (@array) = @_;
                   4555:   my $result=&arrayref2str(\@array);
                   4556:   $result=~s/^__ARRAY_REF__//;
                   4557:   $result=~s/__END_ARRAY_REF__$//;
                   4558:   return $result;
                   4559: }
                   4560: 
1.204     albertel 4561: sub arrayref2str {
                   4562:   my ($arrayref) = @_;
1.265     albertel 4563:   my $result='__ARRAY_REF__';
1.204     albertel 4564:   foreach my $elem (@$arrayref) {
1.265     albertel 4565:     if(ref($elem) eq 'ARRAY') {
                   4566:       $result.=&arrayref2str($elem).'&';
                   4567:     } elsif(ref($elem) eq 'HASH') {
                   4568:       $result.=&hashref2str($elem).'&';
                   4569:     } elsif(ref($elem)) {
                   4570:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4571:     } else {
                   4572:       $result.=&escape($elem).'&';
                   4573:     }
                   4574:   }
                   4575:   $result=~s/\&$//;
1.265     albertel 4576:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4577:   return $result;
                   4578: }
                   4579: 
1.168     albertel 4580: sub hash2str {
1.204     albertel 4581:   my (%hash) = @_;
                   4582:   my $result=&hashref2str(\%hash);
1.265     albertel 4583:   $result=~s/^__HASH_REF__//;
                   4584:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4585:   return $result;
                   4586: }
                   4587: 
                   4588: sub hashref2str {
                   4589:   my ($hashref)=@_;
1.265     albertel 4590:   my $result='__HASH_REF__';
1.800     albertel 4591:   foreach my $key (sort(keys(%$hashref))) {
                   4592:     if (ref($key) eq 'ARRAY') {
                   4593:       $result.=&arrayref2str($key).'=';
                   4594:     } elsif (ref($key) eq 'HASH') {
                   4595:       $result.=&hashref2str($key).'=';
                   4596:     } elsif (ref($key)) {
1.265     albertel 4597:       $result.='=';
1.800     albertel 4598:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 4599:     } else {
1.1132    raeburn  4600: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 4601:     }
                   4602: 
1.800     albertel 4603:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   4604:       $result.=&arrayref2str($hashref->{$key}).'&';
                   4605:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   4606:       $result.=&hashref2str($hashref->{$key}).'&';
                   4607:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4608:        $result.='&';
1.800     albertel 4609:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4610:     } else {
1.800     albertel 4611:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4612:     }
                   4613:   }
1.168     albertel 4614:   $result=~s/\&$//;
1.265     albertel 4615:   $result .= '__END_HASH_REF__';
1.168     albertel 4616:   return $result;
                   4617: }
                   4618: 
                   4619: sub str2hash {
1.265     albertel 4620:     my ($string)=@_;
                   4621:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4622:     return %$hash;
                   4623: }
                   4624: 
                   4625: sub str2hashref {
1.168     albertel 4626:   my ($string) = @_;
1.265     albertel 4627: 
                   4628:   my %hash;
                   4629: 
                   4630:   if($string !~ /^__HASH_REF__/) {
                   4631:       if (! ($string eq '' || !defined($string))) {
                   4632: 	  $hash{'error'}='Not hash reference';
                   4633:       }
                   4634:       return (\%hash, $string);
                   4635:   }
                   4636: 
                   4637:   $string =~ s/^__HASH_REF__//;
                   4638: 
                   4639:   while($string !~ /^__END_HASH_REF__/) {
                   4640:       #key
                   4641:       my $key='';
                   4642:       if($string =~ /^__HASH_REF__/) {
                   4643:           ($key, $string)=&str2hashref($string);
                   4644:           if(defined($key->{'error'})) {
                   4645:               $hash{'error'}='Bad data';
                   4646:               return (\%hash, $string);
                   4647:           }
                   4648:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4649:           ($key, $string)=&str2arrayref($string);
                   4650:           if($key->[0] eq 'Array reference error') {
                   4651:               $hash{'error'}='Bad data';
                   4652:               return (\%hash, $string);
                   4653:           }
                   4654:       } else {
                   4655:           $string =~ s/^(.*?)=//;
1.267     albertel 4656: 	  $key=&unescape($1);
1.265     albertel 4657:       }
                   4658:       $string =~ s/^=//;
                   4659: 
                   4660:       #value
                   4661:       my $value='';
                   4662:       if($string =~ /^__HASH_REF__/) {
                   4663:           ($value, $string)=&str2hashref($string);
                   4664:           if(defined($value->{'error'})) {
                   4665:               $hash{'error'}='Bad data';
                   4666:               return (\%hash, $string);
                   4667:           }
                   4668:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4669:           ($value, $string)=&str2arrayref($string);
                   4670:           if($value->[0] eq 'Array reference error') {
                   4671:               $hash{'error'}='Bad data';
                   4672:               return (\%hash, $string);
                   4673:           }
                   4674:       } else {
                   4675: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4676:       }
                   4677:       $string =~ s/^&//;
                   4678: 
                   4679:       $hash{$key}=$value;
1.204     albertel 4680:   }
1.265     albertel 4681: 
                   4682:   $string =~ s/^__END_HASH_REF__//;
                   4683: 
                   4684:   return (\%hash, $string);
1.204     albertel 4685: }
                   4686: 
                   4687: sub str2array {
1.265     albertel 4688:     my ($string)=@_;
                   4689:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4690:     return @$array;
                   4691: }
                   4692: 
                   4693: sub str2arrayref {
1.204     albertel 4694:   my ($string) = @_;
1.265     albertel 4695:   my @array;
                   4696: 
                   4697:   if($string !~ /^__ARRAY_REF__/) {
                   4698:       if (! ($string eq '' || !defined($string))) {
                   4699: 	  $array[0]='Array reference error';
                   4700:       }
                   4701:       return (\@array, $string);
                   4702:   }
                   4703: 
                   4704:   $string =~ s/^__ARRAY_REF__//;
                   4705: 
                   4706:   while($string !~ /^__END_ARRAY_REF__/) {
                   4707:       my $value='';
                   4708:       if($string =~ /^__HASH_REF__/) {
                   4709:           ($value, $string)=&str2hashref($string);
                   4710:           if(defined($value->{'error'})) {
                   4711:               $array[0] ='Array reference error';
                   4712:               return (\@array, $string);
                   4713:           }
                   4714:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4715:           ($value, $string)=&str2arrayref($string);
                   4716:           if($value->[0] eq 'Array reference error') {
                   4717:               $array[0] ='Array reference error';
                   4718:               return (\@array, $string);
                   4719:           }
                   4720:       } else {
                   4721: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   4722:       }
                   4723:       $string =~ s/^&//;
                   4724: 
                   4725:       push(@array, $value);
1.191     harris41 4726:   }
1.265     albertel 4727: 
                   4728:   $string =~ s/^__END_ARRAY_REF__//;
                   4729: 
                   4730:   return (\@array, $string);
1.168     albertel 4731: }
                   4732: 
1.167     albertel 4733: # -------------------------------------------------------------------Temp Store
                   4734: 
1.168     albertel 4735: sub tmpreset {
                   4736:   my ($symb,$namespace,$domain,$stuname) = @_;
                   4737:   if (!$symb) {
                   4738:     $symb=&symbread();
1.620     albertel 4739:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4740:   }
                   4741:   $symb=escape($symb);
                   4742: 
1.620     albertel 4743:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 4744:   $namespace=~s/\//\_/g;
                   4745:   $namespace=~s/\W//g;
                   4746: 
1.620     albertel 4747:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4748:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4749:   if ($domain eq 'public' && $stuname eq 'public') {
                   4750:       $stuname=$ENV{'REMOTE_ADDR'};
                   4751:   }
1.1117    foxr     4752:   my $path=LONCAPA::tempdir();
1.168     albertel 4753:   my %hash;
                   4754:   if (tie(%hash,'GDBM_File',
                   4755: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4756: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  4757:     foreach my $key (keys(%hash)) {
1.180     albertel 4758:       if ($key=~ /:$symb/) {
1.168     albertel 4759: 	delete($hash{$key});
                   4760:       }
                   4761:     }
                   4762:   }
                   4763: }
                   4764: 
1.167     albertel 4765: sub tmpstore {
1.168     albertel 4766:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4767: 
                   4768:   if (!$symb) {
                   4769:     $symb=&symbread();
1.620     albertel 4770:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4771:   }
                   4772:   $symb=escape($symb);
                   4773: 
                   4774:   if (!$namespace) {
                   4775:     # I don't think we would ever want to store this for a course.
                   4776:     # it seems this will only be used if we don't have a course.
1.620     albertel 4777:     #$namespace=$env{'request.course.id'};
1.168     albertel 4778:     #if (!$namespace) {
1.620     albertel 4779:       $namespace=$env{'request.state'};
1.168     albertel 4780:     #}
                   4781:   }
                   4782:   $namespace=~s/\//\_/g;
                   4783:   $namespace=~s/\W//g;
1.620     albertel 4784:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4785:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4786:   if ($domain eq 'public' && $stuname eq 'public') {
                   4787:       $stuname=$ENV{'REMOTE_ADDR'};
                   4788:   }
1.168     albertel 4789:   my $now=time;
                   4790:   my %hash;
1.1117    foxr     4791:   my $path=LONCAPA::tempdir();
1.168     albertel 4792:   if (tie(%hash,'GDBM_File',
                   4793: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4794: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 4795:     $hash{"version:$symb"}++;
                   4796:     my $version=$hash{"version:$symb"};
                   4797:     my $allkeys=''; 
                   4798:     foreach my $key (keys(%$storehash)) {
                   4799:       $allkeys.=$key.':';
1.591     albertel 4800:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 4801:     }
                   4802:     $hash{"$version:$symb:timestamp"}=$now;
                   4803:     $allkeys.='timestamp';
                   4804:     $hash{"$version:keys:$symb"}=$allkeys;
                   4805:     if (untie(%hash)) {
                   4806:       return 'ok';
                   4807:     } else {
                   4808:       return "error:$!";
                   4809:     }
                   4810:   } else {
                   4811:     return "error:$!";
                   4812:   }
                   4813: }
1.167     albertel 4814: 
1.168     albertel 4815: # -----------------------------------------------------------------Temp Restore
1.167     albertel 4816: 
1.168     albertel 4817: sub tmprestore {
                   4818:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 4819: 
1.168     albertel 4820:   if (!$symb) {
                   4821:     $symb=&symbread();
1.620     albertel 4822:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4823:   }
                   4824:   $symb=escape($symb);
                   4825: 
1.620     albertel 4826:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 4827: 
1.620     albertel 4828:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4829:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4830:   if ($domain eq 'public' && $stuname eq 'public') {
                   4831:       $stuname=$ENV{'REMOTE_ADDR'};
                   4832:   }
1.168     albertel 4833:   my %returnhash;
                   4834:   $namespace=~s/\//\_/g;
                   4835:   $namespace=~s/\W//g;
                   4836:   my %hash;
1.1117    foxr     4837:   my $path=LONCAPA::tempdir();
1.168     albertel 4838:   if (tie(%hash,'GDBM_File',
                   4839: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4840: 	  &GDBM_READER(),0640)) {
1.168     albertel 4841:     my $version=$hash{"version:$symb"};
                   4842:     $returnhash{'version'}=$version;
                   4843:     my $scope;
                   4844:     for ($scope=1;$scope<=$version;$scope++) {
                   4845:       my $vkeys=$hash{"$scope:keys:$symb"};
                   4846:       my @keys=split(/:/,$vkeys);
                   4847:       my $key;
                   4848:       $returnhash{"$scope:keys"}=$vkeys;
                   4849:       foreach $key (@keys) {
1.591     albertel 4850: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   4851: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 4852:       }
                   4853:     }
1.168     albertel 4854:     if (!(untie(%hash))) {
                   4855:       return "error:$!";
                   4856:     }
                   4857:   } else {
                   4858:     return "error:$!";
                   4859:   }
                   4860:   return %returnhash;
1.167     albertel 4861: }
                   4862: 
1.9       www      4863: # ----------------------------------------------------------------------- Store
                   4864: 
                   4865: sub store {
1.124     www      4866:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4867:     my $home='';
                   4868: 
1.168     albertel 4869:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4870: 
1.213     www      4871:     $symb=&symbclean($symb);
1.122     albertel 4872:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4873: 
1.620     albertel 4874:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4875:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4876: 
                   4877:     &devalidate($symb,$stuname,$domain);
1.109     www      4878: 
                   4879:     $symb=escape($symb);
1.187     www      4880:     if (!$namespace) { 
1.620     albertel 4881:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4882:           return ''; 
                   4883:        } 
                   4884:     }
1.620     albertel 4885:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4886: 
                   4887:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4888:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   4889: 
1.12      www      4890:     my $namevalue='';
1.800     albertel 4891:     foreach my $key (keys(%$storehash)) {
                   4892:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4893:     }
1.12      www      4894:     $namevalue=~s/\&$//;
1.187     www      4895:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      4896:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      4897: }
                   4898: 
1.47      www      4899: # -------------------------------------------------------------- Critical Store
                   4900: 
                   4901: sub cstore {
1.124     www      4902:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4903:     my $home='';
                   4904: 
1.168     albertel 4905:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4906: 
1.213     www      4907:     $symb=&symbclean($symb);
1.122     albertel 4908:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4909: 
1.620     albertel 4910:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4911:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4912: 
                   4913:     &devalidate($symb,$stuname,$domain);
1.109     www      4914: 
                   4915:     $symb=escape($symb);
1.187     www      4916:     if (!$namespace) { 
1.620     albertel 4917:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4918:           return ''; 
                   4919:        } 
                   4920:     }
1.620     albertel 4921:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4922: 
                   4923:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4924:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 4925: 
1.47      www      4926:     my $namevalue='';
1.800     albertel 4927:     foreach my $key (keys(%$storehash)) {
                   4928:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4929:     }
1.47      www      4930:     $namevalue=~s/\&$//;
1.187     www      4931:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      4932:     return critical
                   4933:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      4934: }
                   4935: 
1.9       www      4936: # --------------------------------------------------------------------- Restore
                   4937: 
                   4938: sub restore {
1.124     www      4939:     my ($symb,$namespace,$domain,$stuname) = @_;
                   4940:     my $home='';
                   4941: 
1.168     albertel 4942:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4943: 
1.122     albertel 4944:     if (!$symb) {
1.1172.2.26  raeburn  4945:         return if ($namespace eq 'courserequests');
                   4946:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 4947:     } else {
1.1172.2.26  raeburn  4948:         unless ($namespace eq 'courserequests') {
                   4949:             $symb=&escape(&symbclean($symb));
                   4950:         }
1.122     albertel 4951:     }
1.188     www      4952:     if (!$namespace) { 
1.620     albertel 4953:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      4954:           return ''; 
                   4955:        } 
                   4956:     }
1.620     albertel 4957:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4958:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   4959:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 4960:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   4961: 
1.12      www      4962:     my %returnhash=();
1.800     albertel 4963:     foreach my $line (split(/\&/,$answer)) {
                   4964: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 4965:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 4966:     }
1.75      www      4967:     my $version;
                   4968:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 4969:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   4970:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 4971:        }
1.75      www      4972:     }
1.13      www      4973:     return %returnhash;
1.34      www      4974: }
                   4975: 
                   4976: # ---------------------------------------------------------- Course Description
1.1118    foxr     4977: #
                   4978: #  
1.34      www      4979: 
                   4980: sub coursedescription {
1.731     albertel 4981:     my ($courseid,$args)=@_;
1.34      www      4982:     $courseid=~s/^\///;
1.49      www      4983:     $courseid=~s/\_/\//g;
1.34      www      4984:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 4985:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 4986:     my $normalid=$cdomain.'_'.$cnum;
                   4987:     # need to always cache even if we get errors otherwise we keep 
                   4988:     # trying and trying and trying to get the course description.
                   4989:     my %envhash=();
                   4990:     my %returnhash=();
1.731     albertel 4991:     
                   4992:     my $expiretime=600;
                   4993:     if ($env{'request.course.id'} eq $normalid) {
                   4994: 	$expiretime=120;
                   4995:     }
                   4996: 
                   4997:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   4998:     if (!$args->{'freshen_cache'}
                   4999: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   5000: 	foreach my $key (keys(%env)) {
                   5001: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   5002: 	    my ($setting) = $1;
                   5003: 	    $returnhash{$setting} = $env{$key};
                   5004: 	}
                   5005: 	return %returnhash;
                   5006:     }
                   5007: 
1.1118    foxr     5008:     # get the data again
                   5009: 
1.731     albertel 5010:     if (!$args->{'one_time'}) {
                   5011: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   5012:     }
1.811     albertel 5013: 
1.34      www      5014:     if ($chome ne 'no_host') {
1.302     albertel 5015:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 5016:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     5017: 	   my $username = $env{'user.name'}; # Defult username
                   5018: 	   if(defined $args->{'user'}) {
                   5019: 	       $username = $args->{'user'};
                   5020: 	   }
1.129     albertel 5021:            $returnhash{'home'}= $chome;
                   5022: 	   $returnhash{'domain'} = $cdomain;
                   5023: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  5024:            if (!defined($returnhash{'type'})) {
                   5025:                $returnhash{'type'} = 'Course';
                   5026:            }
1.130     albertel 5027:            while (my ($name,$value) = each %returnhash) {
1.53      www      5028:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 5029:            }
1.270     www      5030:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     5031:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     5032: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      5033:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   5034:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   5035:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      5036:        }
                   5037:     }
1.731     albertel 5038:     if (!$args->{'one_time'}) {
1.949     raeburn  5039: 	&appenv(\%envhash);
1.731     albertel 5040:     }
1.302     albertel 5041:     return %returnhash;
1.461     www      5042: }
                   5043: 
1.1080    raeburn  5044: sub update_released_required {
                   5045:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   5046:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   5047:         $cid = $env{'request.course.id'};
                   5048:         $cdom = $env{'course.'.$cid.'.domain'};
                   5049:         $cnum = $env{'course.'.$cid.'.num'};
                   5050:         $chome = $env{'course.'.$cid.'.home'};
                   5051:     }
                   5052:     if ($needsrelease) {
                   5053:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   5054:         my $needsupdate;
                   5055:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   5056:             $needsupdate = 1;
                   5057:         } else {
                   5058:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   5059:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   5060:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   5061:                 $needsupdate = 1;
                   5062:             }
                   5063:         }
                   5064:         if ($needsupdate) {
                   5065:             my %needshash = (
                   5066:                              'internal.releaserequired' => $needsrelease,
                   5067:                             );
                   5068:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   5069:             if ($putresult eq 'ok') {
                   5070:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   5071:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   5072:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   5073:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   5074:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   5075:                 }
                   5076:             }
                   5077:         }
                   5078:     }
                   5079:     return;
                   5080: }
                   5081: 
1.461     www      5082: # -------------------------------------------------See if a user is privileged
                   5083: 
                   5084: sub privileged {
1.1172.2.23  raeburn  5085:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5086:     my $now = time;
1.1172.2.23  raeburn  5087:     my $roles;
                   5088:     if (ref($possroles) eq 'ARRAY') {
                   5089:         $roles = $possroles;
                   5090:     } else {
                   5091:         $roles = ['dc','su'];
                   5092:     }
                   5093:     if (ref($possdomains) eq 'ARRAY') {
                   5094:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   5095:         foreach my $dom (@{$possdomains}) {
                   5096:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   5097:                 (ref($privileged{$dom}) eq 'HASH')) {
                   5098:                 foreach my $role (@{$roles}) {
                   5099:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5100:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5101:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5102:                             return 1 unless (($end && $end < $now) ||
                   5103:                                              ($start && $start > $now));
                   5104:                         }
                   5105:                     }
                   5106:                 }
                   5107:             }
                   5108:         }
                   5109:     } else {
                   5110:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   5111:         my $now = time;
1.1170    droeschl 5112: 
1.1172.2.23  raeburn  5113:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
1.1170    droeschl 5114:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  5115:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   5116:                 return 1 unless ($tend && $tend < $now)
                   5117:                         or ($tstart && $tstart > $now);
1.1170    droeschl 5118:             }
1.1172.2.23  raeburn  5119:         }
                   5120:     }
1.461     www      5121:     return 0;
1.9       www      5122: }
1.1       albertel 5123: 
1.1172.2.23  raeburn  5124: sub privileged_by_domain {
                   5125:     my ($domains,$roles) = @_;
                   5126:     my %privileged = ();
                   5127:     my $cachetime = 60*60*24;
                   5128:     my $now = time;
                   5129:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   5130:         return %privileged;
                   5131:     }
                   5132:     foreach my $dom (@{$domains}) {
                   5133:         next if (ref($privileged{$dom}) eq 'HASH');
                   5134:         my $needroles;
                   5135:         foreach my $role (@{$roles}) {
                   5136:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   5137:             if (defined($cached)) {
                   5138:                 if (ref($result) eq 'HASH') {
                   5139:                     $privileged{$dom}{$role} = $result;
                   5140:                 }
                   5141:             } else {
                   5142:                 $needroles = 1;
                   5143:             }
                   5144:         }
                   5145:         if ($needroles) {
                   5146:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   5147:             $privileged{$dom} = {};
                   5148:             foreach my $server (keys(%dompersonnel)) {
                   5149:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   5150:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   5151:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   5152:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   5153:                         next if ($end && $end < $now);
                   5154:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   5155:                             $dompersonnel{$server}{$item};
                   5156:                     }
                   5157:                 }
                   5158:             }
                   5159:             if (ref($privileged{$dom}) eq 'HASH') {
                   5160:                 foreach my $role (@{$roles}) {
                   5161:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5162:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   5163:                     } else {
                   5164:                         my %hash = ();
                   5165:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   5166:                     }
                   5167:                 }
                   5168:             }
                   5169:         }
                   5170:     }
                   5171:     return %privileged;
                   5172: }
                   5173: 
1.103     harris41 5174: # -------------------------------------------------------- Get user privileges
1.11      www      5175: 
                   5176: sub rolesinit {
1.1169    droeschl 5177:     my ($domain, $username) = @_;
                   5178:     my %userroles = ('user.login.time' => time);
                   5179:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   5180: 
                   5181:     # firstaccess and timerinterval are related to timed maps/resources. 
                   5182:     # also, blocking can be triggered by an activating timer
                   5183:     # it's saved in the user's %env.
                   5184:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   5185:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   5186:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   5187:         %timerintchk, %timerintenv);
                   5188: 
1.1162    raeburn  5189:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 5190:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  5191:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   5192:     }
1.1169    droeschl 5193: 
1.1162    raeburn  5194:     foreach my $key (keys(%timerinterval)) {
                   5195:         my ($cid,$rest) = split(/\0/,$key);
                   5196:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   5197:     }
1.1169    droeschl 5198: 
1.11      www      5199:     my %allroles=();
1.1162    raeburn  5200:     my %allgroups=();
1.11      www      5201: 
1.1169    droeschl 5202:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
                   5203:         my $role = $rolesdump{$area};
                   5204:         $area =~ s/\_\w\w$//;
                   5205: 
                   5206:         my ($trole, $tend, $tstart, $group_privs);
                   5207: 
                   5208:         if ($role =~ /^cr/) {
                   5209:         # Custom role, defined by a user 
                   5210:         # e.g., user.role.cr/msu/smith/mynewrole
                   5211:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5212:                 $trole = $1;
                   5213:                 ($tend, $tstart) = split('_', $2);
                   5214:             } else {
                   5215:                 $trole = $role;
                   5216:             }
                   5217:         } elsif ($role =~ m|^gr/|) {
                   5218:         # Role of member in a group, defined within a course/community
                   5219:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5220:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5221:             next if $tstart eq '-1';
                   5222:             ($trole, $group_privs) = split(/\//, $trole);
                   5223:             $group_privs = &unescape($group_privs);
                   5224:         } else {
                   5225:         # Just a normal role, defined in roles.tab
                   5226:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5227:         }
                   5228: 
                   5229:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5230:                  $username);
                   5231:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5232: 
                   5233:         # role expired or not available yet?
                   5234:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5235:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5236: 
                   5237:         next if $area eq '' or $trole eq '';
                   5238: 
                   5239:         my $spec = "$trole.$area";
                   5240:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5241: 
                   5242:         if ($trole =~ /^cr\//) {
                   5243:         # Custom role, defined by a user
                   5244:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5245:         } elsif ($trole eq 'gr') {
                   5246:         # Role of a member in a group, defined within a course/community
                   5247:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5248:             next;
                   5249:         } else {
                   5250:         # Normal role, defined in roles.tab
                   5251:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5252:         }
                   5253: 
                   5254:         my $cid = $tdomain.'_'.$trest;
                   5255:         unless ($firstaccchk{$cid}) {
                   5256:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5257:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5258:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5259:                         $coursetimerstarts{$cid}{$item}; 
                   5260:                 }
                   5261:             }
                   5262:             $firstaccchk{$cid} = 1;
                   5263:         }
                   5264:         unless ($timerintchk{$cid}) {
                   5265:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5266:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5267:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5268:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5269:                 }
1.12      www      5270:             }
1.1169    droeschl 5271:             $timerintchk{$cid} = 1;
1.191     harris41 5272:         }
1.11      www      5273:     }
1.1169    droeschl 5274: 
                   5275:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
                   5276:         \%allroles, \%allgroups);
                   5277:     $env{'user.adv'} = $userroles{'user.adv'};
                   5278: 
1.1162    raeburn  5279:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5280: }
                   5281: 
1.567     raeburn  5282: sub set_arearole {
1.1172.2.19  raeburn  5283:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   5284:     unless ($nolog) {
1.567     raeburn  5285: # log the associated role with the area
1.1172.2.19  raeburn  5286:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   5287:     }
1.743     albertel 5288:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5289: }
                   5290: 
                   5291: sub custom_roleprivs {
                   5292:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5293:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   5294:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 5295:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5296:         my ($rdummy,$roledef)=
                   5297:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5298:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5299:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5300:             if (defined($syspriv)) {
1.1043    raeburn  5301:                 if ($trest =~ /^$match_community$/) {
                   5302:                     $syspriv =~ s/bre\&S//; 
                   5303:                 }
1.567     raeburn  5304:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5305:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5306:             }
                   5307:             if ($tdomain ne '') {
                   5308:                 if (defined($dompriv)) {
                   5309:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5310:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5311:                 }
                   5312:                 if (($trest ne '') && (defined($coursepriv))) {
                   5313:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5314:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5315:                 }
                   5316:             }
                   5317:         }
                   5318:     }
                   5319: }
                   5320: 
1.678     raeburn  5321: sub group_roleprivs {
                   5322:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   5323:     my $access = 1;
                   5324:     my $now = time;
                   5325:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   5326:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   5327:     if ($access) {
1.811     albertel 5328:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  5329:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   5330:     }
                   5331: }
1.567     raeburn  5332: 
                   5333: sub standard_roleprivs {
                   5334:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   5335:     if (defined($pr{$trole.':s'})) {
                   5336:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   5337:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   5338:     }
                   5339:     if ($tdomain ne '') {
                   5340:         if (defined($pr{$trole.':d'})) {
                   5341:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5342:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5343:         }
                   5344:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   5345:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   5346:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   5347:         }
                   5348:     }
                   5349: }
                   5350: 
                   5351: sub set_userprivs {
1.1064    raeburn  5352:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  5353:     my $author=0;
                   5354:     my $adv=0;
1.678     raeburn  5355:     my %grouproles = ();
                   5356:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  5357:         my @groupkeys; 
1.1000    raeburn  5358:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  5359:             push(@groupkeys,$role);
                   5360:         }
                   5361:         if (ref($groups_roles) eq 'HASH') {
                   5362:             foreach my $key (keys(%{$groups_roles})) {
                   5363:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   5364:                     push(@groupkeys,$key);
                   5365:                 }
                   5366:             }
                   5367:         }
                   5368:         if (@groupkeys > 0) {
                   5369:             foreach my $role (@groupkeys) {
                   5370:                 my ($trole,$area,$sec,$extendedarea);
                   5371:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   5372:                     $trole = $1;
                   5373:                     $area = $2;
                   5374:                     $sec = $3;
                   5375:                     $extendedarea = $area.$sec;
                   5376:                     if (exists($$allgroups{$area})) {
                   5377:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   5378:                             my $spec = $trole.'.'.$extendedarea;
                   5379:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  5380:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  5381:                         }
1.678     raeburn  5382:                     }
                   5383:                 }
                   5384:             }
                   5385:         }
                   5386:     }
1.800     albertel 5387:     foreach my $group (keys(%grouproles)) {
                   5388:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  5389:     }
1.800     albertel 5390:     foreach my $role (keys(%{$allroles})) {
                   5391:         my %thesepriv;
1.941     raeburn  5392:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 5393:         foreach my $item (split(/:/,$$allroles{$role})) {
                   5394:             if ($item ne '') {
                   5395:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  5396:                 if ($restrictions eq '') {
                   5397:                     $thesepriv{$privilege}='F';
                   5398:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   5399:                     $thesepriv{$privilege}.=$restrictions;
                   5400:                 }
                   5401:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   5402:             }
                   5403:         }
                   5404:         my $thesestr='';
1.1104    raeburn  5405:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 5406: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   5407: 	}
                   5408:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  5409:     }
                   5410:     return ($author,$adv);
                   5411: }
                   5412: 
1.994     raeburn  5413: sub role_status {
1.1104    raeburn  5414:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  5415:     my @pwhere = ();
                   5416:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   5417:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   5418:         unless (!defined($$role) || $$role eq '') {
                   5419:             $$where=join('.',@pwhere);
                   5420:             $$trolecode=$$role.'.'.$$where;
                   5421:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   5422:             $$tstatus='is';
1.1104    raeburn  5423:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  5424:                 $$tstatus='future';
1.1034    raeburn  5425:                 if ($$tstart<$now) {
                   5426:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  5427:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  5428:                             my (%allroles,%allgroups,$group_privs,
                   5429:                                 %groups_roles,@rolecodes);
1.1002    raeburn  5430:                             my %userroles = (
                   5431:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   5432:                             );
1.1064    raeburn  5433:                             @rolecodes = ('cm'); 
1.1002    raeburn  5434:                             my $spec=$$role.'.'.$$where;
                   5435:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   5436:                             if ($$role =~ /^cr\//) {
                   5437:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  5438:                                 push(@rolecodes,'cr');
1.1002    raeburn  5439:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  5440:                                 push(@rolecodes,$$role);
1.1002    raeburn  5441:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   5442:                                                     $env{'user.name'});
1.1064    raeburn  5443:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  5444:                                 (undef,my $group_privs) = split(/\//,$trole);
                   5445:                                 $group_privs = &unescape($group_privs);
                   5446:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  5447:                                 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  5448:                                 &get_groups_roles($tdomain,$trest,
                   5449:                                                   \%course_roles,\@rolecodes,
                   5450:                                                   \%groups_roles);
1.1002    raeburn  5451:                             } else {
1.1064    raeburn  5452:                                 push(@rolecodes,$$role);
1.1002    raeburn  5453:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   5454:                             }
1.1064    raeburn  5455:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   5456:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  5457:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   5458:                         }
                   5459:                     }
1.1034    raeburn  5460:                     $$tstatus = 'is';
1.1002    raeburn  5461:                 }
1.994     raeburn  5462:             }
                   5463:             if ($$tend) {
1.1104    raeburn  5464:                 if ($$tend<$update) {
1.994     raeburn  5465:                     $$tstatus='expired';
                   5466:                 } elsif ($$tend<$now) {
                   5467:                     $$tstatus='will_not';
                   5468:                 }
                   5469:             }
                   5470:         }
                   5471:     }
                   5472: }
                   5473: 
1.1104    raeburn  5474: sub get_groups_roles {
                   5475:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   5476:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   5477:                   (ref($rolecodes) eq 'ARRAY') && 
                   5478:                   (ref($groups_roles) eq 'HASH')); 
                   5479:     if (keys(%{$cdom_courseroles}) > 0) {
                   5480:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   5481:         if ($cdom ne '' && $cnum ne '') {
                   5482:             foreach my $key (keys(%{$cdom_courseroles})) {
                   5483:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   5484:                     my $crsrole = $1;
                   5485:                     my $crssec = $2;
                   5486:                     if ($crsrole =~ /^cr/) {
                   5487:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   5488:                             push(@{$rolecodes},'cr');
                   5489:                         }
                   5490:                     } else {
                   5491:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   5492:                             push(@{$rolecodes},$crsrole);
                   5493:                         }
                   5494:                     }
                   5495:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   5496:                     if ($crssec ne '') {
                   5497:                         $rolekey .= "/$crssec";
                   5498:                     }
                   5499:                     $rolekey .= './';
                   5500:                     $groups_roles->{$rolekey} = $rolecodes;
                   5501:                 }
                   5502:             }
                   5503:         }
                   5504:     }
                   5505:     return;
                   5506: }
                   5507: 
                   5508: sub delete_env_groupprivs {
                   5509:     my ($where,$courseroles,$possroles) = @_;
                   5510:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   5511:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   5512:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   5513:         %{$courseroles->{$udom}} =
                   5514:             &get_my_roles('','','userroles',['active'],
                   5515:                           $possroles,[$udom],1);
                   5516:     }
                   5517:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   5518:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   5519:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   5520:             my $area = '/'.$cdom.'/'.$cnum;
                   5521:             my $privkey = "user.priv.$crsrole.$area";
                   5522:             if ($crssec ne '') {
                   5523:                 $privkey .= '/'.$crssec;
                   5524:             }
                   5525:             $privkey .= ".$area/$group";
                   5526:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   5527:         }
                   5528:     }
                   5529:     return;
                   5530: }
                   5531: 
1.994     raeburn  5532: sub check_adhoc_privs {
1.1104    raeburn  5533:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  5534:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.9  raeburn  5535:     my $setprivs;
1.994     raeburn  5536:     if ($env{$cckey}) {
                   5537:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  5538:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  5539:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  5540:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9  raeburn  5541:             $setprivs = 1;
1.994     raeburn  5542:         }
                   5543:     } else {
1.1088    raeburn  5544:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9  raeburn  5545:         $setprivs = 1;
1.994     raeburn  5546:     }
1.1172.2.9  raeburn  5547:     return $setprivs;
1.994     raeburn  5548: }
                   5549: 
                   5550: sub set_adhoc_privileges {
                   5551: # role can be cc or ca
1.1088    raeburn  5552:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  5553:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   5554:     my $spec = $role.'.'.$area;
                   5555:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  5556:                                   $env{'user.name'},1);
1.994     raeburn  5557:     my %ccrole = ();
                   5558:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   5559:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   5560:     &appenv(\%userroles,[$role,'cm']);
                   5561:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  5562:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   5563:         &appenv( {'request.role'        => $spec,
                   5564:                   'request.role.domain' => $dcdom,
                   5565:                   'request.course.sec'  => ''
                   5566:                  }
                   5567:                );
                   5568:         my $tadv=0;
                   5569:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   5570:         &appenv({'request.role.adv'    => $tadv});
                   5571:     }
1.994     raeburn  5572: }
                   5573: 
1.12      www      5574: # --------------------------------------------------------------- get interface
                   5575: 
                   5576: sub get {
1.131     albertel 5577:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5578:    my $items='';
1.800     albertel 5579:    foreach my $item (@$storearr) {
                   5580:        $items.=&escape($item).'&';
1.191     harris41 5581:    }
1.12      www      5582:    $items=~s/\&$//;
1.620     albertel 5583:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5584:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 5585:    my $uhome=&homeserver($uname,$udomain);
                   5586: 
1.133     albertel 5587:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5588:    my @pairs=split(/\&/,$rep);
1.273     albertel 5589:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   5590:      return @pairs;
                   5591:    }
1.15      www      5592:    my %returnhash=();
1.42      www      5593:    my $i=0;
1.800     albertel 5594:    foreach my $item (@$storearr) {
                   5595:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5596:       $i++;
1.191     harris41 5597:    }
1.15      www      5598:    return %returnhash;
1.27      www      5599: }
                   5600: 
                   5601: # --------------------------------------------------------------- del interface
                   5602: 
                   5603: sub del {
1.133     albertel 5604:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      5605:    my $items='';
1.800     albertel 5606:    foreach my $item (@$storearr) {
                   5607:        $items.=&escape($item).'&';
1.191     harris41 5608:    }
1.984     neumanie 5609: 
1.27      www      5610:    $items=~s/\&$//;
1.620     albertel 5611:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5612:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5613:    my $uhome=&homeserver($uname,$udomain);
                   5614:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5615: }
                   5616: 
                   5617: # -------------------------------------------------------------- dump interface
                   5618: 
1.1172.2.22  raeburn  5619: sub unserialize {
                   5620:     my ($rep, $escapedkeys) = @_;
                   5621: 
                   5622:     return {} if $rep =~ /^error/;
                   5623: 
                   5624:     my %returnhash=();
                   5625:     foreach my $item (split(/\&/,$rep)) {
                   5626:         my ($key, $value) = split(/=/, $item, 2);
                   5627:         $key = unescape($key) unless $escapedkeys;
                   5628:         next if $key =~ /^error: 2 /;
                   5629:         $returnhash{$key} = &thaw_unescape($value);
                   5630:     }
                   5631:     return \%returnhash;
                   5632: }
                   5633: 
                   5634: # see Lond::dump_with_regexp
                   5635: # if $escapedkeys hash keys won't get unescaped.
1.15      www      5636: sub dump {
1.1172.2.22  raeburn  5637:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 5638:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5639:     if (!$uname) { $uname=$env{'user.name'}; }
                   5640:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 5641: 
1.1172.2.22  raeburn  5642:     my $reply;
                   5643:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   5644:         # user is hosted on this machine
                   5645:         $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  5646:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  5647:         return %{&unserialize($reply, $escapedkeys)};
                   5648:     }
1.755     albertel 5649:     if ($regexp) {
                   5650: 	$regexp=&escape($regexp);
                   5651:     } else {
                   5652: 	$regexp='.';
                   5653:     }
1.1166    raeburn  5654:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 5655:     my @pairs=split(/\&/,$rep);
                   5656:     my %returnhash=();
1.1098    foxr     5657:     if (!($rep =~ /^error/ )) {
                   5658: 	foreach my $item (@pairs) {
                   5659: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  5660:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     5661: 	    next if ($key =~ /^error: 2 /);
                   5662: 	    $returnhash{$key}=&thaw_unescape($value);
                   5663: 	}
1.755     albertel 5664:     }
                   5665:     return %returnhash;
1.407     www      5666: }
                   5667: 
1.1098    foxr     5668: 
1.717     albertel 5669: # --------------------------------------------------------- dumpstore interface
                   5670: 
                   5671: sub dumpstore {
                   5672:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  5673:    # same as dump but keys must be escaped. They may contain colon separated
                   5674:    # lists of values that may themself contain colons (e.g. symbs).
                   5675:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 5676: }
                   5677: 
1.407     www      5678: # -------------------------------------------------------------- keys interface
                   5679: 
                   5680: sub getkeys {
                   5681:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 5682:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5683:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      5684:    my $uhome=&homeserver($uname,$udomain);
                   5685:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   5686:    my @keyarray=();
1.800     albertel 5687:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  5688:       next if ($key =~ /^error: 2 /);
1.800     albertel 5689:       push(@keyarray,&unescape($key));
1.407     www      5690:    }
                   5691:    return @keyarray;
1.318     matthew  5692: }
                   5693: 
1.319     matthew  5694: # --------------------------------------------------------------- currentdump
                   5695: sub currentdump {
1.328     matthew  5696:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 5697:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   5698:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   5699:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  5700:    my $uhome = &homeserver($sname,$sdom);
                   5701:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  5702:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  5703:    #
1.318     matthew  5704:    my %returnhash=();
1.319     matthew  5705:    #
                   5706:    if ($rep eq "unknown_cmd") { 
                   5707:        # an old lond will not know currentdump
                   5708:        # Do a dump and make it look like a currentdump
1.822     albertel 5709:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  5710:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   5711:        my %hash = @tmp;
                   5712:        @tmp=();
1.424     matthew  5713:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  5714:    } else {
                   5715:        my @pairs=split(/\&/,$rep);
1.800     albertel 5716:        foreach my $pair (@pairs) {
                   5717:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  5718:            my ($symb,$param) = split(/:/,$key);
                   5719:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 5720:                                                         &thaw_unescape($value);
1.319     matthew  5721:        }
1.191     harris41 5722:    }
1.12      www      5723:    return %returnhash;
1.424     matthew  5724: }
                   5725: 
                   5726: sub convert_dump_to_currentdump{
                   5727:     my %hash = %{shift()};
                   5728:     my %returnhash;
                   5729:     # Code ripped from lond, essentially.  The only difference
                   5730:     # here is the unescaping done by lonnet::dump().  Conceivably
                   5731:     # we might run in to problems with parameter names =~ /^v\./
                   5732:     while (my ($key,$value) = each(%hash)) {
                   5733:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 5734: 	$symb  = &unescape($symb);
                   5735: 	$param = &unescape($param);
1.424     matthew  5736:         next if ($v eq 'version' || $symb eq 'keys');
                   5737:         next if (exists($returnhash{$symb}) &&
                   5738:                  exists($returnhash{$symb}->{$param}) &&
                   5739:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   5740:         $returnhash{$symb}->{$param}=$value;
                   5741:         $returnhash{$symb}->{'v.'.$param}=$v;
                   5742:     }
                   5743:     #
                   5744:     # Remove all of the keys in the hashes which keep track of
                   5745:     # the version of the parameter.
                   5746:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   5747:         # use a foreach because we are going to delete from the hash.
                   5748:         foreach my $key (keys(%$param_hash)) {
                   5749:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   5750:         }
                   5751:     }
                   5752:     return \%returnhash;
1.12      www      5753: }
                   5754: 
1.627     albertel 5755: # ------------------------------------------------------ critical inc interface
                   5756: 
                   5757: sub cinc {
                   5758:     return &inc(@_,'critical');
                   5759: }
                   5760: 
1.449     matthew  5761: # --------------------------------------------------------------- inc interface
                   5762: 
                   5763: sub inc {
1.627     albertel 5764:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 5765:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5766:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  5767:     my $uhome=&homeserver($uname,$udomain);
                   5768:     my $items='';
                   5769:     if (! ref($store)) {
                   5770:         # got a single value, so use that instead
                   5771:         $items = &escape($store).'=&';
                   5772:     } elsif (ref($store) eq 'SCALAR') {
                   5773:         $items = &escape($$store).'=&';        
                   5774:     } elsif (ref($store) eq 'ARRAY') {
                   5775:         $items = join('=&',map {&escape($_);} @{$store});
                   5776:     } elsif (ref($store) eq 'HASH') {
                   5777:         while (my($key,$value) = each(%{$store})) {
                   5778:             $items.= &escape($key).'='.&escape($value).'&';
                   5779:         }
                   5780:     }
                   5781:     $items=~s/\&$//;
1.627     albertel 5782:     if ($critical) {
                   5783: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5784:     } else {
                   5785: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5786:     }
1.449     matthew  5787: }
                   5788: 
1.12      www      5789: # --------------------------------------------------------------- put interface
                   5790: 
                   5791: sub put {
1.134     albertel 5792:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5793:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5794:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5795:    my $uhome=&homeserver($uname,$udomain);
1.12      www      5796:    my $items='';
1.800     albertel 5797:    foreach my $item (keys(%$storehash)) {
                   5798:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5799:    }
1.12      www      5800:    $items=~s/\&$//;
1.134     albertel 5801:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      5802: }
                   5803: 
1.631     albertel 5804: # ------------------------------------------------------------ newput interface
                   5805: 
                   5806: sub newput {
                   5807:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   5808:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5809:    if (!$uname) { $uname=$env{'user.name'}; }
                   5810:    my $uhome=&homeserver($uname,$udomain);
                   5811:    my $items='';
                   5812:    foreach my $key (keys(%$storehash)) {
                   5813:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   5814:    }
                   5815:    $items=~s/\&$//;
                   5816:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   5817: }
                   5818: 
                   5819: # ---------------------------------------------------------  putstore interface
                   5820: 
1.524     raeburn  5821: sub putstore {
1.715     albertel 5822:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 5823:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5824:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  5825:    my $uhome=&homeserver($uname,$udomain);
                   5826:    my $items='';
1.715     albertel 5827:    foreach my $key (keys(%$storehash)) {
                   5828:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  5829:    }
1.715     albertel 5830:    $items=~s/\&$//;
1.716     albertel 5831:    my $esc_symb=&escape($symb);
                   5832:    my $esc_v=&escape($version);
1.715     albertel 5833:    my $reply =
1.716     albertel 5834:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 5835: 	      $uhome);
                   5836:    if ($reply eq 'unknown_cmd') {
1.716     albertel 5837:        # gfall back to way things use to be done
1.715     albertel 5838:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   5839: 			    $uname);
1.524     raeburn  5840:    }
1.715     albertel 5841:    return $reply;
                   5842: }
                   5843: 
                   5844: sub old_putstore {
1.716     albertel 5845:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   5846:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5847:     if (!$uname) { $uname=$env{'user.name'}; }
                   5848:     my $uhome=&homeserver($uname,$udomain);
                   5849:     my %newstorehash;
1.800     albertel 5850:     foreach my $item (keys(%$storehash)) {
                   5851: 	my $key = $version.':'.&escape($symb).':'.$item;
                   5852: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 5853:     }
                   5854:     my $items='';
                   5855:     my %allitems = ();
1.800     albertel 5856:     foreach my $item (keys(%newstorehash)) {
                   5857: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 5858: 	    my $key = $1.':keys:'.$2;
                   5859: 	    $allitems{$key} .= $3.':';
                   5860: 	}
1.800     albertel 5861: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 5862:     }
1.800     albertel 5863:     foreach my $item (keys(%allitems)) {
                   5864: 	$allitems{$item} =~ s/\:$//;
                   5865: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 5866:     }
                   5867:     $items=~s/\&$//;
                   5868:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  5869: }
                   5870: 
1.47      www      5871: # ------------------------------------------------------ critical put interface
                   5872: 
                   5873: sub cput {
1.134     albertel 5874:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5875:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5876:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5877:    my $uhome=&homeserver($uname,$udomain);
1.47      www      5878:    my $items='';
1.800     albertel 5879:    foreach my $item (keys(%$storehash)) {
                   5880:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5881:    }
1.47      www      5882:    $items=~s/\&$//;
1.134     albertel 5883:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5884: }
                   5885: 
                   5886: # -------------------------------------------------------------- eget interface
                   5887: 
                   5888: sub eget {
1.133     albertel 5889:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5890:    my $items='';
1.800     albertel 5891:    foreach my $item (@$storearr) {
                   5892:        $items.=&escape($item).'&';
1.191     harris41 5893:    }
1.12      www      5894:    $items=~s/\&$//;
1.620     albertel 5895:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5896:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5897:    my $uhome=&homeserver($uname,$udomain);
                   5898:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5899:    my @pairs=split(/\&/,$rep);
                   5900:    my %returnhash=();
1.42      www      5901:    my $i=0;
1.800     albertel 5902:    foreach my $item (@$storearr) {
                   5903:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5904:       $i++;
1.191     harris41 5905:    }
1.12      www      5906:    return %returnhash;
                   5907: }
                   5908: 
1.667     albertel 5909: # ------------------------------------------------------------ tmpput interface
                   5910: sub tmpput {
1.802     raeburn  5911:     my ($storehash,$server,$context)=@_;
1.667     albertel 5912:     my $items='';
1.800     albertel 5913:     foreach my $item (keys(%$storehash)) {
                   5914: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 5915:     }
                   5916:     $items=~s/\&$//;
1.802     raeburn  5917:     if (defined($context)) {
                   5918:         $items .= ':'.&escape($context);
                   5919:     }
1.667     albertel 5920:     return &reply("tmpput:$items",$server);
                   5921: }
                   5922: 
                   5923: # ------------------------------------------------------------ tmpget interface
                   5924: sub tmpget {
1.688     albertel 5925:     my ($token,$server)=@_;
                   5926:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5927:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 5928:     my %returnhash;
                   5929:     foreach my $item (split(/\&/,$rep)) {
                   5930: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  5931:         next if ($key =~ /^error: 2 /);
1.667     albertel 5932: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   5933:     }
                   5934:     return %returnhash;
                   5935: }
                   5936: 
1.1113    raeburn  5937: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 5938: sub tmpdel {
                   5939:     my ($token,$server)=@_;
                   5940:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5941:     return &reply("tmpdel:$token",$server);
                   5942: }
                   5943: 
1.1172.2.13  raeburn  5944: # ------------------------------------------------------------ get_timebased_id
                   5945: 
                   5946: sub get_timebased_id {
                   5947:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   5948:         $maxtries) = @_;
                   5949:     my ($newid,$error,$dellock);
                   5950:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   5951:         return ('','ok','invalid call to get suffix');
                   5952:     }
                   5953: 
                   5954: # set defaults for any optional args for which values were not supplied
                   5955:     if ($who eq '') {
                   5956:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   5957:     }
                   5958:     if (!$locktries) {
                   5959:         $locktries = 3;
                   5960:     }
                   5961:     if (!$maxtries) {
                   5962:         $maxtries = 10;
                   5963:     }
                   5964: 
                   5965:     if (($cdom eq '') || ($cnum eq '')) {
                   5966:         if ($env{'request.course.id'}) {
                   5967:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5968:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5969:         }
                   5970:         if (($cdom eq '') || ($cnum eq '')) {
                   5971:             return ('','ok','call to get suffix not in course context');
                   5972:         }
                   5973:     }
                   5974: 
                   5975: # construct locking item
                   5976:     my $lockhash = {
                   5977:                       $prefix."\0".'locked_'.$keyid => $who,
                   5978:                    };
                   5979:     my $tries = 0;
                   5980: 
                   5981: # attempt to get lock on nohist_$namespace file
                   5982:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   5983:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   5984:         $tries ++;
                   5985:         sleep 1;
                   5986:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   5987:     }
                   5988: 
                   5989: # attempt to get unique identifier, based on current timestamp
                   5990:     if ($gotlock eq 'ok') {
                   5991:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   5992:         my $id = time;
                   5993:         $newid = $id;
                   5994:         my $idtries = 0;
                   5995:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   5996:             if ($idtype eq 'concat') {
                   5997:                 $newid = $id.$idtries;
                   5998:             } else {
                   5999:                 $newid ++;
                   6000:             }
                   6001:             $idtries ++;
                   6002:         }
                   6003:         if (!exists($inuse{$prefix."\0".$newid})) {
                   6004:             my %new_item =  (
                   6005:                               $prefix."\0".$newid => $who,
                   6006:                             );
                   6007:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   6008:                                                  $cdom,$cnum);
                   6009:             if ($putresult ne 'ok') {
                   6010:                 undef($newid);
                   6011:                 $error = 'error saving new item: '.$putresult;
                   6012:             }
                   6013:         } else {
                   6014:              $error = ('error: no unique suffix available for the new item ');
                   6015:         }
                   6016: #  remove lock
                   6017:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   6018:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   6019:     } else {
                   6020:         $error = "error: could not obtain lockfile\n";
                   6021:         $dellock = 'ok';
                   6022:     }
                   6023:     return ($newid,$dellock,$error);
                   6024: }
                   6025: 
1.765     albertel 6026: # -------------------------------------------------- portfolio access checking
                   6027: 
                   6028: sub portfolio_access {
1.766     albertel 6029:     my ($requrl) = @_;
1.765     albertel 6030:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   6031:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  6032:     if ($result) {
                   6033:         my %setters;
                   6034:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6035:             my ($startblock,$endblock) =
                   6036:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   6037:             if ($startblock && $endblock) {
                   6038:                 return 'B';
                   6039:             }
                   6040:         } else {
                   6041:             my ($startblock,$endblock) =
                   6042:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   6043:             if ($startblock && $endblock) {
                   6044:                 return 'B';
                   6045:             }
                   6046:         }
                   6047:     }
1.765     albertel 6048:     if ($result eq 'ok') {
1.766     albertel 6049:        return 'F';
1.765     albertel 6050:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 6051:        return 'A';
1.765     albertel 6052:     }
1.766     albertel 6053:     return '';
1.765     albertel 6054: }
                   6055: 
                   6056: sub get_portfolio_access {
1.767     albertel 6057:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   6058: 
                   6059:     if (!ref($access_hash)) {
                   6060: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   6061: 	my %access_controls = &get_access_controls($current_perms,$group,
                   6062: 						   $file_name);
                   6063: 	$access_hash = $access_controls{$file_name};
                   6064:     }
                   6065: 
1.765     albertel 6066:     my ($public,$guest,@domains,@users,@courses,@groups);
                   6067:     my $now = time;
                   6068:     if (ref($access_hash) eq 'HASH') {
                   6069:         foreach my $key (keys(%{$access_hash})) {
                   6070:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6071:             if ($start > $now) {
                   6072:                 next;
                   6073:             }
                   6074:             if ($end && $end<$now) {
                   6075:                 next;
                   6076:             }
                   6077:             if ($scope eq 'public') {
                   6078:                 $public = $key;
                   6079:                 last;
                   6080:             } elsif ($scope eq 'guest') {
                   6081:                 $guest = $key;
                   6082:             } elsif ($scope eq 'domains') {
                   6083:                 push(@domains,$key);
                   6084:             } elsif ($scope eq 'users') {
                   6085:                 push(@users,$key);
                   6086:             } elsif ($scope eq 'course') {
                   6087:                 push(@courses,$key);
                   6088:             } elsif ($scope eq 'group') {
                   6089:                 push(@groups,$key);
                   6090:             }
                   6091:         }
                   6092:         if ($public) {
                   6093:             return 'ok';
                   6094:         }
                   6095:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6096:             if ($guest) {
                   6097:                 return $guest;
                   6098:             }
                   6099:         } else {
                   6100:             if (@domains > 0) {
                   6101:                 foreach my $domkey (@domains) {
                   6102:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   6103:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   6104:                             return 'ok';
                   6105:                         }
                   6106:                     }
                   6107:                 }
                   6108:             }
                   6109:             if (@users > 0) {
                   6110:                 foreach my $userkey (@users) {
1.865     raeburn  6111:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   6112:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   6113:                             if (ref($item) eq 'HASH') {
                   6114:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   6115:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   6116:                                     return 'ok';
                   6117:                                 }
                   6118:                             }
                   6119:                         }
                   6120:                     } 
1.765     albertel 6121:                 }
                   6122:             }
                   6123:             my %roleshash;
                   6124:             my @courses_and_groups = @courses;
                   6125:             push(@courses_and_groups,@groups); 
                   6126:             if (@courses_and_groups > 0) {
                   6127:                 my (%allgroups,%allroles); 
                   6128:                 my ($start,$end,$role,$sec,$group);
                   6129:                 foreach my $envkey (%env) {
1.1060    raeburn  6130:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6131:                         my $cid = $2.'_'.$3; 
                   6132:                         if ($1 eq 'gr') {
                   6133:                             $group = $4;
                   6134:                             $allgroups{$cid}{$group} = $env{$envkey};
                   6135:                         } else {
                   6136:                             if ($4 eq '') {
                   6137:                                 $sec = 'none';
                   6138:                             } else {
                   6139:                                 $sec = $4;
                   6140:                             }
                   6141:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6142:                         }
1.811     albertel 6143:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6144:                         my $cid = $2.'_'.$3;
                   6145:                         if ($4 eq '') {
                   6146:                             $sec = 'none';
                   6147:                         } else {
                   6148:                             $sec = $4;
                   6149:                         }
                   6150:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6151:                     }
                   6152:                 }
                   6153:                 if (keys(%allroles) == 0) {
                   6154:                     return;
                   6155:                 }
                   6156:                 foreach my $key (@courses_and_groups) {
                   6157:                     my %content = %{$$access_hash{$key}};
                   6158:                     my $cnum = $content{'number'};
                   6159:                     my $cdom = $content{'domain'};
                   6160:                     my $cid = $cdom.'_'.$cnum;
                   6161:                     if (!exists($allroles{$cid})) {
                   6162:                         next;
                   6163:                     }    
                   6164:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   6165:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   6166:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   6167:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   6168:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   6169:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   6170:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   6171:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   6172:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   6173:                                         if (grep/^all$/,@sections) {
                   6174:                                             return 'ok';
                   6175:                                         } else {
                   6176:                                             if (grep/^$sec$/,@sections) {
                   6177:                                                 return 'ok';
                   6178:                                             }
                   6179:                                         }
                   6180:                                     }
                   6181:                                 }
                   6182:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   6183:                                     if (grep/^none$/,@groups) {
                   6184:                                         return 'ok';
                   6185:                                     }
                   6186:                                 } else {
                   6187:                                     if (grep/^all$/,@groups) {
                   6188:                                         return 'ok';
                   6189:                                     } 
                   6190:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   6191:                                         if (grep/^$group$/,@groups) {
                   6192:                                             return 'ok';
                   6193:                                         }
                   6194:                                     }
                   6195:                                 } 
                   6196:                             }
                   6197:                         }
                   6198:                     }
                   6199:                 }
                   6200:             }
                   6201:             if ($guest) {
                   6202:                 return $guest;
                   6203:             }
                   6204:         }
                   6205:     }
                   6206:     return;
                   6207: }
                   6208: 
                   6209: sub course_group_datechecker {
                   6210:     my ($dates,$now,$status) = @_;
                   6211:     my ($start,$end) = split(/\./,$dates);
                   6212:     if (!$start && !$end) {
                   6213:         return 'ok';
                   6214:     }
                   6215:     if (grep/^active$/,@{$status}) {
                   6216:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   6217:             return 'ok';
                   6218:         }
                   6219:     }
                   6220:     if (grep/^previous$/,@{$status}) {
                   6221:         if ($end > $now ) {
                   6222:             return 'ok';
                   6223:         }
                   6224:     }
                   6225:     if (grep/^future$/,@{$status}) {
                   6226:         if ($start > $now) {
                   6227:             return 'ok';
                   6228:         }
                   6229:     }
                   6230:     return; 
                   6231: }
                   6232: 
                   6233: sub parse_portfolio_url {
                   6234:     my ($url) = @_;
                   6235: 
                   6236:     my ($type,$udom,$unum,$group,$file_name);
                   6237:     
1.823     albertel 6238:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 6239: 	$type = 1;
                   6240:         $udom = $1;
                   6241:         $unum = $2;
                   6242:         $file_name = $3;
1.823     albertel 6243:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 6244: 	$type = 2;
                   6245:         $udom = $1;
                   6246:         $unum = $2;
                   6247:         $group = $3;
                   6248:         $file_name = $3.'/'.$4;
                   6249:     }
                   6250:     if (wantarray) {
                   6251: 	return ($type,$udom,$unum,$file_name,$group);
                   6252:     }
                   6253:     return $type;
                   6254: }
                   6255: 
                   6256: sub is_portfolio_url {
                   6257:     my ($url) = @_;
                   6258:     return scalar(&parse_portfolio_url($url));
                   6259: }
                   6260: 
1.798     raeburn  6261: sub is_portfolio_file {
                   6262:     my ($file) = @_;
1.820     raeburn  6263:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  6264:         return 1;
                   6265:     }
                   6266:     return;
                   6267: }
                   6268: 
1.976     raeburn  6269: sub usertools_access {
1.1084    raeburn  6270:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  6271:     my ($access,%tools);
                   6272:     if ($context eq '') {
                   6273:         $context = 'tools';
                   6274:     }
                   6275:     if ($context eq 'requestcourses') {
                   6276:         %tools = (
                   6277:                       official   => 1,
                   6278:                       unofficial => 1,
1.1006    raeburn  6279:                       community  => 1,
1.985     raeburn  6280:                  );
1.1172.2.9  raeburn  6281:     } elsif ($context eq 'requestauthor') {
                   6282:         %tools = (
                   6283:                       requestauthor => 1,
                   6284:                  );
1.985     raeburn  6285:     } else {
                   6286:         %tools = (
                   6287:                       aboutme   => 1,
                   6288:                       blog      => 1,
1.1172.2.6  raeburn  6289:                       webdav    => 1,
1.985     raeburn  6290:                       portfolio => 1,
                   6291:                  );
                   6292:     }
1.976     raeburn  6293:     return if (!defined($tools{$tool}));
                   6294: 
1.1172.2.35! raeburn  6295:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  6296:         $udom = $env{'user.domain'};
                   6297:         $uname = $env{'user.name'};
                   6298:     }
                   6299: 
1.978     raeburn  6300:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6301:         if ($action ne 'reload') {
1.985     raeburn  6302:             if ($context eq 'requestcourses') {
                   6303:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  6304:             } elsif ($context eq 'requestauthor') {
                   6305:                 return $env{'environment.canrequest.author'};
1.985     raeburn  6306:             } else {
                   6307:                 return $env{'environment.availabletools.'.$tool};
                   6308:             }
                   6309:         }
1.976     raeburn  6310:     }
                   6311: 
1.1172.2.9  raeburn  6312:     my ($toolstatus,$inststatus,$envkey);
                   6313:     if ($context eq 'requestauthor') {
                   6314:         $envkey = $context;
                   6315:     } else {
                   6316:         $envkey = $context.'.'.$tool;
                   6317:     }
1.976     raeburn  6318: 
1.985     raeburn  6319:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   6320:          ($action ne 'reload')) {
1.1172.2.9  raeburn  6321:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  6322:         $inststatus = $env{'environment.inststatus'};
                   6323:     } else {
1.1084    raeburn  6324:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  6325:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  6326:             $inststatus = $userenvref->{'inststatus'};
                   6327:         } else {
1.1172.2.9  raeburn  6328:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   6329:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  6330:             $inststatus = $userenv{'inststatus'};
                   6331:         }
1.976     raeburn  6332:     }
                   6333: 
                   6334:     if ($toolstatus ne '') {
                   6335:         if ($toolstatus) {
                   6336:             $access = 1;
                   6337:         } else {
                   6338:             $access = 0;
                   6339:         }
                   6340:         return $access;
                   6341:     }
                   6342: 
1.1084    raeburn  6343:     my ($is_adv,%domdef);
                   6344:     if (ref($is_advref) eq 'HASH') {
                   6345:         $is_adv = $is_advref->{'is_adv'};
                   6346:     } else {
                   6347:         $is_adv = &is_advanced_user($udom,$uname);
                   6348:     }
                   6349:     if (ref($domdefref) eq 'HASH') {
                   6350:         %domdef = %{$domdefref};
                   6351:     } else {
                   6352:         %domdef = &get_domain_defaults($udom);
                   6353:     }
1.976     raeburn  6354:     if (ref($domdef{$tool}) eq 'HASH') {
                   6355:         if ($is_adv) {
                   6356:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   6357:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   6358:                     $access = 1;
                   6359:                 } else {
                   6360:                     $access = 0;
                   6361:                 }
                   6362:                 return $access;
                   6363:             }
                   6364:         }
                   6365:         if ($inststatus ne '') {
                   6366:             my ($hasaccess,$hasnoaccess);
                   6367:             foreach my $affiliation (split(/:/,$inststatus)) {
                   6368:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   6369:                     if ($domdef{$tool}{$affiliation}) {
                   6370:                         $hasaccess = 1;
                   6371:                     } else {
                   6372:                         $hasnoaccess = 1;
                   6373:                     }
                   6374:                 }
                   6375:             }
                   6376:             if ($hasaccess || $hasnoaccess) {
                   6377:                 if ($hasaccess) {
                   6378:                     $access = 1;
                   6379:                 } elsif ($hasnoaccess) {
                   6380:                     $access = 0; 
                   6381:                 }
                   6382:                 return $access;
                   6383:             }
                   6384:         } else {
                   6385:             if ($domdef{$tool}{'default'} ne '') {
                   6386:                 if ($domdef{$tool}{'default'}) {
                   6387:                     $access = 1;
                   6388:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   6389:                     $access = 0;
                   6390:                 }
                   6391:                 return $access;
                   6392:             }
                   6393:         }
                   6394:     } else {
1.1172.2.6  raeburn  6395:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  6396:             $access = 1;
                   6397:         } else {
                   6398:             $access = 0;
                   6399:         }
1.976     raeburn  6400:         return $access;
                   6401:     }
                   6402: }
                   6403: 
1.1050    raeburn  6404: sub is_course_owner {
                   6405:     my ($cdom,$cnum,$udom,$uname) = @_;
                   6406:     if (($udom eq '') || ($uname eq '')) {
                   6407:         $udom = $env{'user.domain'};
                   6408:         $uname = $env{'user.name'};
                   6409:     }
                   6410:     unless (($udom eq '') || ($uname eq '')) {
                   6411:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   6412:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   6413:                 return 1;
                   6414:             } else {
                   6415:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   6416:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   6417:                     return 1;
                   6418:                 }
                   6419:             }
                   6420:         }
                   6421:     }
                   6422:     return;
                   6423: }
                   6424: 
1.976     raeburn  6425: sub is_advanced_user {
                   6426:     my ($udom,$uname) = @_;
1.1085    raeburn  6427:     if ($udom ne '' && $uname ne '') {
                   6428:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  6429:             if (wantarray) {
                   6430:                 return ($env{'user.adv'},$env{'user.author'});
                   6431:             } else {
                   6432:                 return $env{'user.adv'};
                   6433:             }
1.1085    raeburn  6434:         }
                   6435:     }
1.976     raeburn  6436:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   6437:     my %allroles;
1.1128    raeburn  6438:     my ($is_adv,$is_author);
1.976     raeburn  6439:     foreach my $role (keys(%roleshash)) {
                   6440:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   6441:         my $area = '/'.$tdomain.'/'.$trest;
                   6442:         if ($sec ne '') {
                   6443:             $area .= '/'.$sec;
                   6444:         }
                   6445:         if (($area ne '') && ($trole ne '')) {
                   6446:             my $spec=$trole.'.'.$area;
                   6447:             if ($trole =~ /^cr\//) {
                   6448:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6449:             } elsif ($trole ne 'gr') {
                   6450:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6451:             }
1.1128    raeburn  6452:             if ($trole eq 'au') {
                   6453:                 $is_author = 1;
                   6454:             }
1.976     raeburn  6455:         }
                   6456:     }
                   6457:     foreach my $role (keys(%allroles)) {
                   6458:         last if ($is_adv);
                   6459:         foreach my $item (split(/:/,$allroles{$role})) {
                   6460:             if ($item ne '') {
                   6461:                 my ($privilege,$restrictions)=split(/&/,$item);
                   6462:                 if ($privilege eq 'adv') {
                   6463:                     $is_adv = 1;
                   6464:                     last;
                   6465:                 }
                   6466:             }
                   6467:         }
                   6468:     }
1.1128    raeburn  6469:     if (wantarray) {
                   6470:         return ($is_adv,$is_author);
                   6471:     }
1.976     raeburn  6472:     return $is_adv;
                   6473: }
1.798     raeburn  6474: 
1.1035    raeburn  6475: sub check_can_request {
1.1036    raeburn  6476:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  6477:     my $canreq = 0;
                   6478:     my ($types,$typename) = &Apache::loncommon::course_types();
                   6479:     my @options = ('approval','validate','autolimit');
                   6480:     my $optregex = join('|',@options);
                   6481:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   6482:         foreach my $type (@{$types}) {
                   6483:             if (&usertools_access($env{'user.name'},
                   6484:                                   $env{'user.domain'},
                   6485:                                   $type,undef,'requestcourses')) {
                   6486:                 $canreq ++;
1.1036    raeburn  6487:                 if (ref($request_domains) eq 'HASH') {
                   6488:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   6489:                 }
1.1035    raeburn  6490:                 if ($dom eq $env{'user.domain'}) {
                   6491:                     $can_request->{$type} = 1;
                   6492:                 }
                   6493:             }
                   6494:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   6495:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   6496:                 if (@curr > 0) {
1.1036    raeburn  6497:                     foreach my $item (@curr) {
                   6498:                         if (ref($request_domains) eq 'HASH') {
                   6499:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   6500:                             if ($otherdom ne '') {
                   6501:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   6502:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   6503:                                         push(@{$request_domains->{$type}},$otherdom);
                   6504:                                     }
                   6505:                                 } else {
                   6506:                                     push(@{$request_domains->{$type}},$otherdom);
                   6507:                                 }
                   6508:                             }
                   6509:                         }
                   6510:                     }
                   6511:                     unless($dom eq $env{'user.domain'}) {
                   6512:                         $canreq ++;
1.1035    raeburn  6513:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   6514:                             $can_request->{$type} = 1;
                   6515:                         }
                   6516:                     }
                   6517:                 }
                   6518:             }
                   6519:         }
                   6520:     }
                   6521:     return $canreq;
                   6522: }
                   6523: 
1.341     www      6524: # ---------------------------------------------- Custom access rule evaluation
                   6525: 
                   6526: sub customaccess {
                   6527:     my ($priv,$uri)=@_;
1.807     albertel 6528:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      6529:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 6530:     $udom = &LONCAPA::clean_domain($udom);
                   6531:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      6532:     my $access=0;
1.800     albertel 6533:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 6534: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   6535: 	if ($type eq 'user') {
                   6536: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 6537: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 6538: 		if ($tdom) {
                   6539: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   6540: 		}
1.896     albertel 6541: 		if ($tuname) {
                   6542: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 6543: 		}
                   6544: 		$access=($effect eq 'allow');
                   6545: 		last;
                   6546: 	    }
                   6547: 	} else {
                   6548: 	    if ($role) {
                   6549: 		if ($role ne $urole) { next; }
                   6550: 	    }
                   6551: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   6552: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   6553: 		if ($tdom) {
                   6554: 		    if ($tdom ne $udom) { next; }
                   6555: 		}
                   6556: 		if ($tcrs) {
                   6557: 		    if ($tcrs ne $ucrs) { next; }
                   6558: 		}
                   6559: 		if ($tsec) {
                   6560: 		    if ($tsec ne $usec) { next; }
                   6561: 		}
                   6562: 		$access=($effect eq 'allow');
                   6563: 		last;
                   6564: 	    }
                   6565: 	    if ($realm eq '' && $role eq '') {
                   6566: 		$access=($effect eq 'allow');
                   6567: 	    }
1.402     bowersj2 6568: 	}
1.341     www      6569:     }
                   6570:     return $access;
                   6571: }
                   6572: 
1.103     harris41 6573: # ------------------------------------------------- Check for a user privilege
1.12      www      6574: 
                   6575: sub allowed {
1.810     raeburn  6576:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 6577:     my $ver_orguri=$uri;
1.439     www      6578:     $uri=&deversion($uri);
1.152     www      6579:     my $orguri=$uri;
1.52      www      6580:     $uri=&declutter($uri);
1.809     raeburn  6581: 
1.810     raeburn  6582:     if ($priv eq 'evb') {
                   6583: # Evade communication block restrictions for specified role in a course
                   6584:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   6585:             return $1;
                   6586:         } else {
                   6587:             return;
                   6588:         }
                   6589:     }
                   6590: 
1.620     albertel 6591:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      6592: # Free bre access to adm and meta resources
1.775     albertel 6593:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 6594: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   6595: 	&& ($priv eq 'bre')) {
1.14      www      6596: 	return 'F';
1.159     www      6597:     }
                   6598: 
1.545     banghart 6599: # Free bre access to user's own portfolio contents
1.714     raeburn  6600:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  6601:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  6602: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  6603:         my %setters;
                   6604:         my ($startblock,$endblock) = 
                   6605:             &Apache::loncommon::blockcheck(\%setters,'port');
                   6606:         if ($startblock && $endblock) {
                   6607:             return 'B';
                   6608:         } else {
                   6609:             return 'F';
                   6610:         }
1.545     banghart 6611:     }
                   6612: 
1.762     raeburn  6613: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  6614:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   6615:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   6616:         if (exists($env{'request.course.id'})) {
                   6617:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6618:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6619:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   6620:                 my $courseprivid=$env{'request.course.id'};
                   6621:                 $courseprivid=~s/\_/\//;
                   6622:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   6623:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   6624:                     return $1; 
1.762     raeburn  6625:                 } else {
                   6626:                     if ($env{'request.course.sec'}) {
                   6627:                         $courseprivid.='/'.$env{'request.course.sec'};
                   6628:                     }
                   6629:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   6630:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   6631:                         return $2;
                   6632:                     }
1.714     raeburn  6633:                 }
                   6634:             }
                   6635:         }
                   6636:     }
                   6637: 
1.159     www      6638: # Free bre to public access
                   6639: 
                   6640:     if ($priv eq 'bre') {
1.238     www      6641:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 6642: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      6643:            return 'F'; 
                   6644:         }
1.238     www      6645:         if ($copyright eq 'priv') {
                   6646:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6647: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      6648: 		return '';
                   6649:             }
                   6650:         }
                   6651:         if ($copyright eq 'domain') {
                   6652:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6653: 	    unless (($env{'user.domain'} eq $1) ||
                   6654:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      6655: 		return '';
                   6656:             }
1.262     matthew  6657:         }
1.620     albertel 6658:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  6659:             # Library role, so allow browsing of resources in this domain.
                   6660:             return 'F';
1.238     www      6661:         }
1.341     www      6662:         if ($copyright eq 'custom') {
                   6663: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   6664:         }
1.14      www      6665:     }
1.264     matthew  6666:     # Domain coordinator is trying to create a course
1.620     albertel 6667:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  6668:         # uri is the requested domain in this case.
                   6669:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  6670:         # a role of dc for the domain in question.
1.620     albertel 6671:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  6672:     }
1.29      www      6673: 
1.52      www      6674:     my $thisallowed='';
                   6675:     my $statecond=0;
                   6676:     my $courseprivid='';
                   6677: 
1.1039    raeburn  6678:     my $ownaccess;
1.1043    raeburn  6679:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  6680:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   6681:         if ($uri eq '') {
                   6682:             $ownaccess = 1;
                   6683:         } else {
                   6684:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   6685:                 my $udom = $env{'user.domain'};
                   6686:                 my $uname = $env{'user.name'};
                   6687:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   6688:                     $ownaccess = 1;
1.1040    raeburn  6689:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  6690:                     unless ($uri =~ m{\.\./}) {
                   6691:                         $ownaccess = 1;
                   6692:                     }
                   6693:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   6694:                     my $now = time;
                   6695:                     if ($uri =~ m{^([^/]+)/?$}) {
                   6696:                         my $adom = $1;
                   6697:                         foreach my $key (keys(%env)) {
1.1042    raeburn  6698:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  6699:                                 my ($start,$end) = split('.',$env{$key});
                   6700:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6701:                                     $ownaccess = 1;
                   6702:                                     last;
                   6703:                                 }
                   6704:                             }
                   6705:                         }
                   6706:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   6707:                         my $adom = $1;
                   6708:                         my $aname = $2;
1.1042    raeburn  6709:                         foreach my $role ('ca','aa') { 
                   6710:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   6711:                                 my ($start,$end) =
                   6712:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   6713:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6714:                                     $ownaccess = 1;
                   6715:                                     last;
                   6716:                                 }
1.1039    raeburn  6717:                             }
                   6718:                         }
                   6719:                     }
                   6720:                 }
                   6721:             }
                   6722:         }
                   6723:     }
                   6724: 
1.52      www      6725: # Course
                   6726: 
1.620     albertel 6727:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6728:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6729:             $thisallowed.=$1;
                   6730:         }
1.52      www      6731:     }
1.29      www      6732: 
1.52      www      6733: # Domain
                   6734: 
1.620     albertel 6735:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 6736:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6737:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6738:             $thisallowed.=$1;
                   6739:         }
1.12      www      6740:     }
1.52      www      6741: 
1.1141    raeburn  6742: # User who is not author or co-author might still be able to edit
                   6743: # resource of an author in the domain (e.g., if Domain Coordinator).
                   6744:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   6745:         (&allowed('mdc',$env{'request.course.id'}))) {
                   6746:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   6747:             $thisallowed.=$1;
                   6748:         }
                   6749:     }
                   6750: 
1.52      www      6751: # Course: uri itself is a course
1.66      www      6752:     my $courseuri=$uri;
                   6753:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      6754:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      6755: 
1.620     albertel 6756:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 6757:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6758:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6759:             $thisallowed.=$1;
                   6760:         }
1.12      www      6761:     }
1.29      www      6762: 
1.665     albertel 6763: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 6764: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 6765:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 6766: 	$thisallowed='';
1.671     raeburn  6767:         my ($match)=&is_on_map($uri);
                   6768:         if ($match) {
                   6769:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   6770:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6771:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6772:                 if (@blockers > 0) {
                   6773:                     $thisallowed = 'B';
                   6774:                 } else {
                   6775:                     $thisallowed.=$1;
                   6776:                 }
1.671     raeburn  6777:             }
                   6778:         } else {
1.705     albertel 6779:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  6780:             if ($refuri) {
                   6781:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  6782:                     $thisallowed='F';
1.671     raeburn  6783:                 } else {
                   6784:                     $refuri=&declutter($refuri);
                   6785:                     my ($match) = &is_on_map($refuri);
                   6786:                     if ($match) {
1.1162    raeburn  6787:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6788:                         if (@blockers > 0) {
                   6789:                             $thisallowed = 'B';
                   6790:                         } else {
                   6791:                             $thisallowed='F';
                   6792:                         }
1.671     raeburn  6793:                     }
1.669     raeburn  6794:                 }
1.671     raeburn  6795:             }
                   6796:         }
1.314     www      6797:     }
1.492     albertel 6798: 
1.766     albertel 6799:     if ($priv eq 'bre'
                   6800: 	&& $thisallowed ne 'F' 
                   6801: 	&& $thisallowed ne '2'
                   6802: 	&& &is_portfolio_url($uri)) {
                   6803: 	$thisallowed = &portfolio_access($uri);
                   6804:     }
                   6805:     
1.52      www      6806: # Full access at system, domain or course-wide level? Exit.
1.29      www      6807:     if ($thisallowed=~/F/) {
                   6808: 	return 'F';
                   6809:     }
                   6810: 
1.52      www      6811: # If this is generating or modifying users, exit with special codes
1.29      www      6812: 
1.643     www      6813:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   6814: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 6815: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      6816: # no author name given, so this just checks on the general right to make a co-author in this domain
                   6817: 	    unless ($auname) { return $thisallowed; }
                   6818: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 6819: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   6820: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   6821: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   6822: 	}
1.52      www      6823: 	return $thisallowed;
                   6824:     }
                   6825: #
1.103     harris41 6826: # Gathered so far: system, domain and course wide privileges
1.52      www      6827: #
                   6828: # Course: See if uri or referer is an individual resource that is part of 
                   6829: # the course
                   6830: 
1.620     albertel 6831:     if ($env{'request.course.id'}) {
1.232     www      6832: 
1.620     albertel 6833:        $courseprivid=$env{'request.course.id'};
                   6834:        if ($env{'request.course.sec'}) {
                   6835:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      6836:        }
                   6837:        $courseprivid=~s/\_/\//;
                   6838:        my $checkreferer=1;
1.232     www      6839:        my ($match,$cond)=&is_on_map($uri);
                   6840:        if ($match) {
                   6841:            $statecond=$cond;
1.620     albertel 6842:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6843:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6844:                my $value = $1;
                   6845:                if ($priv eq 'bre') {
                   6846:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6847:                    if (@blockers > 0) {
                   6848:                        $thisallowed = 'B';
                   6849:                    } else {
                   6850:                        $thisallowed.=$value;
                   6851:                    }
                   6852:                } else {
                   6853:                    $thisallowed.=$value;
                   6854:                }
1.52      www      6855:                $checkreferer=0;
                   6856:            }
1.29      www      6857:        }
1.83      www      6858:        
1.148     www      6859:        if ($checkreferer) {
1.620     albertel 6860: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      6861:             unless ($refuri) {
1.800     albertel 6862:                 foreach my $key (keys(%env)) {
                   6863: 		    if ($key=~/^httpref\..*\*/) {
                   6864: 			my $pattern=$key;
1.156     www      6865:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      6866:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   6867:                         $pattern=~s/\//\\\//g;
1.152     www      6868:                         if ($orguri=~/$pattern/) {
1.800     albertel 6869: 			    $refuri=$env{$key};
1.148     www      6870:                         }
                   6871:                     }
1.191     harris41 6872:                 }
1.148     www      6873:             }
1.232     www      6874: 
1.148     www      6875:          if ($refuri) { 
1.152     www      6876: 	  $refuri=&declutter($refuri);
1.232     www      6877:           my ($match,$cond)=&is_on_map($refuri);
                   6878:             if ($match) {
                   6879:               my $refstatecond=$cond;
1.620     albertel 6880:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6881:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6882:                   my $value = $1;
                   6883:                   if ($priv eq 'bre') {
                   6884:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6885:                       if (@blockers > 0) {
                   6886:                           $thisallowed = 'B';
                   6887:                       } else {
                   6888:                           $thisallowed.=$value;
                   6889:                       }
                   6890:                   } else {
                   6891:                       $thisallowed.=$value;
                   6892:                   }
1.53      www      6893:                   $uri=$refuri;
                   6894:                   $statecond=$refstatecond;
1.52      www      6895:               }
                   6896:           }
1.148     www      6897:         }
1.29      www      6898:        }
1.52      www      6899:    }
1.29      www      6900: 
1.52      www      6901: #
1.103     harris41 6902: # Gathered now: all privileges that could apply, and condition number
1.52      www      6903: # 
                   6904: #
                   6905: # Full or no access?
                   6906: #
1.29      www      6907: 
1.52      www      6908:     if ($thisallowed=~/F/) {
                   6909: 	return 'F';
                   6910:     }
1.29      www      6911: 
1.52      www      6912:     unless ($thisallowed) {
                   6913:         return '';
                   6914:     }
1.29      www      6915: 
1.52      www      6916: # Restrictions exist, deal with them
                   6917: #
                   6918: #   C:according to course preferences
                   6919: #   R:according to resource settings
                   6920: #   L:unless locked
                   6921: #   X:according to user session state
                   6922: #
                   6923: 
                   6924: # Possibly locked functionality, check all courses
1.54      www      6925: # Locks might take effect only after 10 minutes cache expiration for other
                   6926: # courses, and 2 minutes for current course
1.52      www      6927: 
                   6928:     my $envkey;
                   6929:     if ($thisallowed=~/L/) {
1.1000    raeburn  6930:         foreach $envkey (keys(%env)) {
1.54      www      6931:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   6932:                my $courseid=$2;
                   6933:                my $roleid=$1.'.'.$2;
1.92      www      6934:                $courseid=~s/^\///;
1.54      www      6935:                my $expiretime=600;
1.620     albertel 6936:                if ($env{'request.role'} eq $roleid) {
1.54      www      6937: 		  $expiretime=120;
                   6938:                }
                   6939: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   6940:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 6941:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 6942: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      6943:                }
1.620     albertel 6944:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6945:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   6946: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   6947:                        &log($env{'user.domain'},$env{'user.name'},
                   6948:                             $env{'user.home'},
1.57      www      6949:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      6950:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6951:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6952: 		       return '';
                   6953:                    }
                   6954:                }
1.620     albertel 6955:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6956:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   6957: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   6958:                        &log($env{'user.domain'},$env{'user.name'},
                   6959:                             $env{'user.home'},
1.57      www      6960:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      6961:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6962:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6963: 		       return '';
                   6964:                    }
                   6965:                }
                   6966: 	   }
1.29      www      6967:        }
1.52      www      6968:     }
                   6969:    
                   6970: #
                   6971: # Rest of the restrictions depend on selected course
                   6972: #
                   6973: 
1.620     albertel 6974:     unless ($env{'request.course.id'}) {
1.766     albertel 6975: 	if ($thisallowed eq 'A') {
                   6976: 	    return 'A';
1.814     raeburn  6977:         } elsif ($thisallowed eq 'B') {
                   6978:             return 'B';
1.766     albertel 6979: 	} else {
                   6980: 	    return '1';
                   6981: 	}
1.52      www      6982:     }
1.29      www      6983: 
1.52      www      6984: #
                   6985: # Now user is definitely in a course
                   6986: #
1.53      www      6987: 
                   6988: 
                   6989: # Course preferences
                   6990: 
                   6991:    if ($thisallowed=~/C/) {
1.620     albertel 6992:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   6993:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   6994:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 6995: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  6996: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6997: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6998: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   6999: 			$env{'request.course.id'});
                   7000: 	   }
1.237     www      7001:            return '';
                   7002:        }
                   7003: 
1.620     albertel 7004:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 7005: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  7006: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7007: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   7008: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   7009: 			$env{'request.course.id'});
                   7010: 	   }
1.54      www      7011:            return '';
                   7012:        }
1.53      www      7013:    }
                   7014: 
                   7015: # Resource preferences
                   7016: 
                   7017:    if ($thisallowed=~/R/) {
1.620     albertel 7018:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 7019:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  7020: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7021: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7022: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   7023: 	   }
                   7024: 	   return '';
1.54      www      7025:        }
1.53      www      7026:    }
1.30      www      7027: 
1.246     www      7028: # Restricted by state or randomout?
1.30      www      7029: 
1.52      www      7030:    if ($thisallowed=~/X/) {
1.620     albertel 7031:       if ($env{'acc.randomout'}) {
1.579     albertel 7032: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 7033:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      7034:             return ''; 
                   7035:          }
1.247     www      7036:       }
                   7037:       if (&condval($statecond)) {
1.52      www      7038: 	 return '2';
                   7039:       } else {
                   7040:          return '';
                   7041:       }
                   7042:    }
1.30      www      7043: 
1.766     albertel 7044:     if ($thisallowed eq 'A') {
                   7045: 	return 'A';
1.814     raeburn  7046:     } elsif ($thisallowed eq 'B') {
                   7047:         return 'B';
1.766     albertel 7048:     }
1.52      www      7049:    return 'F';
1.232     www      7050: }
1.1162    raeburn  7051: 
1.1172.2.13  raeburn  7052: # ------------------------------------------- Check construction space access
                   7053: 
                   7054: sub constructaccess {
                   7055:     my ($url,$setpriv)=@_;
                   7056: 
                   7057: # We do not allow editing of previous versions of files
                   7058:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   7059: 
                   7060: # Get username and domain from URL
                   7061:     my ($ownername,$ownerdomain,$ownerhome);
                   7062: 
                   7063:     ($ownerdomain,$ownername) =
                   7064:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
                   7065: 
                   7066: # The URL does not really point to any authorspace, forget it
                   7067:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   7068: 
                   7069: # Now we need to see if the user has access to the authorspace of
                   7070: # $ownername at $ownerdomain
                   7071: 
                   7072:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   7073: # Real author for this?
                   7074:        $ownerhome = $env{'user.home'};
                   7075:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   7076:           return ($ownername,$ownerdomain,$ownerhome);
                   7077:        }
                   7078:     } else {
                   7079: # Co-author for this?
                   7080:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   7081:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   7082:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   7083:             return ($ownername,$ownerdomain,$ownerhome);
                   7084:         }
                   7085:     }
                   7086: 
                   7087: # We don't have any access right now. If we are not possibly going to do anything about this,
                   7088: # we might as well leave
                   7089:    unless ($setpriv) { return ''; }
                   7090: 
                   7091: # Backdoor access?
                   7092:     my $allowed=&allowed('eco',$ownerdomain);
                   7093: # Nope
                   7094:     unless ($allowed) { return ''; }
                   7095: # Looks like we may have access, but could be locked by the owner of the construction space
                   7096:     if ($allowed eq 'U') {
                   7097:         my %blocked=&get('environment',['domcoord.author'],
                   7098:                          $ownerdomain,$ownername);
                   7099: # Is blocked by owner
                   7100:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   7101:     }
                   7102:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   7103: # Grant temporary access
                   7104:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  7105:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  7106:         if (!$update) { $update = $then; }
                   7107:         my $refresh=$env{'user.refresh.time'};
                   7108:         if (!$refresh) { $refresh = $update; }
                   7109:         my $now = time;
                   7110:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   7111:                            $now,'ca','constructaccess');
                   7112:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   7113:         return($ownername,$ownerdomain,$ownerhome);
                   7114:     }
                   7115: # No business here
                   7116:     return '';
                   7117: }
                   7118: 
1.1162    raeburn  7119: sub get_comm_blocks {
                   7120:     my ($cdom,$cnum) = @_;
                   7121:     if ($cdom eq '' || $cnum eq '') {
                   7122:         return unless ($env{'request.course.id'});
                   7123:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7124:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7125:     }
                   7126:     my %commblocks;
                   7127:     my $hashid=$cdom.'_'.$cnum;
                   7128:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   7129:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   7130:         %commblocks = %{$blocksref};
                   7131:     } else {
                   7132:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   7133:         my $cachetime = 600;
                   7134:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   7135:     }
                   7136:     return %commblocks;
                   7137: }
                   7138: 
                   7139: sub has_comm_blocking {
                   7140:     my ($priv,$symb,$uri,$blocks) = @_;
                   7141:     return unless ($env{'request.course.id'});
                   7142:     return unless ($priv eq 'bre');
                   7143:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   7144:     my %commblocks;
                   7145:     if (ref($blocks) eq 'HASH') {
                   7146:         %commblocks = %{$blocks};
                   7147:     } else {
                   7148:         %commblocks = &get_comm_blocks();
                   7149:     }
                   7150:     return unless (keys(%commblocks) > 0);
                   7151:     if (!$symb) { $symb=&symbread($uri,1); }
                   7152:     my ($map,$resid,undef)=&decode_symb($symb);
                   7153:     my %tocheck = (
                   7154:                     maps      => $map,
                   7155:                     resources => $symb,
                   7156:                   );
                   7157:     my @blockers;
                   7158:     my $now = time;
1.1163    raeburn  7159:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1162    raeburn  7160:     foreach my $block (keys(%commblocks)) {
                   7161:         if ($block =~ /^(\d+)____(\d+)$/) {
                   7162:             my ($start,$end) = ($1,$2);
                   7163:             if ($start <= $now && $end >= $now) {
                   7164:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7165:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7166:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   7167:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
                   7168:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   7169:                                     push(@blockers,$block);
                   7170:                                 }
                   7171:                             }
                   7172:                         }
                   7173:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   7174:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
                   7175:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
                   7176:                                     push(@blockers,$block);
                   7177:                                 }
                   7178:                             }
                   7179:                         }
                   7180:                     }
                   7181:                 }
                   7182:             }
                   7183:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   7184:             my $item = $1;
1.1163    raeburn  7185:             my @to_test;
1.1162    raeburn  7186:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7187:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7188:                     my $check_interval;
                   7189:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
                   7190:                         my @interval;
                   7191:                         my $type = 'map';
                   7192:                         if ($item eq 'course') {
                   7193:                             $type = 'course';
                   7194:                             @interval=&EXT("resource.0.interval");
                   7195:                         } else {
                   7196:                             if ($item =~ /___\d+___/) {
                   7197:                                 $type = 'resource';
                   7198:                                 @interval=&EXT("resource.0.interval",$item);
1.1163    raeburn  7199:                                 if (ref($navmap)) {                        
                   7200:                                     my $res = $navmap->getBySymb($item); 
                   7201:                                     push(@to_test,$res);
                   7202:                                 }
1.1162    raeburn  7203:                             } else {
                   7204:                                 my $mapsymb = &symbread($item,1);
                   7205:                                 if ($mapsymb) {
                   7206:                                     if (ref($navmap)) {
                   7207:                                         my $mapres = $navmap->getBySymb($mapsymb);
1.1163    raeburn  7208:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
                   7209:                                         foreach my $res (@to_test) {
1.1162    raeburn  7210:                                             my $symb = $res->symb();
                   7211:                                             next if ($symb eq $mapsymb);
                   7212:                                             if ($symb ne '') {
                   7213:                                                 @interval=&EXT("resource.0.interval",$symb);
                   7214:                                                 last;
                   7215:                                             }
                   7216:                                         }
                   7217:                                     }
                   7218:                                 }
                   7219:                             }
                   7220:                         }
                   7221:                         if ($interval[0] =~ /\d+/) {
                   7222:                             my $first_access;
                   7223:                             if ($type eq 'resource') {
                   7224:                                 $first_access=&get_first_access($interval[1],$item);
                   7225:                             } elsif ($type eq 'map') {
                   7226:                                 $first_access=&get_first_access($interval[1],undef,$item);
                   7227:                             } else {
                   7228:                                 $first_access=&get_first_access($interval[1]);
                   7229:                             }
                   7230:                             if ($first_access) {
                   7231:                                 my $timesup = $first_access+$interval[0];
                   7232:                                 if ($timesup > $now) {
1.1163    raeburn  7233:                                     foreach my $res (@to_test) {
                   7234:                                         if ($res->is_problem()) {
                   7235:                                             if ($res->completable()) {
                   7236:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   7237:                                                     push(@blockers,$block);
                   7238:                                                 }
                   7239:                                                 last;
                   7240:                                             }
                   7241:                                         }
1.1162    raeburn  7242:                                     }
                   7243:                                 }
                   7244:                             }
                   7245:                         }
                   7246:                     }
                   7247:                 }
                   7248:             }
                   7249:         }
                   7250:     }
                   7251:     return @blockers;
                   7252: }
                   7253: 
                   7254: sub check_docs_block {
                   7255:     my ($docsblock,$tocheck) =@_;
                   7256:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
                   7257:         return;
                   7258:     }
                   7259:     if (ref($docsblock->{'maps'}) eq 'HASH') {
                   7260:         if ($tocheck->{'maps'}) {
                   7261:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
                   7262:                 return 1;
                   7263:             }
                   7264:         }
                   7265:     }
                   7266:     if (ref($docsblock->{'resources'}) eq 'HASH') {
                   7267:         if ($tocheck->{'resources'}) {
                   7268:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
                   7269:                 return 1;
                   7270:             }
                   7271:         }
                   7272:     }
                   7273:     return;
                   7274: }
                   7275: 
1.1133    foxr     7276: #
                   7277: #   Removes the versino from a URI and
                   7278: #   splits it in to its filename and path to the filename.
                   7279: #   Seems like File::Basename could have done this more clearly.
                   7280: #   Parameters:
                   7281: #      $uri   - input URI
                   7282: #   Returns:
                   7283: #     Two element list consisting of 
                   7284: #     $pathname  - the URI up to and excluding the trailing /
                   7285: #     $filename  - The part of the URI following the last /
                   7286: #  NOTE:
                   7287: #    Another realization of this is simply:
                   7288: #    use File::Basename;
                   7289: #    ...
                   7290: #    $uri = shift;
                   7291: #    $filename = basename($uri);
                   7292: #    $path     = dirname($uri);
                   7293: #    return ($filename, $path);
                   7294: #
                   7295: #     The implementation below is probably faster however.
                   7296: #
1.710     albertel 7297: sub split_uri_for_cond {
                   7298:     my $uri=&deversion(&declutter(shift));
                   7299:     my @uriparts=split(/\//,$uri);
                   7300:     my $filename=pop(@uriparts);
                   7301:     my $pathname=join('/',@uriparts);
                   7302:     return ($pathname,$filename);
                   7303: }
1.232     www      7304: # --------------------------------------------------- Is a resource on the map?
                   7305: 
                   7306: sub is_on_map {
1.710     albertel 7307:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 7308:     #Trying to find the conditional for the file
1.620     albertel 7309:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 7310: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      7311:     if ($match) {
1.289     bowersj2 7312: 	return (1,$1);
                   7313:     } else {
1.434     www      7314: 	return (0,0);
1.289     bowersj2 7315:     }
1.12      www      7316: }
                   7317: 
1.427     www      7318: # --------------------------------------------------------- Get symb from alias
                   7319: 
                   7320: sub get_symb_from_alias {
                   7321:     my $symb=shift;
                   7322:     my ($map,$resid,$url)=&decode_symb($symb);
                   7323: # Already is a symb
                   7324:     if ($url) { return $symb; }
                   7325: # Must be an alias
                   7326:     my $aliassymb='';
                   7327:     my %bighash;
1.620     albertel 7328:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      7329:                             &GDBM_READER(),0640)) {
                   7330:         my $rid=$bighash{'mapalias_'.$symb};
                   7331: 	if ($rid) {
                   7332: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 7333: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   7334: 				    $resid,$bighash{'src_'.$rid});
1.427     www      7335: 	}
                   7336:         untie %bighash;
                   7337:     }
                   7338:     return $aliassymb;
                   7339: }
                   7340: 
1.12      www      7341: # ----------------------------------------------------------------- Define Role
                   7342: 
                   7343: sub definerole {
                   7344:   if (allowed('mcr','/')) {
                   7345:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 7346:     foreach my $role (split(':',$sysrole)) {
                   7347: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7348:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   7349:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   7350: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7351:                return "refused:s:$crole&$cqual"; 
                   7352:             }
                   7353:         }
1.191     harris41 7354:     }
1.800     albertel 7355:     foreach my $role (split(':',$domrole)) {
                   7356: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7357:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   7358:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   7359: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      7360:                return "refused:d:$crole&$cqual"; 
                   7361:             }
                   7362:         }
1.191     harris41 7363:     }
1.800     albertel 7364:     foreach my $role (split(':',$courole)) {
                   7365: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7366:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   7367:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   7368: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7369:                return "refused:c:$crole&$cqual"; 
                   7370:             }
                   7371:         }
1.191     harris41 7372:     }
1.620     albertel 7373:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   7374:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7375: 	        "rolesdef_$rolename=".
                   7376:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 7377:     return reply($command,$env{'user.home'});
1.12      www      7378:   } else {
                   7379:     return 'refused';
                   7380:   }
1.105     harris41 7381: }
                   7382: 
                   7383: # ---------------- Make a metadata query against the network of library servers
                   7384: 
                   7385: sub metadata_query {
1.1172.2.33  raeburn  7386:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 7387:     my %rhash;
1.845     albertel 7388:     my %libserv = &all_library();
1.244     matthew  7389:     my @server_list = (defined($server_array) ? @$server_array
                   7390:                                               : keys(%libserv) );
                   7391:     for my $server (@server_list) {
1.1172.2.33  raeburn  7392:         my $domains = '';
                   7393:         if (ref($domains_hash) eq 'HASH') {
                   7394:             $domains = $domains_hash->{$server};    
                   7395:         }
1.118     harris41 7396: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  7397: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 7398: 	    $rhash{$server}=$reply;
                   7399: 	}
                   7400: 	else {
                   7401: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  7402: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 7403: 			     $server);
                   7404: 	    $rhash{$server}=$reply;
                   7405: 	}
1.112     harris41 7406:     }
1.118     harris41 7407:     return \%rhash;
1.240     www      7408: }
                   7409: 
                   7410: # ----------------------------------------- Send log queries and wait for reply
                   7411: 
                   7412: sub log_query {
                   7413:     my ($uname,$udom,$query,%filters)=@_;
                   7414:     my $uhome=&homeserver($uname,$udom);
                   7415:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 7416:     my $uhost=&hostname($uhome);
1.800     albertel 7417:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      7418:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   7419:                        $uhome);
1.479     albertel 7420:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      7421:     return get_query_reply($queryid);
                   7422: }
                   7423: 
1.818     raeburn  7424: # -------------------------- Update MySQL table for portfolio file
                   7425: 
                   7426: sub update_portfolio_table {
1.821     raeburn  7427:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  7428:     if ($group ne '') {
                   7429:         $file_name =~s /^\Q$group\E//;
                   7430:     }
1.818     raeburn  7431:     my $homeserver = &homeserver($uname,$udom);
                   7432:     my $queryid=
1.821     raeburn  7433:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   7434:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  7435:     my $reply = &get_query_reply($queryid);
                   7436:     return $reply;
                   7437: }
                   7438: 
1.899     raeburn  7439: # -------------------------- Update MySQL allusers table
                   7440: 
                   7441: sub update_allusers_table {
                   7442:     my ($uname,$udom,$names) = @_;
                   7443:     my $homeserver = &homeserver($uname,$udom);
                   7444:     my $queryid=
                   7445:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   7446:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   7447:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   7448:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   7449:                'generation='.&escape($names->{'generation'}).'%%'.
                   7450:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   7451:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  7452:     return;
1.899     raeburn  7453: }
                   7454: 
1.508     raeburn  7455: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  7456: 
                   7457: sub fetch_enrollment_query {
1.511     raeburn  7458:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  7459:     my $homeserver;
1.547     raeburn  7460:     my $maxtries = 1;
1.508     raeburn  7461:     if ($context eq 'automated') {
                   7462:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  7463:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  7464:     } else {
                   7465:         $homeserver = &homeserver($cnum,$dom);
                   7466:     }
1.838     albertel 7467:     my $host=&hostname($homeserver);
1.506     raeburn  7468:     my $cmd = '';
1.1000    raeburn  7469:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 7470:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  7471:     }
                   7472:     $cmd =~ s/%%$//;
                   7473:     $cmd = &escape($cmd);
                   7474:     my $query = 'fetchenrollment';
1.620     albertel 7475:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  7476:     unless ($queryid=~/^\Q$host\E\_/) { 
                   7477:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   7478:         return 'error: '.$queryid;
                   7479:     }
1.506     raeburn  7480:     my $reply = &get_query_reply($queryid);
1.547     raeburn  7481:     my $tries = 1;
                   7482:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7483:         $reply = &get_query_reply($queryid);
                   7484:         $tries ++;
                   7485:     }
1.526     raeburn  7486:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 7487:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  7488:     } else {
1.901     albertel 7489:         my @responses = split(/:/,$reply);
1.515     raeburn  7490:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 7491:             foreach my $line (@responses) {
                   7492:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  7493:                 $$replyref{$key} = $value;
                   7494:             }
                   7495:         } else {
1.1117    foxr     7496:             my $pathname = LONCAPA::tempdir();
1.800     albertel 7497:             foreach my $line (@responses) {
                   7498:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  7499:                 $$replyref{$key} = $value;
                   7500:                 if ($value > 0) {
1.800     albertel 7501:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   7502:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  7503:                         my $destname = $pathname.'/'.$filename;
                   7504:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  7505:                         if ($xml_classlist =~ /^error/) {
                   7506:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   7507:                         } else {
1.506     raeburn  7508:                             if ( open(FILE,">$destname") ) {
                   7509:                                 print FILE &unescape($xml_classlist);
                   7510:                                 close(FILE);
1.526     raeburn  7511:                             } else {
                   7512:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  7513:                             }
                   7514:                         }
                   7515:                     }
                   7516:                 }
                   7517:             }
                   7518:         }
                   7519:         return 'ok';
                   7520:     }
                   7521:     return 'error';
                   7522: }
                   7523: 
1.242     www      7524: sub get_query_reply {
                   7525:     my $queryid=shift;
1.1117    foxr     7526:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      7527:     my $reply='';
                   7528:     for (1..100) {
                   7529: 	sleep 2;
                   7530:         if (-e $replyfile.'.end') {
1.448     albertel 7531: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 7532: 		$reply = join('',<$fh>);
                   7533: 		close($fh);
1.240     www      7534: 	   } else { return 'error: reply_file_error'; }
1.242     www      7535:            return &unescape($reply);
                   7536: 	}
1.240     www      7537:     }
1.242     www      7538:     return 'timeout:'.$queryid;
1.240     www      7539: }
                   7540: 
                   7541: sub courselog_query {
1.241     www      7542: #
                   7543: # possible filters:
                   7544: # url: url or symb
                   7545: # username
                   7546: # domain
                   7547: # action: view, submit, grade
                   7548: # start: timestamp
                   7549: # end: timestamp
                   7550: #
1.240     www      7551:     my (%filters)=@_;
1.620     albertel 7552:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      7553:     if ($filters{'url'}) {
                   7554: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   7555:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   7556:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   7557:     }
1.620     albertel 7558:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7559:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      7560:     return &log_query($cname,$cdom,'courselog',%filters);
                   7561: }
                   7562: 
                   7563: sub userlog_query {
1.858     raeburn  7564: #
                   7565: # possible filters:
                   7566: # action: log check role
                   7567: # start: timestamp
                   7568: # end: timestamp
                   7569: #
1.240     www      7570:     my ($uname,$udom,%filters)=@_;
                   7571:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      7572: }
                   7573: 
1.506     raeburn  7574: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   7575: 
                   7576: sub auto_run {
1.508     raeburn  7577:     my ($cnum,$cdom) = @_;
1.876     raeburn  7578:     my $response = 0;
                   7579:     my $settings;
                   7580:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   7581:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   7582:         $settings = $domconfig{'autoenroll'};
                   7583:         if ($settings->{'run'} eq '1') {
                   7584:             $response = 1;
                   7585:         }
                   7586:     } else {
1.934     raeburn  7587:         my $homeserver;
                   7588:         if (&is_course($cdom,$cnum)) {
                   7589:             $homeserver = &homeserver($cnum,$cdom);
                   7590:         } else {
                   7591:             $homeserver = &domain($cdom,'primary');
                   7592:         }
                   7593:         if ($homeserver ne 'no_host') {
                   7594:             $response = &reply('autorun:'.$cdom,$homeserver);
                   7595:         }
1.876     raeburn  7596:     }
1.506     raeburn  7597:     return $response;
                   7598: }
1.776     albertel 7599: 
1.506     raeburn  7600: sub auto_get_sections {
1.508     raeburn  7601:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  7602:     my $homeserver;
                   7603:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   7604:         $homeserver = &homeserver($cnum,$cdom);
                   7605:     }
                   7606:     if (!defined($homeserver)) { 
                   7607:         if ($cdom =~ /^$match_domain$/) {
                   7608:             $homeserver = &domain($cdom,'primary');
                   7609:         }
                   7610:     }
                   7611:     my @secs;
                   7612:     if (defined($homeserver)) {
                   7613:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   7614:         unless ($response eq 'refused') {
                   7615:             @secs = split(/:/,$response);
                   7616:         }
1.506     raeburn  7617:     }
                   7618:     return @secs;
                   7619: }
1.776     albertel 7620: 
1.506     raeburn  7621: sub auto_new_course {
1.1099    raeburn  7622:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  7623:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  7624:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  7625:     return $response;
                   7626: }
1.776     albertel 7627: 
1.506     raeburn  7628: sub auto_validate_courseID {
1.508     raeburn  7629:     my ($cnum,$cdom,$inst_course_id) = @_;
                   7630:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  7631:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  7632:     return $response;
                   7633: }
1.776     albertel 7634: 
1.1007    raeburn  7635: sub auto_validate_instcode {
1.1020    raeburn  7636:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  7637:     my ($homeserver,$response);
                   7638:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7639:         $homeserver = &homeserver($cnum,$cdom);
                   7640:     }
                   7641:     if (!defined($homeserver)) {
                   7642:         if ($cdom =~ /^$match_domain$/) {
                   7643:             $homeserver = &domain($cdom,'primary');
                   7644:         }
                   7645:     }
1.1065    raeburn  7646:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   7647:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  7648:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   7649:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  7650: }
                   7651: 
1.506     raeburn  7652: sub auto_create_password {
1.873     raeburn  7653:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   7654:     my ($homeserver,$response);
1.506     raeburn  7655:     my $create_passwd = 0;
                   7656:     my $authchk = '';
1.873     raeburn  7657:     if ($udom =~ /^$match_domain$/) {
                   7658:         $homeserver = &domain($udom,'primary');
                   7659:     }
                   7660:     if ($homeserver eq '') {
                   7661:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7662:             $homeserver = &homeserver($cnum,$cdom);
                   7663:         }
                   7664:     }
                   7665:     if ($homeserver eq '') {
                   7666:         $authchk = 'nodomain';
1.506     raeburn  7667:     } else {
1.873     raeburn  7668:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   7669:         if ($response eq 'refused') {
                   7670:             $authchk = 'refused';
                   7671:         } else {
1.901     albertel 7672:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  7673:         }
1.506     raeburn  7674:     }
                   7675:     return ($authparam,$create_passwd,$authchk);
                   7676: }
                   7677: 
1.706     raeburn  7678: sub auto_photo_permission {
                   7679:     my ($cnum,$cdom,$students) = @_;
                   7680:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 7681:     my ($outcome,$perm_reqd,$conditions) = 
                   7682: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 7683:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7684: 	return (undef,undef);
                   7685:     }
1.706     raeburn  7686:     return ($outcome,$perm_reqd,$conditions);
                   7687: }
                   7688: 
                   7689: sub auto_checkphotos {
                   7690:     my ($uname,$udom,$pid) = @_;
                   7691:     my $homeserver = &homeserver($uname,$udom);
                   7692:     my ($result,$resulttype);
                   7693:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 7694: 				   &escape($uname).':'.&escape($pid),
                   7695: 				   $homeserver));
1.709     albertel 7696:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7697: 	return (undef,undef);
                   7698:     }
1.706     raeburn  7699:     if ($outcome) {
                   7700:         ($result,$resulttype) = split(/:/,$outcome);
                   7701:     } 
                   7702:     return ($result,$resulttype);
                   7703: }
                   7704: 
                   7705: sub auto_photochoice {
                   7706:     my ($cnum,$cdom) = @_;
                   7707:     my $homeserver = &homeserver($cnum,$cdom);
                   7708:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 7709: 						       &escape($cdom),
                   7710: 						       $homeserver)));
1.709     albertel 7711:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7712: 	return (undef,undef);
                   7713:     }
1.706     raeburn  7714:     return ($update,$comment);
                   7715: }
                   7716: 
                   7717: sub auto_photoupdate {
                   7718:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   7719:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 7720:     my $host=&hostname($homeserver);
1.706     raeburn  7721:     my $cmd = '';
                   7722:     my $maxtries = 1;
1.800     albertel 7723:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   7724:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  7725:     }
                   7726:     $cmd =~ s/%%$//;
                   7727:     $cmd = &escape($cmd);
                   7728:     my $query = 'institutionalphotos';
                   7729:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   7730:     unless ($queryid=~/^\Q$host\E\_/) {
                   7731:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   7732:         return 'error: '.$queryid;
                   7733:     }
                   7734:     my $reply = &get_query_reply($queryid);
                   7735:     my $tries = 1;
                   7736:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7737:         $reply = &get_query_reply($queryid);
                   7738:         $tries ++;
                   7739:     }
                   7740:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   7741:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   7742:     } else {
                   7743:         my @responses = split(/:/,$reply);
                   7744:         my $outcome = shift(@responses); 
                   7745:         foreach my $item (@responses) {
                   7746:             my ($key,$value) = split(/=/,$item);
                   7747:             $$photo{$key} = $value;
                   7748:         }
                   7749:         return $outcome;
                   7750:     }
                   7751:     return 'error';
                   7752: }
                   7753: 
1.521     raeburn  7754: sub auto_instcode_format {
1.793     albertel 7755:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   7756: 	$cat_order) = @_;
1.521     raeburn  7757:     my $courses = '';
1.772     raeburn  7758:     my @homeservers;
1.521     raeburn  7759:     if ($caller eq 'global') {
1.841     albertel 7760: 	my %servers = &get_servers($codedom,'library');
                   7761: 	foreach my $tryserver (keys(%servers)) {
                   7762: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7763: 		push(@homeservers,$tryserver);
                   7764: 	    }
1.584     raeburn  7765:         }
1.1022    raeburn  7766:     } elsif ($caller eq 'requests') {
                   7767:         if ($codedom =~ /^$match_domain$/) {
                   7768:             my $chome = &domain($codedom,'primary');
                   7769:             unless ($chome eq 'no_host') {
                   7770:                 push(@homeservers,$chome);
                   7771:             }
                   7772:         }
1.521     raeburn  7773:     } else {
1.772     raeburn  7774:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  7775:     }
1.793     albertel 7776:     foreach my $code (keys(%{$instcodes})) {
                   7777:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  7778:     }
                   7779:     chop($courses);
1.772     raeburn  7780:     my $ok_response = 0;
                   7781:     my $response;
                   7782:     while (@homeservers > 0 && $ok_response == 0) {
                   7783:         my $server = shift(@homeservers); 
                   7784:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   7785:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   7786:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 7787: 		split(/:/,$response);
1.772     raeburn  7788:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   7789:             push(@{$codetitles},&str2array($codetitles_str));
                   7790:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   7791:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   7792:             $ok_response = 1;
                   7793:         }
                   7794:     }
                   7795:     if ($ok_response) {
1.521     raeburn  7796:         return 'ok';
1.772     raeburn  7797:     } else {
                   7798:         return $response;
1.521     raeburn  7799:     }
                   7800: }
                   7801: 
1.792     raeburn  7802: sub auto_instcode_defaults {
                   7803:     my ($domain,$returnhash,$code_order) = @_;
                   7804:     my @homeservers;
1.841     albertel 7805: 
                   7806:     my %servers = &get_servers($domain,'library');
                   7807:     foreach my $tryserver (keys(%servers)) {
                   7808: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7809: 	    push(@homeservers,$tryserver);
                   7810: 	}
1.792     raeburn  7811:     }
1.841     albertel 7812: 
1.792     raeburn  7813:     my $response;
1.841     albertel 7814:     foreach my $server (@homeservers) {
1.792     raeburn  7815:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 7816:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   7817: 	
                   7818: 	foreach my $pair (split(/\&/,$response)) {
                   7819: 	    my ($name,$value)=split(/\=/,$pair);
                   7820: 	    if ($name eq 'code_order') {
                   7821: 		@{$code_order} = split(/\&/,&unescape($value));
                   7822: 	    } else {
                   7823: 		$returnhash->{&unescape($name)}=&unescape($value);
                   7824: 	    }
                   7825: 	}
                   7826: 	return 'ok';
1.792     raeburn  7827:     }
1.841     albertel 7828: 
                   7829:     return $response;
1.1003    raeburn  7830: }
                   7831: 
                   7832: sub auto_possible_instcodes {
1.1007    raeburn  7833:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   7834:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   7835:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   7836:         return;
                   7837:     }
1.1003    raeburn  7838:     my (@homeservers,$uhome);
                   7839:     if (defined(&domain($domain,'primary'))) {
                   7840:         $uhome=&domain($domain,'primary');
                   7841:         push(@homeservers,&domain($domain,'primary'));
                   7842:     } else {
                   7843:         my %servers = &get_servers($domain,'library');
                   7844:         foreach my $tryserver (keys(%servers)) {
                   7845:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7846:                 push(@homeservers,$tryserver);
                   7847:             }
                   7848:         }
                   7849:     }
                   7850:     my $response;
                   7851:     foreach my $server (@homeservers) {
                   7852:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   7853:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  7854:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   7855:             split(':',$response);
                   7856:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   7857:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  7858:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  7859:             my ($name,$value)=split('=',$item);
                   7860:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7861:         }
                   7862:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  7863:             my ($name,$value)=split('=',$item);
                   7864:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7865:         }
                   7866:         return 'ok';
                   7867:     }
                   7868:     return $response;
                   7869: }
1.792     raeburn  7870: 
1.1010    raeburn  7871: sub auto_courserequest_checks {
                   7872:     my ($dom) = @_;
1.1020    raeburn  7873:     my ($homeserver,%validations);
                   7874:     if ($dom =~ /^$match_domain$/) {
                   7875:         $homeserver = &domain($dom,'primary');
                   7876:     }
                   7877:     unless ($homeserver eq 'no_host') {
                   7878:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   7879:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   7880:             my @items = split(/&/,$response);
                   7881:             foreach my $item (@items) {
                   7882:                 my ($key,$value) = split('=',$item);
                   7883:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   7884:             }
                   7885:         }
                   7886:     }
1.1010    raeburn  7887:     return %validations; 
                   7888: }
                   7889: 
1.1020    raeburn  7890: sub auto_courserequest_validation {
                   7891:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   7892:     my ($homeserver,$response);
                   7893:     if ($dom =~ /^$match_domain$/) {
                   7894:         $homeserver = &domain($dom,'primary');
                   7895:     }
                   7896:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  7897:           
1.1020    raeburn  7898:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  7899:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  7900:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   7901:                                     $homeserver));
                   7902:     }
                   7903:     return $response;
                   7904: }
                   7905: 
1.777     albertel 7906: sub auto_validate_class_sec {
1.918     raeburn  7907:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  7908:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  7909:     my $ownerlist;
                   7910:     if (ref($owners) eq 'ARRAY') {
                   7911:         $ownerlist = join(',',@{$owners});
                   7912:     } else {
                   7913:         $ownerlist = $owners;
                   7914:     }
1.773     raeburn  7915:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  7916:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  7917:     return $response;
                   7918: }
                   7919: 
1.679     raeburn  7920: # ------------------------------------------------------- Course Group routines
                   7921: 
                   7922: sub get_coursegroups {
1.809     raeburn  7923:     my ($cdom,$cnum,$group,$namespace) = @_;
                   7924:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  7925: }
                   7926: 
1.679     raeburn  7927: sub modify_coursegroup {
                   7928:     my ($cdom,$cnum,$groupsettings) = @_;
                   7929:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   7930: }
                   7931: 
1.809     raeburn  7932: sub toggle_coursegroup_status {
                   7933:     my ($cdom,$cnum,$group,$action) = @_;
                   7934:     my ($from_namespace,$to_namespace);
                   7935:     if ($action eq 'delete') {
                   7936:         $from_namespace = 'coursegroups';
                   7937:         $to_namespace = 'deleted_groups';
                   7938:     } else {
                   7939:         $from_namespace = 'deleted_groups';
                   7940:         $to_namespace = 'coursegroups';
                   7941:     }
                   7942:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  7943:     if (my $tmp = &error(%curr_group)) {
                   7944:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   7945:         return ('read error',$tmp);
                   7946:     } else {
                   7947:         my %savedsettings = %curr_group; 
1.809     raeburn  7948:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  7949:         my $deloutcome;
                   7950:         if ($result eq 'ok') {
1.809     raeburn  7951:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  7952:         } else {
                   7953:             return ('write error',$result);
                   7954:         }
                   7955:         if ($deloutcome eq 'ok') {
                   7956:             return 'ok';
                   7957:         } else {
                   7958:             return ('delete error',$deloutcome);
                   7959:         }
                   7960:     }
                   7961: }
                   7962: 
1.679     raeburn  7963: sub modify_group_roles {
1.957     raeburn  7964:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  7965:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   7966:     my $role = 'gr/'.&escape($userprivs);
                   7967:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  7968:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  7969:     if ($result eq 'ok') {
                   7970:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   7971:     }
1.679     raeburn  7972:     return $result;
                   7973: }
                   7974: 
                   7975: sub modify_coursegroup_membership {
                   7976:     my ($cdom,$cnum,$membership) = @_;
                   7977:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   7978:     return $result;
                   7979: }
                   7980: 
1.682     raeburn  7981: sub get_active_groups {
                   7982:     my ($udom,$uname,$cdom,$cnum) = @_;
                   7983:     my $now = time;
                   7984:     my %groups = ();
                   7985:     foreach my $key (keys(%env)) {
1.811     albertel 7986:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  7987:             my ($start,$end) = split(/\./,$env{$key});
                   7988:             if (($end!=0) && ($end<$now)) { next; }
                   7989:             if (($start!=0) && ($start>$now)) { next; }
                   7990:             if ($1 eq $cdom && $2 eq $cnum) {
                   7991:                 $groups{$3} = $env{$key} ;
                   7992:             }
                   7993:         }
                   7994:     }
                   7995:     return %groups;
                   7996: }
                   7997: 
1.683     raeburn  7998: sub get_group_membership {
                   7999:     my ($cdom,$cnum,$group) = @_;
                   8000:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   8001: }
                   8002: 
                   8003: sub get_users_groups {
                   8004:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  8005:     my @usersgroups;
1.683     raeburn  8006:     my $cachetime=1800;
                   8007: 
                   8008:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  8009:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   8010:     if (defined($cached)) {
1.734     albertel 8011:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  8012:     } else {  
                   8013:         $grouplist = '';
1.816     raeburn  8014:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  8015:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  8016:         my $access_end = $env{'course.'.$courseid.
                   8017:                               '.default_enrollment_end_date'};
                   8018:         my $now = time;
                   8019:         foreach my $key (keys(%roleshash)) {
                   8020:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   8021:                 my $group = $1;
                   8022:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   8023:                     my $start = $2;
                   8024:                     my $end = $1;
                   8025:                     if ($start == -1) { next; } # deleted from group
                   8026:                     if (($start!=0) && ($start>$now)) { next; }
                   8027:                     if (($end!=0) && ($end<$now)) {
                   8028:                         if ($access_end && $access_end < $now) {
                   8029:                             if ($access_end - $end < 86400) {
                   8030:                                 push(@usersgroups,$group);
1.733     raeburn  8031:                             }
                   8032:                         }
1.817     raeburn  8033:                         next;
1.733     raeburn  8034:                     }
1.817     raeburn  8035:                     push(@usersgroups,$group);
1.683     raeburn  8036:                 }
                   8037:             }
                   8038:         }
1.817     raeburn  8039:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   8040:         $grouplist = join(':',@usersgroups);
                   8041:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  8042:     }
1.733     raeburn  8043:     return @usersgroups;
1.683     raeburn  8044: }
                   8045: 
                   8046: sub devalidate_getgroups_cache {
                   8047:     my ($udom,$uname,$cdom,$cnum)=@_;
                   8048:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 8049: 
1.683     raeburn  8050:     my $hashid="$udom:$uname:$courseid";
                   8051:     &devalidate_cache_new('getgroups',$hashid);
                   8052: }
                   8053: 
1.12      www      8054: # ------------------------------------------------------------------ Plain Text
                   8055: 
                   8056: sub plaintext {
1.988     raeburn  8057:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  8058:     if ($short =~ m{^cr/}) {
1.758     albertel 8059: 	return (split('/',$short))[-1];
                   8060:     }
1.742     raeburn  8061:     if (!defined($cid)) {
                   8062:         $cid = $env{'request.course.id'};
                   8063:     }
                   8064:     my %rolenames = (
1.1008    raeburn  8065:                       Course    => 'std',
                   8066:                       Community => 'alt1',
1.742     raeburn  8067:                     );
1.1037    raeburn  8068:     if ($cid ne '') {
                   8069:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   8070:             unless ($forcedefault) {
                   8071:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   8072:                 &Apache::lonlocal::mt_escape(\$roletext);
                   8073:                 return &Apache::lonlocal::mt($roletext);
                   8074:             }
                   8075:         }
                   8076:     }
                   8077:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   8078:         (defined($rolenames{$type})) && 
                   8079:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  8080:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  8081:     } elsif ($cid ne '') {
                   8082:         my $crstype = $env{'course.'.$cid.'.type'};
                   8083:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   8084:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   8085:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   8086:         }
1.742     raeburn  8087:     }
1.1037    raeburn  8088:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      8089: }
                   8090: 
                   8091: # ----------------------------------------------------------------- Assign Role
                   8092: 
                   8093: sub assignrole {
1.957     raeburn  8094:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   8095:         $context)=@_;
1.21      www      8096:     my $mrole;
                   8097:     if ($role =~ /^cr\//) {
1.393     www      8098:         my $cwosec=$url;
1.811     albertel 8099:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      8100: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  8101:            my $refused = 1;
                   8102:            if ($context eq 'requestcourses') {
                   8103:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   8104:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   8105:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   8106:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8107:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8108:                            if ($crsenv{'internal.courseowner'} eq
                   8109:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   8110:                                $refused = '';
                   8111:                            }
                   8112:                        }
                   8113:                    }
                   8114:                }
                   8115:            }
                   8116:            if ($refused) {
                   8117:                &logthis('Refused custom assignrole: '.
                   8118:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   8119:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   8120:                return 'refused';
                   8121:            }
1.104     www      8122:         }
1.21      www      8123:         $mrole='cr';
1.678     raeburn  8124:     } elsif ($role =~ /^gr\//) {
                   8125:         my $cwogrp=$url;
1.811     albertel 8126:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  8127:         unless (&allowed('mdg',$cwogrp)) {
                   8128:             &logthis('Refused group assignrole: '.
                   8129:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   8130:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   8131:             return 'refused';
                   8132:         }
                   8133:         $mrole='gr';
1.21      www      8134:     } else {
1.82      www      8135:         my $cwosec=$url;
1.811     albertel 8136:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  8137:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   8138:             my $refused;
                   8139:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   8140:                 if (!(&allowed('c'.$role,$url))) {
                   8141:                     $refused = 1;
                   8142:                 }
                   8143:             } else {
                   8144:                 $refused = 1;
                   8145:             }
1.947     raeburn  8146:             if ($refused) {
1.1045    raeburn  8147:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8148:                 if (!$selfenroll && $context eq 'course') {
                   8149:                     my %crsenv;
                   8150:                     if ($role eq 'cc' || $role eq 'co') {
                   8151:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8152:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   8153:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   8154:                                 if ($crsenv{'internal.courseowner'} eq 
                   8155:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8156:                                     $refused = '';
                   8157:                                 }
                   8158:                             }
                   8159:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   8160:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   8161:                                 if ($crsenv{'internal.courseowner'} eq 
                   8162:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8163:                                     $refused = '';
                   8164:                                 }
                   8165:                             }
                   8166:                         }
                   8167:                     }
                   8168:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  8169:                     $refused = '';
1.1017    raeburn  8170:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  8171:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  8172:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  8173:                         my $wrongcc;
                   8174:                         if ($cnum =~ /^$match_community$/) {
                   8175:                             $wrongcc = 1 if ($role eq 'cc');
                   8176:                         } else {
                   8177:                             $wrongcc = 1 if ($role eq 'co');
                   8178:                         }
                   8179:                         unless ($wrongcc) {
                   8180:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8181:                             if ($crsenv{'internal.courseowner'} eq 
                   8182:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   8183:                                 $refused = '';
                   8184:                             }
1.1017    raeburn  8185:                         }
                   8186:                     }
1.1172.2.9  raeburn  8187:                 } elsif ($context eq 'requestauthor') {
                   8188:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   8189:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   8190:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   8191:                             $refused = '';
                   8192:                         } else {
                   8193:                             my %domdefaults = &get_domain_defaults($udom);
                   8194:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   8195:                                 my $checkbystatus;
                   8196:                                 if ($env{'user.adv'}) {
                   8197:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   8198:                                     if ($disposition eq 'automatic') {
                   8199:                                         $refused = '';
                   8200:                                     } elsif ($disposition eq '') {
                   8201:                                         $checkbystatus = 1;
                   8202:                                     }
                   8203:                                 } else {
                   8204:                                     $checkbystatus = 1;
                   8205:                                 }
                   8206:                                 if ($checkbystatus) {
                   8207:                                     if ($env{'environment.inststatus'}) {
                   8208:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   8209:                                         foreach my $type (@inststatuses) {
                   8210:                                             if (($type ne '') &&
                   8211:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   8212:                                                 $refused = '';
                   8213:                                             }
                   8214:                                         }
                   8215:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   8216:                                         $refused = '';
                   8217:                                     }
                   8218:                                 }
                   8219:                             }
                   8220:                         }
                   8221:                     }
1.1017    raeburn  8222:                 }
                   8223:                 if ($refused) {
1.947     raeburn  8224:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   8225:                              ' '.$role.' '.$end.' '.$start.' by '.
                   8226: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   8227:                     return 'refused';
                   8228:                 }
1.932     raeburn  8229:             }
1.1131    raeburn  8230:         } elsif ($role eq 'au') {
                   8231:             if ($url ne '/'.$udom.'/') {
                   8232:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   8233:                          ' to assign author role for '.$uname.':'.$udom.
                   8234:                          ' in domain: '.$url.' refused (wrong domain).');
                   8235:                 return 'refused';
                   8236:             }
1.104     www      8237:         }
1.21      www      8238:         $mrole=$role;
                   8239:     }
1.620     albertel 8240:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      8241:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      8242:     if ($end) { $command.='_'.$end; }
1.21      www      8243:     if ($start) {
                   8244: 	if ($end) { 
1.81      www      8245:            $command.='_'.$start; 
1.21      www      8246:         } else {
1.81      www      8247:            $command.='_0_'.$start;
1.21      www      8248:         }
                   8249:     }
1.739     raeburn  8250:     my $origstart = $start;
                   8251:     my $origend = $end;
1.957     raeburn  8252:     my $delflag;
1.357     www      8253: # actually delete
                   8254:     if ($deleteflag) {
1.373     www      8255: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      8256: # modify command to delete the role
1.620     albertel 8257:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      8258:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 8259: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      8260: # set start and finish to negative values for userrolelog
                   8261:            $start=-1;
                   8262:            $end=-1;
1.957     raeburn  8263:            $delflag = 1;
1.357     www      8264:         }
                   8265:     }
                   8266: # send command
1.349     www      8267:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      8268: # log new user role if status is ok
1.349     www      8269:     if ($answer eq 'ok') {
1.663     raeburn  8270: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  8271:         if (($role eq 'cc') || ($role eq 'in') ||
                   8272:             ($role eq 'ep') || ($role eq 'ad') ||
                   8273:             ($role eq 'ta') || ($role eq 'st') ||
                   8274:             ($role=~/^cr/) || ($role eq 'gr') ||
                   8275:             ($role eq 'co')) {
1.1172.2.13  raeburn  8276: # for course roles, perform group memberships changes triggered by role change.
                   8277:             unless ($role =~ /^gr/) {
                   8278:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   8279:                                                  $origstart,$selfenroll,$context);
                   8280:             }
1.1172.2.9  raeburn  8281:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8282:                            $selfenroll,$context);
                   8283:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
                   8284:                  ($role eq 'au') || ($role eq 'dc')) {
                   8285:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8286:                            $context);
                   8287:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   8288:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8289:                              $context);
                   8290:         }
1.1053    raeburn  8291:         if ($role eq 'cc') {
                   8292:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   8293:         }
1.349     www      8294:     }
                   8295:     return $answer;
1.169     harris41 8296: }
                   8297: 
1.1053    raeburn  8298: sub autoupdate_coowners {
                   8299:     my ($url,$end,$start,$uname,$udom) = @_;
                   8300:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   8301:     if (($cdom ne '') && ($cnum ne '')) {
                   8302:         my $now = time;
                   8303:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   8304:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   8305:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   8306:             my $instcode = $coursehash{'internal.coursecode'};
                   8307:             if ($instcode ne '') {
1.1056    raeburn  8308:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   8309:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  8310:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  8311:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   8312:                         if ($result eq 'valid') {
                   8313:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  8314:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8315:                                     push(@newcoowners,$coowner);
                   8316:                                 }
                   8317:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   8318:                                     push(@newcoowners,$uname.':'.$udom);
                   8319:                                 }
                   8320:                                 @newcoowners = sort(@newcoowners);
                   8321:                             } else {
                   8322:                                 push(@newcoowners,$uname.':'.$udom);
                   8323:                             }
                   8324:                         } else {
                   8325:                             if ($coursehash{'internal.co-owners'}) {
                   8326:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8327:                                     unless ($coowner eq $uname.':'.$udom) {
                   8328:                                         push(@newcoowners,$coowner);
                   8329:                                     }
                   8330:                                 }
                   8331:                                 unless (@newcoowners > 0) {
                   8332:                                     $delcoowners = 1;
                   8333:                                     $coowners = '';
                   8334:                                 }
                   8335:                             }
                   8336:                         }
                   8337:                         if (@newcoowners || $delcoowners) {
                   8338:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   8339:                                             $delcoowners,@newcoowners);
                   8340:                         }
                   8341:                     }
                   8342:                 }
                   8343:             }
                   8344:         }
                   8345:     }
                   8346: }
                   8347: 
                   8348: sub store_coowners {
                   8349:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   8350:     my $cid = $cdom.'_'.$cnum;
                   8351:     my ($coowners,$delresult,$putresult);
                   8352:     if (@newcoowners) {
                   8353:         $coowners = join(',',@newcoowners);
                   8354:         my %coownershash = (
                   8355:                             'internal.co-owners' => $coowners,
                   8356:                            );
                   8357:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   8358:         if ($putresult eq 'ok') {
                   8359:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   8360:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   8361:             }
                   8362:         }
                   8363:     }
                   8364:     if ($delcoowners) {
                   8365:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   8366:         if ($delresult eq 'ok') {
                   8367:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   8368:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   8369:             }
                   8370:         }
                   8371:     }
                   8372:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   8373:         my %crsinfo =
                   8374:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   8375:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   8376:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   8377:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   8378:         }
                   8379:     }
                   8380: }
                   8381: 
1.169     harris41 8382: # -------------------------------------------------- Modify user authentication
1.197     www      8383: # Overrides without validation
                   8384: 
1.169     harris41 8385: sub modifyuserauth {
                   8386:     my ($udom,$uname,$umode,$upass)=@_;
                   8387:     my $uhome=&homeserver($uname,$udom);
1.197     www      8388:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   8389:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 8390:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8391:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 8392:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   8393: 		     &escape($upass),$uhome);
1.620     albertel 8394:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      8395:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   8396:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   8397:     &log($udom,,$uname,$uhome,
1.620     albertel 8398:         'Authentication changed by '.$env{'user.domain'}.', '.
                   8399:                                      $env{'user.name'}.', '.$umode.
1.197     www      8400:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 8401:     unless ($reply eq 'ok') {
1.197     www      8402:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 8403: 	return 'error: '.$reply;
                   8404:     }   
1.170     harris41 8405:     return 'ok';
1.80      www      8406: }
                   8407: 
1.81      www      8408: # --------------------------------------------------------------- Modify a user
1.80      www      8409: 
1.81      www      8410: sub modifyuser {
1.206     matthew  8411:     my ($udom,    $uname, $uid,
                   8412:         $umode,   $upass, $first,
                   8413:         $middle,  $last,  $gene,
1.1058    raeburn  8414:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 8415:     $udom= &LONCAPA::clean_domain($udom);
                   8416:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  8417:     my $showcandelete = 'none';
                   8418:     if (ref($candelete) eq 'ARRAY') {
                   8419:         if (@{$candelete} > 0) {
                   8420:             $showcandelete = join(', ',@{$candelete});
                   8421:         }
                   8422:     }
1.81      www      8423:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      8424:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  8425: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  8426:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   8427:                                      ' desiredhome not specified'). 
1.620     albertel 8428:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8429:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 8430:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  8431:     my $newuser;
                   8432:     if ($uhome eq 'no_host') {
                   8433:         $newuser = 1;
                   8434:     }
1.80      www      8435: # ----------------------------------------------------------------- Create User
1.406     albertel 8436:     if (($uhome eq 'no_host') && 
                   8437: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      8438:         my $unhome='';
1.844     albertel 8439:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  8440:             $unhome = $desiredhome;
1.620     albertel 8441: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   8442: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  8443:         } else { # load balancing routine for determining $unhome
1.81      www      8444:             my $loadm=10000000;
1.841     albertel 8445: 	    my %servers = &get_servers($udom,'library');
                   8446: 	    foreach my $tryserver (keys(%servers)) {
                   8447: 		my $answer=reply('load',$tryserver);
                   8448: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   8449: 		    $loadm=$answer;
                   8450: 		    $unhome=$tryserver;
                   8451: 		}
1.80      www      8452: 	    }
                   8453:         }
                   8454:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  8455: 	    return 'error: unable to find a home server for '.$uname.
                   8456:                    ' in domain '.$udom;
1.80      www      8457:         }
                   8458:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   8459:                          &escape($upass),$unhome);
                   8460: 	unless ($reply eq 'ok') {
                   8461:             return 'error: '.$reply;
                   8462:         }   
1.230     stredwic 8463:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      8464:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  8465: 	    return 'error: unable verify users home machine.';
1.80      www      8466:         }
1.209     matthew  8467:     }   # End of creation of new user
1.80      www      8468: # ---------------------------------------------------------------------- Add ID
                   8469:     if ($uid) {
                   8470:        $uid=~tr/A-Z/a-z/;
                   8471:        my %uidhash=&idrget($udom,$uname);
1.196     www      8472:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   8473:          && (!$forceid)) {
1.80      www      8474: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  8475: 	      return 'error: user id "'.$uid.'" does not match '.
                   8476:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      8477:           }
                   8478:        } else {
                   8479: 	  &idput($udom,($uname => $uid));
                   8480:        }
                   8481:     }
                   8482: # -------------------------------------------------------------- Add names, etc
1.313     matthew  8483:     my @tmp=&get('environment',
1.899     raeburn  8484: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  8485:                     'permanentemail','inststatus'],
1.134     albertel 8486: 		   $udom,$uname);
1.1075    raeburn  8487:     my (%names,%oldnames);
1.313     matthew  8488:     if ($tmp[0] =~ m/^error:.*/) { 
                   8489:         %names=(); 
                   8490:     } else {
                   8491:         %names = @tmp;
1.1075    raeburn  8492:         %oldnames = %names;
1.313     matthew  8493:     }
1.388     www      8494: #
1.1058    raeburn  8495: # If name, email and/or uid are blank (e.g., because an uploaded file
                   8496: # of users did not contain them), do not overwrite existing values
                   8497: # unless field is in $candelete array ref.  
                   8498: #
                   8499: 
                   8500:     my @fields = ('firstname','middlename','lastname','generation',
                   8501:                   'permanentemail','id');
                   8502:     my %newvalues;
                   8503:     if (ref($candelete) eq 'ARRAY') {
                   8504:         foreach my $field (@fields) {
                   8505:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   8506:                 if ($field eq 'firstname') {
                   8507:                     $names{$field} = $first;
                   8508:                 } elsif ($field eq 'middlename') {
                   8509:                     $names{$field} = $middle;
                   8510:                 } elsif ($field eq 'lastname') {
                   8511:                     $names{$field} = $last;
                   8512:                 } elsif ($field eq 'generation') { 
                   8513:                     $names{$field} = $gene;
                   8514:                 } elsif ($field eq 'permanentemail') {
                   8515:                     $names{$field} = $email;
                   8516:                 } elsif ($field eq 'id') {
                   8517:                     $names{$field}  = $uid;
                   8518:                 }
                   8519:             }
                   8520:         }
                   8521:     }
1.388     www      8522:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  8523:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      8524:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  8525:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      8526:     if ($email) {
                   8527:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  8528:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      8529:     }
1.899     raeburn  8530:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  8531:     if (defined($inststatus)) {
                   8532:         $names{'inststatus'} = '';
                   8533:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   8534:         if (ref($usertypes) eq 'HASH') {
                   8535:             my @okstatuses; 
                   8536:             foreach my $item (split(/:/,$inststatus)) {
                   8537:                 if (defined($usertypes->{$item})) {
                   8538:                     push(@okstatuses,$item);  
                   8539:                 }
                   8540:             }
                   8541:             if (@okstatuses) {
                   8542:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   8543:             }
                   8544:         }
                   8545:     }
1.1075    raeburn  8546:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  8547:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  8548:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  8549:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   8550:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   8551:     } else {
                   8552:         $logmsg .= ' during self creation';
                   8553:     }
1.1075    raeburn  8554:     my $changed;
                   8555:     if ($newuser) {
                   8556:         $changed = 1;
                   8557:     } else {
                   8558:         foreach my $field (@fields) {
                   8559:             if ($names{$field} ne $oldnames{$field}) {
                   8560:                 $changed = 1;
                   8561:                 last;
                   8562:             }
                   8563:         }
                   8564:     }
                   8565:     unless ($changed) {
                   8566:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   8567:         &logthis($logmsg);
                   8568:         return 'ok';
                   8569:     }
                   8570:     my $reply = &put('environment', \%names, $udom,$uname);
                   8571:     if ($reply ne 'ok') { 
                   8572:         return 'error: '.$reply;
                   8573:     }
1.1087    raeburn  8574:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   8575:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   8576:     }
1.1075    raeburn  8577:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   8578:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   8579:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  8580:     &logthis($logmsg);
1.134     albertel 8581:     return 'ok';
1.80      www      8582: }
                   8583: 
1.81      www      8584: # -------------------------------------------------------------- Modify student
1.80      www      8585: 
1.81      www      8586: sub modifystudent {
                   8587:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  8588:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.19  raeburn  8589:         $selfenroll,$context,$inststatus,$credits)=@_;
1.455     albertel 8590:     if (!$cid) {
1.620     albertel 8591: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8592: 	    return 'not_in_class';
                   8593: 	}
1.80      www      8594:     }
                   8595: # --------------------------------------------------------------- Make the user
1.81      www      8596:     my $reply=&modifyuser
1.209     matthew  8597: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  8598:          $desiredhome,$email,$inststatus);
1.80      www      8599:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  8600:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  8601:     # student's environment
1.297     matthew  8602:     $uid = undef if (!$forceid);
1.455     albertel 8603:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  8604: 					$gene,$usec,$end,$start,$type,$locktype,
                   8605:                                         $cid,$selfenroll,$context,$credits);
1.297     matthew  8606:     return $reply;
                   8607: }
                   8608: 
                   8609: sub modify_student_enrollment {
1.1172.2.23  raeburn  8610:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
                   8611:         $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455     albertel 8612:     my ($cdom,$cnum,$chome);
                   8613:     if (!$cid) {
1.620     albertel 8614: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8615: 	    return 'not_in_class';
                   8616: 	}
1.620     albertel 8617: 	$cdom=$env{'course.'.$cid.'.domain'};
                   8618: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 8619:     } else {
                   8620: 	($cdom,$cnum)=split(/_/,$cid);
                   8621:     }
1.620     albertel 8622:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 8623:     if (!$chome) {
1.457     raeburn  8624: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  8625:     }
1.455     albertel 8626:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  8627:     # Make sure the user exists
1.81      www      8628:     my $uhome=&homeserver($uname,$udom);
                   8629:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8630: 	return 'error: no such user';
                   8631:     }
1.297     matthew  8632:     # Get student data if we were not given enough information
                   8633:     if (!defined($first)  || $first  eq '' || 
                   8634:         !defined($last)   || $last   eq '' || 
                   8635:         !defined($uid)    || $uid    eq '' || 
                   8636:         !defined($middle) || $middle eq '' || 
                   8637:         !defined($gene)   || $gene   eq '') {
1.294     matthew  8638:         # They did not supply us with enough data to enroll the student, so
                   8639:         # we need to pick up more information.
1.297     matthew  8640:         my %tmp = &get('environment',
1.294     matthew  8641:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  8642:                        ,$udom,$uname);
                   8643: 
1.800     albertel 8644:         #foreach my $key (keys(%tmp)) {
                   8645:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 8646:         #}
1.294     matthew  8647:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   8648:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   8649:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  8650:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  8651:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   8652:     }
1.556     albertel 8653:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  8654:     my $user = "$uname:$udom";
                   8655:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 8656:     my $reply=cput('classlist',
1.1148    raeburn  8657: 		   {$user => 
1.1172.2.19  raeburn  8658: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487     albertel 8659: 		   $cdom,$cnum);
1.1148    raeburn  8660:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   8661:         &devalidate_getsection_cache($udom,$uname,$cid);
                   8662:     } else { 
1.81      www      8663: 	return 'error: '.$reply;
                   8664:     }
1.297     matthew  8665:     # Add student role to user
1.83      www      8666:     my $uurl='/'.$cid;
1.81      www      8667:     $uurl=~s/\_/\//g;
                   8668:     if ($usec) {
                   8669: 	$uurl.='/'.$usec;
                   8670:     }
1.1148    raeburn  8671:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   8672:                              $selfenroll,$context);
                   8673:     if ($result ne 'ok') {
                   8674:         if ($old_entry{$user} ne '') {
                   8675:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   8676:         } else {
                   8677:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   8678:         }
                   8679:     }
                   8680:     return $result; 
1.21      www      8681: }
                   8682: 
1.556     albertel 8683: sub format_name {
                   8684:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   8685:     my $name;
                   8686:     if ($first ne 'lastname') {
                   8687: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   8688:     } else {
                   8689: 	if ($lastname=~/\S/) {
                   8690: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   8691: 	    $name=~s/\s+,/,/;
                   8692: 	} else {
                   8693: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   8694: 	}
                   8695:     }
                   8696:     $name=~s/^\s+//;
                   8697:     $name=~s/\s+$//;
                   8698:     $name=~s/\s+/ /g;
                   8699:     return $name;
                   8700: }
                   8701: 
1.84      www      8702: # ------------------------------------------------- Write to course preferences
                   8703: 
                   8704: sub writecoursepref {
                   8705:     my ($courseid,%prefs)=@_;
                   8706:     $courseid=~s/^\///;
                   8707:     $courseid=~s/\_/\//g;
                   8708:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   8709:     my $chome=homeserver($cnum,$cdomain);
                   8710:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   8711: 	return 'error: no such course';
                   8712:     }
                   8713:     my $cstring='';
1.800     albertel 8714:     foreach my $pref (keys(%prefs)) {
                   8715: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 8716:     }
1.84      www      8717:     $cstring=~s/\&$//;
                   8718:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   8719: }
                   8720: 
                   8721: # ---------------------------------------------------------- Make/modify course
                   8722: 
                   8723: sub createcourse {
1.741     raeburn  8724:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  8725:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      8726:     $url=&declutter($url);
                   8727:     my $cid='';
1.1028    raeburn  8728:     if ($context eq 'requestcourses') {
                   8729:         my $can_create = 0;
                   8730:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   8731:         if ($udom eq $ownerdom) {
                   8732:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   8733:                                   $context)) {
                   8734:                 $can_create = 1;
                   8735:             }
                   8736:         } else {
                   8737:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   8738:                                            $category);
                   8739:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   8740:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   8741:                 if (@curr > 0) {
                   8742:                     my @options = qw(approval validate autolimit);
                   8743:                     my $optregex = join('|',@options);
                   8744:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   8745:                         $can_create = 1;
                   8746:                     }
                   8747:                 }
                   8748:             }
                   8749:         }
                   8750:         if ($can_create) {
                   8751:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   8752:                 unless (&allowed('ccc',$udom)) {
                   8753:                     return 'refused'; 
                   8754:                 }
1.1017    raeburn  8755:             }
                   8756:         } else {
                   8757:             return 'refused';
                   8758:         }
1.1028    raeburn  8759:     } elsif (!&allowed('ccc',$udom)) {
                   8760:         return 'refused';
1.84      www      8761:     }
1.1011    raeburn  8762: # --------------------------------------------------------------- Get Unique ID
                   8763:     my $uname;
                   8764:     if ($cnum =~ /^$match_courseid$/) {
                   8765:         my $chome=&homeserver($cnum,$udom,'true');
                   8766:         if (($chome eq '') || ($chome eq 'no_host')) {
                   8767:             $uname = $cnum;
                   8768:         } else {
1.1038    raeburn  8769:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8770:         }
                   8771:     } else {
1.1038    raeburn  8772:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8773:     }
                   8774:     return $uname if ($uname =~ /^error/);
                   8775: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  8776:     if (!defined($course_server)) {
                   8777:         if (defined(&domain($udom,'primary'))) {
                   8778:             $course_server = &domain($udom,'primary');
                   8779:         } else {
                   8780:             $course_server = $env{'user.home'}; 
                   8781:         }
                   8782:     }
                   8783:     my %host_servers =
                   8784:         &Apache::lonnet::get_servers($udom,'library');
                   8785:     unless ($host_servers{$course_server}) {
                   8786:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  8787:     }
1.84      www      8788: # ------------------------------------------------------------- Make the course
                   8789:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  8790:                       $course_server);
1.84      www      8791:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  8792:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      8793:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8794: 	return 'error: no such course';
                   8795:     }
1.271     www      8796: # ----------------------------------------------------------------- Course made
1.516     raeburn  8797: # log existence
1.1029    raeburn  8798:     my $now = time;
1.918     raeburn  8799:     my $newcourse = {
                   8800:                     $udom.'_'.$uname => {
1.921     raeburn  8801:                                      description => $description,
                   8802:                                      inst_code   => $inst_code,
                   8803:                                      owner       => $course_owner,
                   8804:                                      type        => $crstype,
1.1029    raeburn  8805:                                      creator     => $env{'user.name'}.':'.
                   8806:                                                     $env{'user.domain'},
                   8807:                                      created     => $now,
                   8808:                                      context     => $context,
1.918     raeburn  8809:                                                 },
                   8810:                     };
1.921     raeburn  8811:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      8812: # set toplevel url
1.271     www      8813:     my $topurl=$url;
                   8814:     unless ($nonstandard) {
                   8815: # ------------------------------------------ For standard courses, make top url
                   8816:         my $mapurl=&clutter($url);
1.278     www      8817:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 8818:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      8819: <map>
                   8820: <resource id="1" type="start"></resource>
                   8821: <resource id="2" src="$mapurl"></resource>
                   8822: <resource id="3" type="finish"></resource>
                   8823: <link index="1" from="1" to="2"></link>
                   8824: <link index="2" from="2" to="3"></link>
                   8825: </map>
                   8826: ENDINITMAP
                   8827:         $topurl=&declutter(
1.638     albertel 8828:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      8829:                           );
                   8830:     }
                   8831: # ----------------------------------------------------------- Write preferences
1.84      www      8832:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  8833:                      ('description'              => $description,
                   8834:                       'url'                      => $topurl,
                   8835:                       'internal.creator'         => $env{'user.name'}.':'.
                   8836:                                                     $env{'user.domain'},
                   8837:                       'internal.created'         => $now,
                   8838:                       'internal.creationcontext' => $context)
                   8839:                     );
1.84      www      8840:     return '/'.$udom.'/'.$uname;
                   8841: }
                   8842: 
1.1011    raeburn  8843: # ------------------------------------------------------------------- Create ID
                   8844: sub generate_coursenum {
1.1038    raeburn  8845:     my ($udom,$crstype) = @_;
1.1011    raeburn  8846:     my $domdesc = &domain($udom);
                   8847:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  8848:     my $first;
                   8849:     if ($crstype eq 'Community') {
                   8850:         $first = '0';
                   8851:     } else {
                   8852:         $first = int(1+rand(9)); 
                   8853:     } 
                   8854:     my $uname=$first.
1.1011    raeburn  8855:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8856:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8857:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8858: # ----------------------------------------------- Make sure that does not exist
                   8859:     my $uhome=&homeserver($uname,$udom,'true');
                   8860:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  8861:         if ($crstype eq 'Community') {
                   8862:             $first = '0';
                   8863:         } else {
                   8864:             $first = int(1+rand(9));
                   8865:         }
                   8866:         $uname=$first.
1.1011    raeburn  8867:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8868:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8869:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8870:         $uhome=&homeserver($uname,$udom,'true');
                   8871:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   8872:             return 'error: unable to generate unique course-ID';
                   8873:         }
                   8874:     }
                   8875:     return $uname;
                   8876: }
                   8877: 
1.813     albertel 8878: sub is_course {
1.1167    droeschl 8879:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   8880:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   8881: 
                   8882:     return unless $cdom and $cnum;
                   8883: 
                   8884:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   8885:         '.');
                   8886: 
1.1172.2.23  raeburn  8887:     return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167    droeschl 8888:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 8889: }
                   8890: 
1.1015    raeburn  8891: sub store_userdata {
                   8892:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  8893:     my $result;
1.1016    raeburn  8894:     if ($datakey ne '') {
1.1013    raeburn  8895:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  8896:             if ($udom eq '' || $uname eq '') {
                   8897:                 $udom = $env{'user.domain'};
                   8898:                 $uname = $env{'user.name'};
                   8899:             }
                   8900:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  8901:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   8902:                 $result = 'error: no_host';
                   8903:             } else {
                   8904:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   8905:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   8906: 
                   8907:                 my $namevalue='';
                   8908:                 foreach my $key (keys(%{$storehash})) {
                   8909:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   8910:                 }
                   8911:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  8912:                 unless ($namespace eq 'courserequests') {
                   8913:                     $datakey = &escape($datakey);
                   8914:                 }
1.1105    raeburn  8915:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   8916:                                   $namevalue,$uhome);
1.1013    raeburn  8917:             }
                   8918:         } else {
                   8919:             $result = 'error: data to store was not a hash reference'; 
                   8920:         }
                   8921:     } else {
                   8922:         $result= 'error: invalid requestkey'; 
                   8923:     }
                   8924:     return $result;
                   8925: }
                   8926: 
1.21      www      8927: # ---------------------------------------------------------- Assign Custom Role
                   8928: 
                   8929: sub assigncustomrole {
1.957     raeburn  8930:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8931:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  8932:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      8933: }
                   8934: 
                   8935: # ----------------------------------------------------------------- Revoke Role
                   8936: 
                   8937: sub revokerole {
1.957     raeburn  8938:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8939:     my $now=time;
1.965     raeburn  8940:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      8941: }
                   8942: 
                   8943: # ---------------------------------------------------------- Revoke Custom Role
                   8944: 
                   8945: sub revokecustomrole {
1.957     raeburn  8946:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8947:     my $now=time;
1.357     www      8948:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  8949:            $deleteflag,$selfenroll,$context);
1.17      www      8950: }
                   8951: 
1.533     banghart 8952: # ------------------------------------------------------------ Disk usage
1.535     albertel 8953: sub diskusage {
1.955     raeburn  8954:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   8955:     $directorypath =~ s/\/$//;
                   8956:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   8957:                        .&escape($getpropath).':'.&escape($uname).':'
                   8958:                        .&escape($udom),homeserver($uname,$udom));
                   8959:     if ($listing eq 'unknown_cmd') {
                   8960:         if ($getpropath) {
                   8961:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   8962:         }
                   8963:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   8964:     }
1.514     albertel 8965:     return $listing;
1.512     banghart 8966: }
                   8967: 
1.566     banghart 8968: sub is_locked {
1.1096    raeburn  8969:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 8970:     my @check;
                   8971:     my $is_locked;
1.1093    raeburn  8972:     push (@check,$file_name);
1.613     albertel 8973:     my %locked = &get('file_permissions',\@check,
1.620     albertel 8974: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 8975:     my ($tmp)=keys(%locked);
                   8976:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  8977:     
1.566     banghart 8978:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  8979:         $is_locked = 'false';
                   8980:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  8981:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  8982:                $is_locked = 'true';
1.1096    raeburn  8983:                if (ref($which) eq 'ARRAY') {
                   8984:                    push(@{$which},$entry);
                   8985:                } else {
                   8986:                    last;
                   8987:                }
1.745     raeburn  8988:            }
                   8989:        }
1.566     banghart 8990:     } else {
                   8991:         $is_locked = 'false';
                   8992:     }
1.1093    raeburn  8993:     return $is_locked;
1.566     banghart 8994: }
                   8995: 
1.759     albertel 8996: sub declutter_portfile {
                   8997:     my ($file) = @_;
1.833     albertel 8998:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 8999:     return $file;
                   9000: }
                   9001: 
1.559     banghart 9002: # ------------------------------------------------------------- Mark as Read Only
                   9003: 
                   9004: sub mark_as_readonly {
                   9005:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 9006:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9007:     my ($tmp)=keys(%current_permissions);
                   9008:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 9009:     foreach my $file (@{$files}) {
1.759     albertel 9010: 	$file = &declutter_portfile($file);
1.561     banghart 9011:         push(@{$current_permissions{$file}},$what);
1.559     banghart 9012:     }
1.613     albertel 9013:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9014:     return;
                   9015: }
                   9016: 
1.572     banghart 9017: # ------------------------------------------------------------Save Selected Files
                   9018: 
                   9019: sub save_selected_files {
                   9020:     my ($user, $path, @files) = @_;
                   9021:     my $filename = $user."savedfiles";
1.573     banghart 9022:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 9023:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 9024:     foreach my $file (@files) {
1.620     albertel 9025:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 9026:     }
                   9027:     foreach my $file (@other_files) {
1.574     banghart 9028:         print (OUT $file."\n");
1.572     banghart 9029:     }
1.574     banghart 9030:     close (OUT);
1.572     banghart 9031:     return 'ok';
                   9032: }
                   9033: 
1.574     banghart 9034: sub clear_selected_files {
                   9035:     my ($user) = @_;
                   9036:     my $filename = $user."savedfiles";
1.1117    foxr     9037:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 9038:     print (OUT undef);
                   9039:     close (OUT);
                   9040:     return ("ok");    
                   9041: }
                   9042: 
1.572     banghart 9043: sub files_in_path {
                   9044:     my ($user, $path) = @_;
                   9045:     my $filename = $user."savedfiles";
                   9046:     my %return_files;
1.1117    foxr     9047:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 9048:     while (my $line_in = <IN>) {
1.574     banghart 9049:         chomp ($line_in);
                   9050:         my @paths_and_file = split (m!/!, $line_in);
                   9051:         my $file_part = pop (@paths_and_file);
                   9052:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 9053:         $path_part.='/';
                   9054:         my $path_and_file = $path_part.$file_part;
                   9055:         if ($path_part eq $path) {
                   9056:             $return_files{$file_part}= 'selected';
                   9057:         }
                   9058:     }
1.574     banghart 9059:     close (IN);
                   9060:     return (\%return_files);
1.572     banghart 9061: }
                   9062: 
                   9063: # called in portfolio select mode, to show files selected NOT in current directory
                   9064: sub files_not_in_path {
                   9065:     my ($user, $path) = @_;
                   9066:     my $filename = $user."savedfiles";
                   9067:     my @return_files;
                   9068:     my $path_part;
1.1117    foxr     9069:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 9070:     while (my $line = <IN>) {
1.572     banghart 9071:         #ok, I know it's clunky, but I want it to work
1.800     albertel 9072:         my @paths_and_file = split(m|/|, $line);
                   9073:         my $file_part = pop(@paths_and_file);
                   9074:         chomp($file_part);
                   9075:         my $path_part = join('/', @paths_and_file);
1.572     banghart 9076:         $path_part .= '/';
                   9077:         my $path_and_file = $path_part.$file_part;
                   9078:         if ($path_part ne $path) {
1.800     albertel 9079:             push(@return_files, ($path_and_file));
1.572     banghart 9080:         }
                   9081:     }
1.800     albertel 9082:     close(OUT);
1.574     banghart 9083:     return (@return_files);
1.572     banghart 9084: }
                   9085: 
1.745     raeburn  9086: #----------------------------------------------Get portfolio file permissions
1.629     banghart 9087: 
1.745     raeburn  9088: sub get_portfile_permissions {
                   9089:     my ($domain,$user) = @_;
1.613     albertel 9090:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9091:     my ($tmp)=keys(%current_permissions);
                   9092:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9093:     return \%current_permissions;
                   9094: }
                   9095: 
                   9096: #---------------------------------------------Get portfolio file access controls
                   9097: 
1.749     raeburn  9098: sub get_access_controls {
1.745     raeburn  9099:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 9100:     my %access;
                   9101:     my $real_file = $file;
                   9102:     $file =~ s/\.meta$//;
1.745     raeburn  9103:     if (defined($file)) {
1.749     raeburn  9104:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   9105:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 9106:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  9107:             }
                   9108:         }
1.745     raeburn  9109:     } else {
1.749     raeburn  9110:         foreach my $key (keys(%{$current_permissions})) {
                   9111:             if ($key =~ /\0accesscontrol$/) {
                   9112:                 if (defined($group)) {
                   9113:                     if ($key !~ m-^\Q$group\E/-) {
                   9114:                         next;
                   9115:                     }
                   9116:                 }
                   9117:                 my ($fullpath) = split(/\0/,$key);
                   9118:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   9119:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   9120:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   9121:                     }
                   9122:                 }
                   9123:             }
                   9124:         }
                   9125:     }
                   9126:     return %access;
                   9127: }
                   9128: 
                   9129: sub modify_access_controls {
                   9130:     my ($file_name,$changes,$domain,$user)=@_;
                   9131:     my ($outcome,$deloutcome);
                   9132:     my %store_permissions;
                   9133:     my %new_values;
                   9134:     my %new_control;
                   9135:     my %translation;
                   9136:     my @deletions = ();
                   9137:     my $now = time;
                   9138:     if (exists($$changes{'activate'})) {
                   9139:         if (ref($$changes{'activate'}) eq 'HASH') {
                   9140:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   9141:             my $numnew = scalar(@newitems);
                   9142:             for (my $i=0; $i<$numnew; $i++) {
                   9143:                 my $newkey = $newitems[$i];
                   9144:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  9145:                 if ($newkey =~ /^\d+:/) { 
                   9146:                     $newkey =~ s/^(\d+)/$newid/;
                   9147:                     $translation{$1} = $newid;
                   9148:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   9149:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   9150:                     $translation{$1} = $newid;
                   9151:                 }
1.749     raeburn  9152:                 $new_values{$file_name."\0".$newkey} = 
                   9153:                                           $$changes{'activate'}{$newitems[$i]};
                   9154:                 $new_control{$newkey} = $now;
                   9155:             }
                   9156:         }
                   9157:     }
                   9158:     my %todelete;
                   9159:     my %changed_items;
                   9160:     foreach my $action ('delete','update') {
                   9161:         if (exists($$changes{$action})) {
                   9162:             if (ref($$changes{$action}) eq 'HASH') {
                   9163:                 foreach my $key (keys(%{$$changes{$action}})) {
                   9164:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   9165:                     if ($action eq 'delete') { 
                   9166:                         $todelete{$itemnum} = 1;
                   9167:                     } else {
                   9168:                         $changed_items{$itemnum} = $key;
                   9169:                     }
                   9170:                 }
1.745     raeburn  9171:             }
                   9172:         }
1.749     raeburn  9173:     }
                   9174:     # get lock on access controls for file.
                   9175:     my $lockhash = {
                   9176:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   9177:                                                        ':'.$env{'user.domain'},
                   9178:                    }; 
                   9179:     my $tries = 0;
                   9180:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9181:    
                   9182:     while (($gotlock ne 'ok') && $tries <3) {
                   9183:         $tries ++;
                   9184:         sleep 1;
                   9185:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9186:     }
                   9187:     if ($gotlock eq 'ok') {
                   9188:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   9189:         my ($tmp)=keys(%curr_permissions);
                   9190:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   9191:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   9192:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   9193:             if (ref($curr_controls) eq 'HASH') {
                   9194:                 foreach my $control_item (keys(%{$curr_controls})) {
                   9195:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   9196:                     if (defined($todelete{$itemnum})) {
                   9197:                         push(@deletions,$file_name."\0".$control_item);
                   9198:                     } else {
                   9199:                         if (defined($changed_items{$itemnum})) {
                   9200:                             $new_control{$changed_items{$itemnum}} = $now;
                   9201:                             push(@deletions,$file_name."\0".$control_item);
                   9202:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   9203:                         } else {
                   9204:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   9205:                         }
                   9206:                     }
1.745     raeburn  9207:                 }
                   9208:             }
                   9209:         }
1.970     raeburn  9210:         my ($group);
                   9211:         if (&is_course($domain,$user)) {
                   9212:             ($group,my $file) = split(/\//,$file_name,2);
                   9213:         }
1.749     raeburn  9214:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   9215:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   9216:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   9217:         #  remove lock
                   9218:         my @del_lock = ($file_name."\0".'locked_access_records');
                   9219:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  9220:         my $sqlresult =
1.970     raeburn  9221:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  9222:                                     $group);
1.749     raeburn  9223:     } else {
                   9224:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  9225:     }
1.749     raeburn  9226:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  9227: }
                   9228: 
1.827     raeburn  9229: sub make_public_indefinitely {
                   9230:     my ($requrl) = @_;
                   9231:     my $now = time;
                   9232:     my $action = 'activate';
                   9233:     my $aclnum = 0;
                   9234:     if (&is_portfolio_url($requrl)) {
                   9235:         my (undef,$udom,$unum,$file_name,$group) =
                   9236:             &parse_portfolio_url($requrl);
                   9237:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   9238:         my %access_controls = &get_access_controls($current_perms,
                   9239:                                                    $group,$file_name);
                   9240:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   9241:             my ($num,$scope,$end,$start) = 
                   9242:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   9243:             if ($scope eq 'public') {
                   9244:                 if ($start <= $now && $end == 0) {
                   9245:                     $action = 'none';
                   9246:                 } else {
                   9247:                     $action = 'update';
                   9248:                     $aclnum = $num;
                   9249:                 }
                   9250:                 last;
                   9251:             }
                   9252:         }
                   9253:         if ($action eq 'none') {
                   9254:              return 'ok';
                   9255:         } else {
                   9256:             my %changes;
                   9257:             my $newend = 0;
                   9258:             my $newstart = $now;
                   9259:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   9260:             $changes{$action}{$newkey} = {
                   9261:                 type => 'public',
                   9262:                 time => {
                   9263:                     start => $newstart,
                   9264:                     end   => $newend,
                   9265:                 },
                   9266:             };
                   9267:             my ($outcome,$deloutcome,$new_values,$translation) =
                   9268:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   9269:             return $outcome;
                   9270:         }
                   9271:     } else {
                   9272:         return 'invalid';
                   9273:     }
                   9274: }
                   9275: 
1.745     raeburn  9276: #------------------------------------------------------Get Marked as Read Only
                   9277: 
                   9278: sub get_marked_as_readonly {
                   9279:     my ($domain,$user,$what,$group) = @_;
                   9280:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 9281:     my @readonly_files;
1.629     banghart 9282:     my $cmp1=$what;
                   9283:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  9284:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9285:         if (defined($group)) {
                   9286:             if ($file_name !~ m-^\Q$group\E/-) {
                   9287:                 next;
                   9288:             }
                   9289:         }
1.561     banghart 9290:         if (ref($value) eq "ARRAY"){
                   9291:             foreach my $stored_what (@{$value}) {
1.629     banghart 9292:                 my $cmp2=$stored_what;
1.759     albertel 9293:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  9294:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  9295:                 }
1.629     banghart 9296:                 if ($cmp1 eq $cmp2) {
1.561     banghart 9297:                     push(@readonly_files, $file_name);
1.745     raeburn  9298:                     last;
1.563     banghart 9299:                 } elsif (!defined($what)) {
                   9300:                     push(@readonly_files, $file_name);
1.745     raeburn  9301:                     last;
1.561     banghart 9302:                 }
                   9303:             }
1.745     raeburn  9304:         }
1.561     banghart 9305:     }
                   9306:     return @readonly_files;
                   9307: }
1.577     banghart 9308: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 9309: 
1.577     banghart 9310: sub get_marked_as_readonly_hash {
1.745     raeburn  9311:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 9312:     my %readonly_files;
1.745     raeburn  9313:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9314:         if (defined($group)) {
                   9315:             if ($file_name !~ m-^\Q$group\E/-) {
                   9316:                 next;
                   9317:             }
                   9318:         }
1.577     banghart 9319:         if (ref($value) eq "ARRAY"){
                   9320:             foreach my $stored_what (@{$value}) {
1.745     raeburn  9321:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 9322:                     foreach my $lock_descriptor(@{$stored_what}) {
                   9323:                         if ($lock_descriptor eq 'graded') {
                   9324:                             $readonly_files{$file_name} = 'graded';
                   9325:                         } elsif ($lock_descriptor eq 'handback') {
                   9326:                             $readonly_files{$file_name} = 'handback';
                   9327:                         } else {
                   9328:                             if (!exists($readonly_files{$file_name})) {
                   9329:                                 $readonly_files{$file_name} = 'locked';
                   9330:                             }
                   9331:                         }
1.745     raeburn  9332:                     }
1.750     banghart 9333:                 } 
1.577     banghart 9334:             }
                   9335:         } 
                   9336:     }
                   9337:     return %readonly_files;
                   9338: }
1.559     banghart 9339: # ------------------------------------------------------------ Unmark as Read Only
                   9340: 
                   9341: sub unmark_as_readonly {
1.629     banghart 9342:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   9343:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  9344:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 9345:     $file_name = &declutter_portfile($file_name);
1.634     albertel 9346:     my $symb_crs = $what;
                   9347:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  9348:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 9349:     my ($tmp)=keys(%current_permissions);
                   9350:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9351:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 9352:     foreach my $file (@readonly_files) {
1.759     albertel 9353: 	my $clean_file = &declutter_portfile($file);
                   9354: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 9355: 	my $current_locks = $current_permissions{$file};
1.563     banghart 9356:         my @new_locks;
                   9357:         my @del_keys;
                   9358:         if (ref($current_locks) eq "ARRAY"){
                   9359:             foreach my $locker (@{$current_locks}) {
1.632     albertel 9360:                 my $compare=$locker;
1.749     raeburn  9361:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  9362:                     $compare=join('',@{$locker});
1.746     raeburn  9363:                     if ($compare ne $symb_crs) {
                   9364:                         push(@new_locks, $locker);
                   9365:                     }
1.563     banghart 9366:                 }
                   9367:             }
1.650     albertel 9368:             if (scalar(@new_locks) > 0) {
1.563     banghart 9369:                 $current_permissions{$file} = \@new_locks;
                   9370:             } else {
                   9371:                 push(@del_keys, $file);
1.613     albertel 9372:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 9373:                 delete($current_permissions{$file});
1.563     banghart 9374:             }
                   9375:         }
1.561     banghart 9376:     }
1.613     albertel 9377:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9378:     return;
                   9379: }
1.512     banghart 9380: 
1.17      www      9381: # ------------------------------------------------------------ Directory lister
                   9382: 
                   9383: sub dirlist {
1.955     raeburn  9384:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      9385:     $uri=~s/^\///;
                   9386:     $uri=~s/\/$//;
1.253     stredwic 9387:     my ($udom, $uname);
1.955     raeburn  9388:     if ($getuserdir) {
1.253     stredwic 9389:         $udom = $userdomain;
                   9390:         $uname = $username;
1.955     raeburn  9391:     } else {
                   9392:         (undef,$udom,$uname)=split(/\//,$uri);
                   9393:         if(defined($userdomain)) {
                   9394:             $udom = $userdomain;
                   9395:         }
                   9396:         if(defined($username)) {
                   9397:             $uname = $username;
                   9398:         }
1.253     stredwic 9399:     }
1.955     raeburn  9400:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 9401: 
1.955     raeburn  9402:     $dirRoot = $perlvar{'lonDocRoot'};
                   9403:     if (defined($getpropath)) {
                   9404:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 9405:         $dirRoot =~ s/\/$//;
1.955     raeburn  9406:     } elsif (defined($getuserdir)) {
                   9407:         my $subdir=$uname.'__';
                   9408:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   9409:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   9410:                    ."/$udom/$subdir/$uname";
                   9411:     } elsif (defined($alternateRoot)) {
                   9412:         $dirRoot = $alternateRoot;
1.751     banghart 9413:     }
1.253     stredwic 9414: 
                   9415:     if($udom) {
                   9416:         if($uname) {
1.1135    raeburn  9417:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  9418:             if ($uhome eq 'no_host') {
                   9419:                 return ([],'no_host');
                   9420:             }
1.955     raeburn  9421:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  9422:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  9423:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  9424:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9425:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  9426:             } else {
                   9427:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9428:             }
1.605     matthew  9429:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9430:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  9431:                 @listing_results = split(/:/,$listing);
                   9432:             } else {
                   9433:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9434:             }
1.1135    raeburn  9435:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  9436:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9437:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9438:                 return ([],$listing);
                   9439:             } else {
                   9440:                 return (\@listing_results);
1.1135    raeburn  9441:             }
1.955     raeburn  9442:         } elsif(!$alternateRoot) {
1.1136    raeburn  9443:             my (%allusers,%listerror);
1.841     albertel 9444: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  9445:  	    foreach my $tryserver (keys(%servers)) {
                   9446:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   9447:                                   &escape($udom),$tryserver);
                   9448:                 if ($listing eq 'unknown_cmd') {
                   9449: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9450: 				      $udom, $tryserver);
                   9451:                 } else {
                   9452:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9453:                 }
1.841     albertel 9454: 		if ($listing eq 'unknown_cmd') {
                   9455: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9456: 				      $udom, $tryserver);
                   9457: 		    @listing_results = split(/:/,$listing);
                   9458: 		} else {
                   9459: 		    @listing_results =
                   9460: 			map { &unescape($_); } split(/:/,$listing);
                   9461: 		}
1.1136    raeburn  9462:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   9463:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9464:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9465:                     $listerror{$tryserver} = $listing;
                   9466:                 } else {
1.841     albertel 9467: 		    foreach my $line (@listing_results) {
                   9468: 			my ($entry) = split(/&/,$line,2);
                   9469: 			$allusers{$entry} = 1;
                   9470: 		    }
                   9471: 		}
1.253     stredwic 9472:             }
1.1136    raeburn  9473:             my @alluserslist=();
1.800     albertel 9474:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  9475:                 push(@alluserslist,$user.'&user');
1.253     stredwic 9476:             }
1.1136    raeburn  9477:             return (\@alluserslist);
1.253     stredwic 9478:         } else {
1.1136    raeburn  9479:             return ([],'missing username');
1.253     stredwic 9480:         }
1.955     raeburn  9481:     } elsif(!defined($getpropath)) {
1.1136    raeburn  9482:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   9483:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   9484:         return (\@all_domains);
1.955     raeburn  9485:     } else {
1.1136    raeburn  9486:         return ([],'missing domain');
1.275     stredwic 9487:     }
                   9488: }
                   9489: 
                   9490: # --------------------------------------------- GetFileTimestamp
                   9491: # This function utilizes dirlist and returns the date stamp for
                   9492: # when it was last modified.  It will also return an error of -1
                   9493: # if an error occurs
                   9494: 
                   9495: sub GetFileTimestamp {
1.955     raeburn  9496:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 9497:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   9498:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  9499:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   9500:                                     undef,$getuserdir);
                   9501:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9502:         return -1;
                   9503:     }
                   9504:     if (ref($fileref) eq 'ARRAY') {
                   9505:         my @stats = split('&',$fileref->[0]);
1.375     matthew  9506:         # @stats contains first the filename, then the stat output
                   9507:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 9508:     } else {
                   9509:         return -1;
1.253     stredwic 9510:     }
1.26      www      9511: }
                   9512: 
1.712     albertel 9513: sub stat_file {
                   9514:     my ($uri) = @_;
1.787     albertel 9515:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 9516: 
1.955     raeburn  9517:     my ($udom,$uname,$file);
1.712     albertel 9518:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   9519: 	($udom,$uname,$file) =
1.811     albertel 9520: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 9521: 	$file = 'userfiles/'.$file;
                   9522:     }
                   9523:     if ($uri =~ m-^/res/-) {
                   9524: 	($udom,$uname) = 
1.807     albertel 9525: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 9526: 	$file = $uri;
                   9527:     }
                   9528: 
                   9529:     if (!$udom || !$uname || !$file) {
                   9530: 	# unable to handle the uri
                   9531: 	return ();
                   9532:     }
1.956     raeburn  9533:     my $getpropath;
                   9534:     if ($file =~ /^userfiles\//) {
                   9535:         $getpropath = 1;
                   9536:     }
1.1136    raeburn  9537:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   9538:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9539:         return ();
                   9540:     } else {
                   9541:         if (ref($listref) eq 'ARRAY') {
                   9542:             my @stats = split('&',$listref->[0]);
                   9543: 	    shift(@stats); #filename is first
                   9544: 	    return @stats;
                   9545:         }
1.712     albertel 9546:     }
                   9547:     return ();
                   9548: }
                   9549: 
1.26      www      9550: # -------------------------------------------------------- Value of a Condition
                   9551: 
1.713     albertel 9552: # gets the value of a specific preevaluated condition
                   9553: #    stored in the string  $env{user.state.<cid>}
                   9554: # or looks up a condition reference in the bighash and if if hasn't
                   9555: # already been evaluated recurses into docondval to get the value of
                   9556: # the condition, then memoizing it to 
                   9557: #   $env{user.state.<cid>.<condition>}
1.40      www      9558: sub directcondval {
                   9559:     my $number=shift;
1.620     albertel 9560:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 9561: 	&Apache::lonuserstate::evalstate();
                   9562:     }
1.713     albertel 9563:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   9564: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   9565:     } elsif ($number =~ /^_/) {
                   9566: 	my $sub_condition;
                   9567: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   9568: 		&GDBM_READER(),0640)) {
                   9569: 	    $sub_condition=$bighash{'conditions'.$number};
                   9570: 	    untie(%bighash);
                   9571: 	}
                   9572: 	my $value = &docondval($sub_condition);
1.949     raeburn  9573: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 9574: 	return $value;
                   9575:     }
1.620     albertel 9576:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   9577:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      9578:     } else {
                   9579:        return 2;
                   9580:     }
                   9581: }
                   9582: 
1.713     albertel 9583: # get the collection of conditions for this resource
1.26      www      9584: sub condval {
                   9585:     my $condidx=shift;
1.54      www      9586:     my $allpathcond='';
1.713     albertel 9587:     foreach my $cond (split(/\|/,$condidx)) {
                   9588: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   9589: 	    $allpathcond.=
                   9590: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   9591: 	}
1.191     harris41 9592:     }
1.54      www      9593:     $allpathcond=~s/\|$//;
1.713     albertel 9594:     return &docondval($allpathcond);
                   9595: }
                   9596: 
                   9597: #evaluates an expression of conditions
                   9598: sub docondval {
                   9599:     my ($allpathcond) = @_;
                   9600:     my $result=0;
                   9601:     if ($env{'request.course.id'}
                   9602: 	&& defined($allpathcond)) {
                   9603: 	my $operand='|';
                   9604: 	my @stack;
                   9605: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   9606: 	    if ($chunk eq '(') {
                   9607: 		push @stack,($operand,$result);
                   9608: 	    } elsif ($chunk eq ')') {
                   9609: 		my $before=pop @stack;
                   9610: 		if (pop @stack eq '&') {
                   9611: 		    $result=$result>$before?$before:$result;
                   9612: 		} else {
                   9613: 		    $result=$result>$before?$result:$before;
                   9614: 		}
                   9615: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   9616: 		$operand=$chunk;
                   9617: 	    } else {
                   9618: 		my $new=directcondval($chunk);
                   9619: 		if ($operand eq '&') {
                   9620: 		    $result=$result>$new?$new:$result;
                   9621: 		} else {
                   9622: 		    $result=$result>$new?$result:$new;
                   9623: 		}
                   9624: 	    }
                   9625: 	}
1.26      www      9626:     }
                   9627:     return $result;
1.421     albertel 9628: }
                   9629: 
                   9630: # ---------------------------------------------------- Devalidate courseresdata
                   9631: 
                   9632: sub devalidatecourseresdata {
                   9633:     my ($coursenum,$coursedomain)=@_;
                   9634:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9635:     &devalidate_cache_new('courseres',$hashid);
1.28      www      9636: }
                   9637: 
1.763     www      9638: 
1.200     www      9639: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     9640: #
                   9641: #  Parameters:
                   9642: #      $coursenum    - Number of the course.
                   9643: #      $coursedomain - Domain at which the course was created.
                   9644: #  Returns:
                   9645: #     A hash of the course parameters along (I think) with timestamps
                   9646: #     and version info.
1.877     foxr     9647: 
1.624     albertel 9648: sub get_courseresdata {
                   9649:     my ($coursenum,$coursedomain)=@_;
1.200     www      9650:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   9651:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9652:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 9653:     my %dumpreply;
1.417     albertel 9654:     unless (defined($cached)) {
1.624     albertel 9655: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 9656: 	$result=\%dumpreply;
1.251     albertel 9657: 	my ($tmp) = keys(%dumpreply);
                   9658: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 9659: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 9660: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   9661: 	    return $tmp;
1.416     albertel 9662: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 9663: 	    $result=undef;
1.599     albertel 9664: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 9665: 	}
                   9666:     }
1.624     albertel 9667:     return $result;
                   9668: }
                   9669: 
1.633     albertel 9670: sub devalidateuserresdata {
                   9671:     my ($uname,$udom)=@_;
                   9672:     my $hashid="$udom:$uname";
                   9673:     &devalidate_cache_new('userres',$hashid);
                   9674: }
                   9675: 
1.624     albertel 9676: sub get_userresdata {
                   9677:     my ($uname,$udom)=@_;
                   9678:     #most student don\'t have any data set, check if there is some data
                   9679:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   9680: 
                   9681:     my $hashid="$udom:$uname";
                   9682:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   9683:     if (!defined($cached)) {
                   9684: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   9685: 	$result=\%resourcedata;
                   9686: 	&do_cache_new('userres',$hashid,$result,600);
                   9687:     }
                   9688:     my ($tmp)=keys(%$result);
                   9689:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   9690: 	return $result;
                   9691:     }
                   9692:     #error 2 occurs when the .db doesn't exist
                   9693:     if ($tmp!~/error: 2 /) {
1.672     albertel 9694: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 9695: 		 " Trying to get resource data for ".
                   9696: 		 $uname." at ".$udom.": ".
                   9697: 		 $tmp."</font>");
                   9698:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 9699: 	#&EXT_cache_set($udom,$uname);
                   9700: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 9701: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 9702:     }
                   9703:     return $tmp;
                   9704: }
1.879     foxr     9705: #----------------------------------------------- resdata - return resource data
                   9706: #  Purpose:
                   9707: #    Return resource data for either users or for a course.
                   9708: #  Parameters:
                   9709: #     $name      - Course/user name.
                   9710: #     $domain    - Name of the domain the user/course is registered on.
                   9711: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   9712: #     @which     - Array of names of resources desired.
                   9713: #  Returns:
                   9714: #     The value of the first reasource in @which that is found in the
                   9715: #     resource hash.
                   9716: #  Exceptional Conditions:
                   9717: #     If the $type passed in is not valid (not the string 'course' or 
                   9718: #     'user', an undefined  reference is returned.
                   9719: #     If none of the resources are found, an undef is returned
1.624     albertel 9720: sub resdata {
                   9721:     my ($name,$domain,$type,@which)=@_;
                   9722:     my $result;
                   9723:     if ($type eq 'course') {
                   9724: 	$result=&get_courseresdata($name,$domain);
                   9725:     } elsif ($type eq 'user') {
                   9726: 	$result=&get_userresdata($name,$domain);
                   9727:     }
                   9728:     if (!ref($result)) { return $result; }    
1.251     albertel 9729:     foreach my $item (@which) {
1.927     albertel 9730: 	if (defined($result->{$item->[0]})) {
                   9731: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 9732: 	}
1.250     albertel 9733:     }
1.291     albertel 9734:     return undef;
1.200     www      9735: }
                   9736: 
1.1172.2.31  raeburn  9737: sub get_numsuppfiles {
                   9738:     my ($cnum,$cdom,$ignorecache)=@_;
                   9739:     my $hashid=$cnum.':'.$cdom;
                   9740:     my ($suppcount,$cached);
                   9741:     unless ($ignorecache) {
                   9742:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   9743:     }
                   9744:     unless (defined($cached)) {
                   9745:         my $chome=&homeserver($cnum,$cdom);
                   9746:         unless ($chome eq 'no_host') {
                   9747:             ($suppcount,my $errors) = (0,0);
                   9748:             my $suppmap = 'supplemental.sequence';
                   9749:             ($suppcount,$errors) =
                   9750:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   9751:         }
                   9752:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   9753:     }
                   9754:     return $suppcount;
                   9755: }
                   9756: 
1.379     matthew  9757: #
                   9758: # EXT resource caching routines
                   9759: #
                   9760: 
                   9761: sub clear_EXT_cache_status {
1.383     albertel 9762:     &delenv('cache.EXT.');
1.379     matthew  9763: }
                   9764: 
                   9765: sub EXT_cache_status {
                   9766:     my ($target_domain,$target_user) = @_;
1.383     albertel 9767:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 9768:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  9769:         # We know already the user has no data
                   9770:         return 1;
                   9771:     } else {
                   9772:         return 0;
                   9773:     }
                   9774: }
                   9775: 
                   9776: sub EXT_cache_set {
                   9777:     my ($target_domain,$target_user) = @_;
1.383     albertel 9778:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  9779:     #&appenv({$cachename => time});
1.379     matthew  9780: }
                   9781: 
1.28      www      9782: # --------------------------------------------------------- Value of a Variable
1.58      www      9783: sub EXT {
1.715     albertel 9784: 
1.1172.2.28  raeburn  9785:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      9786:     unless ($varname) { return ''; }
1.218     albertel 9787:     #get real user name/domain, courseid and symb
                   9788:     my $courseid;
1.359     albertel 9789:     my $publicuser;
1.427     www      9790:     if ($symbparm) {
                   9791: 	$symbparm=&get_symb_from_alias($symbparm);
                   9792:     }
1.218     albertel 9793:     if (!($uname && $udom)) {
1.790     albertel 9794:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 9795:       if (!$symbparm) {	$symbparm=$cursymb; }
                   9796:     } else {
1.620     albertel 9797: 	$courseid=$env{'request.course.id'};
1.218     albertel 9798:     }
1.48      www      9799:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   9800:     my $rest;
1.320     albertel 9801:     if (defined($therest[0])) {
1.48      www      9802:        $rest=join('.',@therest);
                   9803:     } else {
                   9804:        $rest='';
                   9805:     }
1.320     albertel 9806: 
1.57      www      9807:     my $qualifierrest=$qualifier;
                   9808:     if ($rest) { $qualifierrest.='.'.$rest; }
                   9809:     my $spacequalifierrest=$space;
                   9810:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      9811:     if ($realm eq 'user') {
1.48      www      9812: # --------------------------------------------------------------- user.resource
                   9813: 	if ($space eq 'resource') {
1.651     albertel 9814: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   9815: 		  || defined($Apache::lonhomework::parsing_a_task))
                   9816: 		 &&
1.744     albertel 9817: 		 ($symbparm eq &symbread()) ) {	
                   9818: 		# if we are in the middle of processing the resource the
                   9819: 		# get the value we are planning on committing
                   9820:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   9821:                     return $Apache::lonhomework::results{$qualifierrest};
                   9822:                 } else {
                   9823:                     return $Apache::lonhomework::history{$qualifierrest};
                   9824:                 }
1.335     albertel 9825: 	    } else {
1.359     albertel 9826: 		my %restored;
1.620     albertel 9827: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 9828: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   9829: 		} else {
                   9830: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   9831: 		}
1.335     albertel 9832: 		return $restored{$qualifierrest};
                   9833: 	    }
1.48      www      9834: # ----------------------------------------------------------------- user.access
                   9835:         } elsif ($space eq 'access') {
1.218     albertel 9836: 	    # FIXME - not supporting calls for a specific user
1.48      www      9837:             return &allowed($qualifier,$rest);
                   9838: # ------------------------------------------ user.preferences, user.environment
                   9839:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 9840: 	    if (($uname eq $env{'user.name'}) &&
                   9841: 		($udom eq $env{'user.domain'})) {
                   9842: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 9843: 	    } else {
1.359     albertel 9844: 		my %returnhash;
                   9845: 		if (!$publicuser) {
                   9846: 		    %returnhash=&userenvironment($udom,$uname,
                   9847: 						 $qualifierrest);
                   9848: 		}
1.218     albertel 9849: 		return $returnhash{$qualifierrest};
                   9850: 	    }
1.48      www      9851: # ----------------------------------------------------------------- user.course
                   9852:         } elsif ($space eq 'course') {
1.218     albertel 9853: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9854:             return $env{join('.',('request.course',$qualifier))};
1.48      www      9855: # ------------------------------------------------------------------- user.role
                   9856:         } elsif ($space eq 'role') {
1.218     albertel 9857: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9858:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      9859:             if ($qualifier eq 'value') {
                   9860: 		return $role;
                   9861:             } elsif ($qualifier eq 'extent') {
                   9862:                 return $where;
                   9863:             }
                   9864: # ----------------------------------------------------------------- user.domain
                   9865:         } elsif ($space eq 'domain') {
1.218     albertel 9866:             return $udom;
1.48      www      9867: # ------------------------------------------------------------------- user.name
                   9868:         } elsif ($space eq 'name') {
1.218     albertel 9869:             return $uname;
1.48      www      9870: # ---------------------------------------------------- Any other user namespace
1.29      www      9871:         } else {
1.359     albertel 9872: 	    my %reply;
                   9873: 	    if (!$publicuser) {
                   9874: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   9875: 	    }
                   9876: 	    return $reply{$qualifierrest};
1.48      www      9877:         }
1.236     www      9878:     } elsif ($realm eq 'query') {
                   9879: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 9880:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   9881: 						[$spacequalifierrest]);
1.620     albertel 9882: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      9883:    } elsif ($realm eq 'request') {
1.48      www      9884: # ------------------------------------------------------------- request.browser
                   9885:         if ($space eq 'browser') {
1.1145    bisitz   9886:             return $env{'browser.'.$qualifier};
1.57      www      9887: # ------------------------------------------------------------ request.filename
                   9888:         } else {
1.620     albertel 9889:             return $env{'request.'.$spacequalifierrest};
1.29      www      9890:         }
1.28      www      9891:     } elsif ($realm eq 'course') {
1.48      www      9892: # ---------------------------------------------------------- course.description
1.620     albertel 9893:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      9894:     } elsif ($realm eq 'resource') {
1.165     www      9895: 
1.620     albertel 9896: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 9897: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   9898: 	}
1.693     albertel 9899: 
1.1172.2.30  raeburn  9900:         if ($qualifier eq '') {
                   9901: 	    if ($space eq 'title') {
                   9902: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   9903: 	        return &gettitle($symbparm);
                   9904: 	    }
1.693     albertel 9905: 	
1.1172.2.30  raeburn  9906: 	    if ($space eq 'map') {
                   9907: 	        my ($map) = &decode_symb($symbparm);
                   9908: 	        return &symbread($map);
                   9909: 	    }
                   9910:             if ($space eq 'maptitle') {
                   9911:                 my ($map) = &decode_symb($symbparm);
                   9912:                 return &gettitle($map);
                   9913:             }
                   9914: 	    if ($space eq 'filename') {
                   9915: 	        if ($symbparm) {
                   9916: 		    return &clutter((&decode_symb($symbparm))[2]);
                   9917: 	        }
                   9918: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 9919: 	    }
1.1172.2.30  raeburn  9920: 
                   9921:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   9922:                 if ($space eq 'visibleparts') {
                   9923:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   9924:                     my $item;
                   9925:                     if (ref($navmap)) {
                   9926:                         my $res = $navmap->getBySymb($symbparm);
                   9927:                         my $parts = $res->parts();
                   9928:                         if (ref($parts) eq 'ARRAY') {
                   9929:                             $item = join(',',@{$parts});
                   9930:                         }
                   9931:                         undef($navmap);
                   9932:                     }
                   9933:                     return $item;
                   9934:                 }
                   9935:             }
                   9936:         }
1.693     albertel 9937: 
                   9938: 	my ($section, $group, @groups);
1.593     albertel 9939: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  9940:         if (($courseid eq '') && ($cid)) {
                   9941:             $courseid = $cid;
                   9942:         }
                   9943: 	if (($symbparm && $courseid) && 
                   9944: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      9945: 
1.218     albertel 9946: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      9947: 
1.60      www      9948: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 9949: 	    my $symbp=$symbparm;
1.735     albertel 9950: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 9951: 
                   9952: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   9953: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   9954: 
1.620     albertel 9955: 	    if (($env{'user.name'} eq $uname) &&
                   9956: 		($env{'user.domain'} eq $udom)) {
                   9957: 		$section=$env{'request.course.sec'};
1.733     raeburn  9958:                 @groups = split(/:/,$env{'request.course.groups'});  
                   9959:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 9960: 	    } else {
1.539     albertel 9961: 		if (! defined($usection)) {
1.551     albertel 9962: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 9963: 		} else {
                   9964: 		    $section = $usection;
                   9965: 		}
1.733     raeburn  9966:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 9967: 	    }
                   9968: 
                   9969: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   9970: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   9971: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   9972: 
1.593     albertel 9973: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 9974: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 9975: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      9976: 
1.60      www      9977: # ----------------------------------------------------------- first, check user
1.624     albertel 9978: 
                   9979: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 9980: 				       ([$courselevelr,'resource'],
                   9981: 					[$courselevelm,'map'     ],
                   9982: 					[$courselevel, 'course'  ]));
1.931     albertel 9983: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      9984: 
1.594     albertel 9985: # ------------------------------------------------ second, check some of course
1.684     raeburn  9986:             my $coursereply;
1.691     raeburn  9987:             if (@groups > 0) {
                   9988:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   9989:                                        $mapparm,$spacequalifierrest);
1.927     albertel 9990:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  9991:             }
1.96      www      9992: 
1.684     raeburn  9993: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 9994: 				  $env{'course.'.$courseid.'.domain'},
                   9995: 				  'course',
                   9996: 				  ([$seclevelr,   'resource'],
                   9997: 				   [$seclevelm,   'map'     ],
                   9998: 				   [$seclevel,    'course'  ],
                   9999: 				   [$courselevelr,'resource']));
                   10000: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      10001: 
1.60      www      10002: # ------------------------------------------------------ third, check map parms
1.218     albertel 10003: 	    my %parmhash=();
                   10004: 	    my $thisparm='';
                   10005: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 10006: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 10007: 		    &GDBM_READER(),0640)) {
1.218     albertel 10008: 		$thisparm=$parmhash{$symbparm};
                   10009: 		untie(%parmhash);
                   10010: 	    }
1.927     albertel 10011: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 10012: 	}
1.594     albertel 10013: # ------------------------------------------ fourth, look in resource metadata
1.71      www      10014: 
1.218     albertel 10015: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 10016: 	my $filename;
                   10017: 	if (!$symbparm) { $symbparm=&symbread(); }
                   10018: 	if ($symbparm) {
1.409     www      10019: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 10020: 	} else {
1.620     albertel 10021: 	    $filename=$env{'request.filename'};
1.282     albertel 10022: 	}
                   10023: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 10024: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 10025: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 10026: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      10027: 
1.927     albertel 10028: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 10029: 	if ($symbparm && defined($courseid) && 
1.620     albertel 10030: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 10031: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   10032: 				     $env{'course.'.$courseid.'.domain'},
                   10033: 				     'course',
1.927     albertel 10034: 				     ([$courselevelm,'map'   ],
                   10035: 				      [$courselevel, 'course']));
                   10036: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 10037: 	}
1.145     www      10038: # ------------------------------------------------------------------ Cascade up
1.218     albertel 10039: 	unless ($space eq '0') {
1.336     albertel 10040: 	    my @parts=split(/_/,$space);
                   10041: 	    my $id=pop(@parts);
                   10042: 	    my $part=join('_',@parts);
                   10043: 	    if ($part eq '') { $part='0'; }
1.927     albertel 10044: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 10045: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  10046: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 10047: 	}
1.395     albertel 10048: 	if ($recurse) { return undef; }
                   10049: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 10050: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      10051: # ---------------------------------------------------- Any other user namespace
                   10052:     } elsif ($realm eq 'environment') {
                   10053: # ----------------------------------------------------------------- environment
1.620     albertel 10054: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   10055: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 10056: 	} else {
1.770     albertel 10057: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   10058: 		return '';
                   10059: 	    }
1.219     albertel 10060: 	    my %returnhash=&userenvironment($udom,$uname,
                   10061: 					    $spacequalifierrest);
                   10062: 	    return $returnhash{$spacequalifierrest};
                   10063: 	}
1.28      www      10064:     } elsif ($realm eq 'system') {
1.48      www      10065: # ----------------------------------------------------------------- system.time
                   10066: 	if ($space eq 'time') {
                   10067: 	    return time;
                   10068:         }
1.696     albertel 10069:     } elsif ($realm eq 'server') {
                   10070: # ----------------------------------------------------------------- system.time
                   10071: 	if ($space eq 'name') {
                   10072: 	    return $ENV{'SERVER_NAME'};
                   10073:         }
1.28      www      10074:     }
1.48      www      10075:     return '';
1.61      www      10076: }
                   10077: 
1.927     albertel 10078: sub get_reply {
                   10079:     my ($reply_value) = @_;
1.940     raeburn  10080:     if (ref($reply_value) eq 'ARRAY') {
                   10081:         if (wantarray) {
                   10082: 	    return @$reply_value;
                   10083:         }
                   10084:         return $reply_value->[0];
                   10085:     } else {
                   10086:         return $reply_value;
1.927     albertel 10087:     }
                   10088: }
                   10089: 
1.691     raeburn  10090: sub check_group_parms {
                   10091:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   10092:     my @groupitems = ();
                   10093:     my $resultitem;
1.927     albertel 10094:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  10095:     foreach my $group (@{$groups}) {
                   10096:         foreach my $level (@levels) {
1.927     albertel 10097:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   10098:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  10099:         }
                   10100:     }
                   10101:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   10102:                             $env{'course.'.$courseid.'.domain'},
                   10103:                                      'course',@groupitems);
                   10104:     return $coursereply;
                   10105: }
                   10106: 
                   10107: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  10108:     my ($courseid,@groups) = @_;
                   10109:     @groups = sort(@groups);
1.691     raeburn  10110:     return @groups;
                   10111: }
                   10112: 
1.395     albertel 10113: sub packages_tab_default {
                   10114:     my ($uri,$varname)=@_;
                   10115:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 10116: 
                   10117:     my (@extension,@specifics,$do_default);
                   10118:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 10119: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 10120: 	if ($pack_type eq 'default') {
                   10121: 	    $do_default=1;
                   10122: 	} elsif ($pack_type eq 'extension') {
                   10123: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 10124: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 10125: 	    # only look at packages defaults for packages that this id is
1.738     albertel 10126: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   10127: 	}
                   10128:     }
                   10129:     # first look for a package that matches the requested part id
                   10130:     foreach my $package (@specifics) {
                   10131: 	my (undef,$pack_type,$pack_part)=@{$package};
                   10132: 	next if ($pack_part ne $part);
                   10133: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10134: 	    return $packagetab{"$pack_type&$name&default"};
                   10135: 	}
                   10136:     }
                   10137:     # look for any possible matching non extension_ package
                   10138:     foreach my $package (@specifics) {
                   10139: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 10140: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10141: 	    return $packagetab{"$pack_type&$name&default"};
                   10142: 	}
1.585     albertel 10143: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 10144: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   10145: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 10146: 	}
                   10147:     }
1.738     albertel 10148:     # look for any posible extension_ match
                   10149:     foreach my $package (@extension) {
                   10150: 	my ($package,$pack_type)=@{$package};
                   10151: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10152: 	    return $packagetab{"$pack_type&$name&default"};
                   10153: 	}
                   10154: 	if (defined($packagetab{$package."&$name&default"})) {
                   10155: 	    return $packagetab{$package."&$name&default"};
                   10156: 	}
                   10157:     }
                   10158:     # look for a global default setting
                   10159:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   10160: 	return $packagetab{"default&$name&default"};
                   10161:     }
1.395     albertel 10162:     return undef;
                   10163: }
                   10164: 
1.334     albertel 10165: sub add_prefix_and_part {
                   10166:     my ($prefix,$part)=@_;
                   10167:     my $keyroot;
                   10168:     if (defined($prefix) && $prefix !~ /^__/) {
                   10169: 	# prefix that has a part already
                   10170: 	$keyroot=$prefix;
                   10171:     } elsif (defined($prefix)) {
                   10172: 	# prefix that is missing a part
                   10173: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   10174:     } else {
                   10175: 	# no prefix at all
                   10176: 	if (defined($part)) { $keyroot='_'.$part; }
                   10177:     }
                   10178:     return $keyroot;
                   10179: }
                   10180: 
1.71      www      10181: # ---------------------------------------------------------------- Get metadata
                   10182: 
1.599     albertel 10183: my %metaentry;
1.1070    www      10184: my %importedpartids;
1.71      www      10185: sub metadata {
1.176     www      10186:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      10187:     $uri=&declutter($uri);
1.288     albertel 10188:     # if it is a non metadata possible uri return quickly
1.529     albertel 10189:     if (($uri eq '') || 
                   10190: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.20  raeburn  10191: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108    raeburn  10192:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 10193: 	return undef;
                   10194:     }
1.1140    www      10195:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
1.924     albertel 10196: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 10197: 	return undef;
1.288     albertel 10198:     }
1.73      www      10199:     my $filename=$uri;
                   10200:     $uri=~s/\.meta$//;
1.172     www      10201: #
                   10202: # Is the metadata already cached?
1.177     www      10203: # Look at timestamp of caching
1.172     www      10204: # Everything is cached by the main uri, libraries are never directly cached
                   10205: #
1.428     albertel 10206:     if (!defined($liburi)) {
1.599     albertel 10207: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 10208: 	if (defined($cached)) { return $result->{':'.$what}; }
                   10209:     }
                   10210:     {
1.1069    www      10211: # Imported parts would go here
1.1070    www      10212:         my %importedids=();
                   10213:         my @origfileimportpartids=();
1.1069    www      10214:         my $importedparts=0;
1.172     www      10215: #
                   10216: # Is this a recursive call for a library?
                   10217: #
1.599     albertel 10218: #	if (! exists($metacache{$uri})) {
                   10219: #	    $metacache{$uri}={};
                   10220: #	}
1.924     albertel 10221: 	my $cachetime = 60*60;
1.171     www      10222:         if ($liburi) {
                   10223: 	    $liburi=&declutter($liburi);
                   10224:             $filename=$liburi;
1.401     bowersj2 10225:         } else {
1.599     albertel 10226: 	    &devalidate_cache_new('meta',$uri);
                   10227: 	    undef(%metaentry);
1.401     bowersj2 10228: 	}
1.140     www      10229:         my %metathesekeys=();
1.73      www      10230:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 10231: 	my $metastring;
1.1140    www      10232: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 10233: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 10234: 	    $metastring = 
1.929     albertel 10235: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 10236: 					  ('grade_target' => 'meta'));
                   10237: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  10238: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   10239:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 10240: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 10241: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 10242: 	    $metastring=&getfile($file);
1.489     albertel 10243: 	}
1.208     albertel 10244:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      10245:         my $token;
1.140     www      10246:         undef %metathesekeys;
1.71      www      10247:         while ($token=$parser->get_token) {
1.339     albertel 10248: 	    if ($token->[0] eq 'S') {
                   10249: 		if (defined($token->[2]->{'package'})) {
1.172     www      10250: #
                   10251: # This is a package - get package info
                   10252: #
1.339     albertel 10253: 		    my $package=$token->[2]->{'package'};
                   10254: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10255: 		    if (defined($token->[2]->{'id'})) { 
                   10256: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   10257: 		    }
1.599     albertel 10258: 		    if ($metaentry{':packages'}) {
                   10259: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 10260: 		    } else {
1.599     albertel 10261: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 10262: 		    }
1.736     albertel 10263: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 10264: 			my $part=$keyroot;
                   10265: 			$part=~s/^\_//;
1.736     albertel 10266: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   10267: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   10268: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 10269: 			    # ignore package.tab specified default values
                   10270:                             # here &package_tab_default() will fetch those
                   10271: 			    if ($subp eq 'default') { next; }
1.736     albertel 10272: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 10273: 			    my $unikey;
                   10274: 			    if ($pack =~ /_0$/) {
                   10275: 				$unikey='parameter_0_'.$name;
                   10276: 				$part=0;
                   10277: 			    } else {
                   10278: 				$unikey='parameter'.$keyroot.'_'.$name;
                   10279: 			    }
1.339     albertel 10280: 			    if ($subp eq 'display') {
                   10281: 				$value.=' [Part: '.$part.']';
                   10282: 			    }
1.599     albertel 10283: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 10284: 			    $metathesekeys{$unikey}=1;
1.599     albertel 10285: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10286: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 10287: 			    }
1.599     albertel 10288: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   10289: 				$metaentry{':'.$unikey}=
                   10290: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 10291: 			    }
1.339     albertel 10292: 			}
                   10293: 		    }
                   10294: 		} else {
1.172     www      10295: #
                   10296: # This is not a package - some other kind of start tag
1.339     albertel 10297: #
                   10298: 		    my $entry=$token->[1];
1.1068    www      10299: 		    my $unikey='';
1.175     www      10300: 
1.339     albertel 10301: 		    if ($entry eq 'import') {
1.175     www      10302: #
                   10303: # Importing a library here
1.339     albertel 10304: #
1.1067    www      10305:                         my $location=$parser->get_text('/import');
                   10306:                         my $dir=$filename;
                   10307:                         $dir=~s|[^/]*$||;
                   10308:                         $location=&filelocation($dir,$location);
1.1069    www      10309:                        
1.1068    www      10310:                         my $importmode=$token->[2]->{'importmode'};
                   10311:                         if ($importmode eq 'problem') {
1.1069    www      10312: # Import as problem/response
1.1068    www      10313:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10314:                         } elsif ($importmode eq 'part') {
                   10315: # Import as part(s)
1.1069    www      10316:                            $importedparts=1;
                   10317: # We need to get the original file and the imported file to get the part order correct
                   10318: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   10319: # Load and inspect original file
1.1070    www      10320:                            if ($#origfileimportpartids<0) {
                   10321:                               undef(%importedpartids);
                   10322:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   10323:                               my $origfile=&getfile($origfilelocation);
                   10324:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10325:                            }
                   10326: 
1.1069    www      10327: # Load and inspect imported file
                   10328:                            my $impfile=&getfile($location);
                   10329:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10330:                            if ($#impfilepartids>=0) {
                   10331: # This problem had parts
1.1070    www      10332:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      10333:                            } else {
                   10334: # Importing by turning a single problem into a problem part
                   10335: # It gets the import-tags ID as part-ID
                   10336:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      10337:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      10338:                            }
1.1068    www      10339:                         } else {
                   10340: # Normal import
                   10341:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10342:                            if (defined($token->[2]->{'id'})) {
                   10343:                               $unikey.='_'.$token->[2]->{'id'};
                   10344:                            }
1.1067    www      10345:                         }
                   10346: 
1.339     albertel 10347: 			if ($depthcount<20) {
1.736     albertel 10348: 			    my $metadata = 
                   10349: 				&metadata($uri,'keys', $location,$unikey,
                   10350: 					  $depthcount+1);
                   10351: 			    foreach my $meta (split(',',$metadata)) {
                   10352: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   10353: 				$metathesekeys{$meta}=1;
1.339     albertel 10354: 			    }
1.1068    www      10355: 			
                   10356:                         }
1.1067    www      10357: 		    } else {
                   10358: #
                   10359: # Not importing, some other kind of non-package, non-library start tag
                   10360: # 
                   10361:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10362:                         if (defined($token->[2]->{'id'})) {
                   10363:                             $unikey.='_'.$token->[2]->{'id'};
                   10364:                         }
1.339     albertel 10365: 			if (defined($token->[2]->{'name'})) { 
                   10366: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   10367: 			}
                   10368: 			$metathesekeys{$unikey}=1;
1.736     albertel 10369: 			foreach my $param (@{$token->[3]}) {
                   10370: 			    $metaentry{':'.$unikey.'.'.$param} =
                   10371: 				$token->[2]->{$param};
1.339     albertel 10372: 			}
                   10373: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 10374: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 10375: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   10376: 		 # only ws inside the tag, and not in default, so use default
                   10377: 		 # as value
1.599     albertel 10378: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 10379: 			} elsif ( $internaltext =~ /\S/ ) {
                   10380: 		  # something interesting inside the tag
                   10381: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 10382: 			} else {
1.908     albertel 10383: 		  # no interesting values, don't set a default
1.339     albertel 10384: 			}
1.172     www      10385: # end of not-a-package not-a-library import
1.339     albertel 10386: 		    }
1.172     www      10387: # end of not-a-package start tag
1.339     albertel 10388: 		}
1.172     www      10389: # the next is the end of "start tag"
1.339     albertel 10390: 	    }
                   10391: 	}
1.483     albertel 10392: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 10393: 	$extension = lc($extension);
                   10394: 	if ($extension eq 'htm') { $extension='html'; }
                   10395: 
1.737     albertel 10396: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 10397: 	    #no specific packages #how's our extension
                   10398: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 10399: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 10400: 					 \%metathesekeys);
                   10401: 	}
1.883     albertel 10402: 
                   10403: 	if (!exists($metaentry{':packages'})
                   10404: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 10405: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 10406: 		#no specific packages well let's get default then
                   10407: 		if ($key!~/^default&/) { next; }
1.488     albertel 10408: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 10409: 					     \%metathesekeys);
                   10410: 	    }
                   10411: 	}
1.338     www      10412: # are there custom rights to evaluate
1.599     albertel 10413: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 10414: 
1.338     www      10415:     #
                   10416:     # Importing a rights file here
1.339     albertel 10417:     #
                   10418: 	    unless ($depthcount) {
1.599     albertel 10419: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 10420: 		my $dir=$filename;
                   10421: 		$dir=~s|[^/]*$||;
                   10422: 		$location=&filelocation($dir,$location);
1.736     albertel 10423: 		my $rights_metadata =
                   10424: 		    &metadata($uri,'keys',$location,'_rights',
                   10425: 			      $depthcount+1);
                   10426: 		foreach my $rights (split(',',$rights_metadata)) {
                   10427: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   10428: 		    $metathesekeys{$rights}=1;
1.339     albertel 10429: 		}
                   10430: 	    }
                   10431: 	}
1.737     albertel 10432: 	# uniqifiy package listing
                   10433: 	my %seen;
                   10434: 	my @uniq_packages =
                   10435: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   10436: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   10437: 
1.1070    www      10438:         if ($importedparts) {
                   10439: # We had imported parts and need to rebuild partorder
                   10440:            $metaentry{':partorder'}='';
                   10441:            $metathesekeys{'partorder'}=1;
                   10442:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   10443:                if ($origfileimportpartids[$index] eq 'part') {
                   10444: # original part, part of the problem
                   10445:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   10446:                } else {
                   10447: # we have imported parts at this position
                   10448:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   10449:                }
                   10450:            }
                   10451:            $metaentry{':partorder'}=~s/^\,//;
                   10452:         }
                   10453: 
1.737     albertel 10454: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 10455: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   10456: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 10457: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      10458: # this is the end of "was not already recently cached
1.71      www      10459:     }
1.599     albertel 10460:     return $metaentry{':'.$what};
1.261     albertel 10461: }
                   10462: 
1.488     albertel 10463: sub metadata_create_package_def {
1.483     albertel 10464:     my ($uri,$key,$package,$metathesekeys)=@_;
                   10465:     my ($pack,$name,$subp)=split(/\&/,$key);
                   10466:     if ($subp eq 'default') { next; }
                   10467:     
1.599     albertel 10468:     if (defined($metaentry{':packages'})) {
                   10469: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 10470:     } else {
1.599     albertel 10471: 	$metaentry{':packages'}=$package;
1.483     albertel 10472:     }
                   10473:     my $value=$packagetab{$key};
                   10474:     my $unikey;
                   10475:     $unikey='parameter_0_'.$name;
1.599     albertel 10476:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 10477:     $$metathesekeys{$unikey}=1;
1.599     albertel 10478:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10479: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 10480:     }
1.599     albertel 10481:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   10482: 	$metaentry{':'.$unikey}=
                   10483: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 10484:     }
                   10485: }
                   10486: 
1.261     albertel 10487: sub metadata_generate_part0 {
                   10488:     my ($metadata,$metacache,$uri) = @_;
                   10489:     my %allnames;
1.737     albertel 10490:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 10491: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 10492: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   10493: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 10494: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 10495: 	    $allnames{$name}=$part;
                   10496: 	  }
                   10497: 	}
                   10498:     }
                   10499:     foreach my $name (keys(%allnames)) {
                   10500:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 10501:       my $key=":parameter_0_$name";
1.261     albertel 10502:       $$metacache{"$key.part"}='0';
                   10503:       $$metacache{"$key.name"}=$name;
1.428     albertel 10504:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 10505: 					   $allnames{$name}.'_'.$name.
                   10506: 					   '.type'};
1.428     albertel 10507:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 10508: 			     '.display'};
1.644     www      10509:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 10510:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 10511:       $$metacache{"$key.display"}=$olddis;
                   10512:     }
1.71      www      10513: }
                   10514: 
1.764     albertel 10515: # ------------------------------------------------------ Devalidate title cache
                   10516: 
                   10517: sub devalidate_title_cache {
                   10518:     my ($url)=@_;
                   10519:     if (!$env{'request.course.id'}) { return; }
                   10520:     my $symb=&symbread($url);
                   10521:     if (!$symb) { return; }
                   10522:     my $key=$env{'request.course.id'}."\0".$symb;
                   10523:     &devalidate_cache_new('title',$key);
                   10524: }
                   10525: 
1.1014    droeschl 10526: # ------------------------------------------------- Get the title of a course
                   10527: 
                   10528: sub current_course_title {
                   10529:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   10530: }
1.301     www      10531: # ------------------------------------------------- Get the title of a resource
                   10532: 
                   10533: sub gettitle {
                   10534:     my $urlsymb=shift;
                   10535:     my $symb=&symbread($urlsymb);
1.534     albertel 10536:     if ($symb) {
1.620     albertel 10537: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 10538: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 10539: 	if (defined($cached)) { 
                   10540: 	    return $result;
                   10541: 	}
1.534     albertel 10542: 	my ($map,$resid,$url)=&decode_symb($symb);
                   10543: 	my $title='';
1.907     albertel 10544: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   10545: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   10546: 	} else {
                   10547: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10548: 		    &GDBM_READER(),0640)) {
                   10549: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   10550: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   10551: 		untie(%bighash);
                   10552: 	    }
1.534     albertel 10553: 	}
                   10554: 	$title=~s/\&colon\;/\:/gs;
                   10555: 	if ($title) {
1.1159    www      10556: # Remember both $symb and $title for dynamic metadata
                   10557:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      10558:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      10559: # Cache this title and then return it
1.599     albertel 10560: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 10561: 	}
                   10562: 	$urlsymb=$url;
                   10563:     }
                   10564:     my $title=&metadata($urlsymb,'title');
                   10565:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   10566:     return $title;
1.301     www      10567: }
1.613     albertel 10568: 
1.614     albertel 10569: sub get_slot {
                   10570:     my ($which,$cnum,$cdom)=@_;
                   10571:     if (!$cnum || !$cdom) {
1.790     albertel 10572: 	(undef,my $courseid)=&whichuser();
1.620     albertel 10573: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   10574: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 10575:     }
1.703     albertel 10576:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   10577:     my %slotinfo;
                   10578:     if (exists($remembered{$key})) {
                   10579: 	$slotinfo{$which} = $remembered{$key};
                   10580:     } else {
                   10581: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   10582: 	&Apache::lonhomework::showhash(%slotinfo);
                   10583: 	my ($tmp)=keys(%slotinfo);
                   10584: 	if ($tmp=~/^error:/) { return (); }
                   10585: 	$remembered{$key} = $slotinfo{$which};
                   10586:     }
1.616     albertel 10587:     if (ref($slotinfo{$which}) eq 'HASH') {
                   10588: 	return %{$slotinfo{$which}};
                   10589:     }
                   10590:     return $slotinfo{$which};
1.614     albertel 10591: }
1.1150    raeburn  10592: 
                   10593: sub get_reservable_slots {
                   10594:     my ($cnum,$cdom,$uname,$udom) = @_;
                   10595:     my $now = time;
                   10596:     my $reservable_info;
                   10597:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   10598:     if (exists($remembered{$key})) {
                   10599:         $reservable_info = $remembered{$key};
                   10600:     } else {
                   10601:         my %resv;
                   10602:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   10603:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   10604:         $reservable_info = \%resv;
                   10605:         $remembered{$key} = $reservable_info;
                   10606:     }
                   10607:     return $reservable_info;
                   10608: }
                   10609: 
                   10610: sub get_course_slots {
                   10611:     my ($cnum,$cdom) = @_;
                   10612:     my $hashid=$cnum.':'.$cdom;
                   10613:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   10614:     if (defined($cached)) {
                   10615:         if (ref($result) eq 'HASH') {
                   10616:             return %{$result};
                   10617:         }
                   10618:     } else {
                   10619:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   10620:         my ($tmp) = keys(%slots);
                   10621:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  10622:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  10623:             return %slots;
                   10624:         }
                   10625:     }
                   10626:     return;
                   10627: }
                   10628: 
                   10629: sub devalidate_slots_cache {
                   10630:     my ($cnum,$cdom)=@_;
                   10631:     my $hashid=$cnum.':'.$cdom;
                   10632:     &devalidate_cache_new('allslots',$hashid);
                   10633: }
                   10634: 
1.1172.2.8  raeburn  10635: sub get_coursechange {
                   10636:     my ($cdom,$cnum) = @_;
                   10637:     if ($cdom eq '' || $cnum eq '') {
                   10638:         return unless ($env{'request.course.id'});
                   10639:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10640:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10641:     }
                   10642:     my $hashid=$cdom.'_'.$cnum;
                   10643:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   10644:     if ((defined($cached)) && ($change ne '')) {
                   10645:         return $change;
                   10646:     } else {
                   10647:         my %crshash;
                   10648:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   10649:         if ($crshash{'internal.contentchange'} eq '') {
                   10650:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   10651:             if ($change eq '') {
                   10652:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   10653:                 $change = $crshash{'internal.created'};
                   10654:             }
                   10655:         } else {
                   10656:             $change = $crshash{'internal.contentchange'};
                   10657:         }
                   10658:         my $cachetime = 600;
                   10659:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   10660:     }
                   10661:     return $change;
                   10662: }
                   10663: 
                   10664: sub devalidate_coursechange_cache {
                   10665:     my ($cnum,$cdom)=@_;
                   10666:     my $hashid=$cnum.':'.$cdom;
                   10667:     &devalidate_cache_new('crschange',$hashid);
                   10668: }
                   10669: 
1.31      www      10670: # ------------------------------------------------- Update symbolic store links
                   10671: 
                   10672: sub symblist {
                   10673:     my ($mapname,%newhash)=@_;
1.438     www      10674:     $mapname=&deversion(&declutter($mapname));
1.31      www      10675:     my %hash;
1.620     albertel 10676:     if (($env{'request.course.fn'}) && (%newhash)) {
                   10677:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10678:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  10679: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 10680: 		next if ($url eq 'last_known'
                   10681: 			 && $env{'form.no_update_last_known'});
                   10682: 		$hash{declutter($url)}=&encode_symb($mapname,
                   10683: 						    $newhash{$url}->[1],
                   10684: 						    $newhash{$url}->[0]);
1.191     harris41 10685:             }
1.31      www      10686:             if (untie(%hash)) {
                   10687: 		return 'ok';
                   10688:             }
                   10689:         }
                   10690:     }
                   10691:     return 'error';
1.212     www      10692: }
                   10693: 
                   10694: # --------------------------------------------------------------- Verify a symb
                   10695: 
                   10696: sub symbverify {
1.1172.2.11  raeburn  10697:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      10698:     my $thisfn=$thisurl;
1.439     www      10699:     $thisfn=&declutter($thisfn);
1.215     www      10700: # direct jump to resource in page or to a sequence - will construct own symbs
                   10701:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   10702: # check URL part
1.409     www      10703:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      10704: 
1.431     www      10705:     unless ($url eq $thisfn) { return 0; }
1.213     www      10706: 
1.216     www      10707:     $symb=&symbclean($symb);
1.510     www      10708:     $thisurl=&deversion($thisurl);
1.439     www      10709:     $thisfn=&deversion($thisfn);
1.213     www      10710: 
                   10711:     my %bighash;
                   10712:     my $okay=0;
1.431     www      10713: 
1.620     albertel 10714:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10715:                             &GDBM_READER(),0640)) {
1.1172.2.13  raeburn  10716:         my $noclutter;
1.1032    raeburn  10717:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   10718:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  10719:             if ($map =~ m{^uploaded/.+\.page$}) {
                   10720:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   10721:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   10722:                 $noclutter = 1;
                   10723:             }
                   10724:         }
                   10725:         my $ids;
                   10726:         if ($noclutter) {
                   10727:             $ids=$bighash{'ids_'.$thisurl};
                   10728:         } else {
                   10729:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  10730:         }
1.1102    raeburn  10731:         unless ($ids) {
1.1172.2.13  raeburn  10732:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  10733:             $ids=$bighash{$idkey};
1.216     www      10734:         }
                   10735:         if ($ids) {
                   10736: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  10737:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   10738:                 $symb =~ s/\?.+$//;
                   10739:             }
1.800     albertel 10740: 	    foreach my $id (split(/\,/,$ids)) {
                   10741: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      10742:                if (
                   10743:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  10744:    eq $symb) {
1.1172.2.11  raeburn  10745:                    if (ref($encstate)) {
                   10746:                        $$encstate = $bighash{'encrypted_'.$id};
                   10747:                    }
1.1172.2.13  raeburn  10748:                    if (($env{'request.role.adv'}) ||
                   10749:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  10750:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  10751:                        $okay=1;
                   10752:                        last;
                   10753:                    }
                   10754:                }
                   10755:            }
1.216     www      10756:         }
1.213     www      10757: 	untie(%bighash);
                   10758:     }
                   10759:     return $okay;
1.31      www      10760: }
                   10761: 
1.210     www      10762: # --------------------------------------------------------------- Clean-up symb
                   10763: 
                   10764: sub symbclean {
                   10765:     my $symb=shift;
1.568     albertel 10766:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      10767: # remove version from map
                   10768:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      10769: 
1.210     www      10770: # remove version from URL
                   10771:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      10772: 
1.507     www      10773: # remove wrapper
                   10774: 
1.510     www      10775:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 10776:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      10777:     return $symb;
1.409     www      10778: }
                   10779: 
                   10780: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 10781: 
                   10782: sub encode_symb {
                   10783:     my ($map,$resid,$url)=@_;
                   10784:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   10785: }
1.409     www      10786: 
                   10787: sub decode_symb {
1.568     albertel 10788:     my $symb=shift;
                   10789:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   10790:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      10791:     return (&fixversion($map),$resid,&fixversion($url));
                   10792: }
                   10793: 
                   10794: sub fixversion {
                   10795:     my $fn=shift;
1.609     banghart 10796:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      10797:     my %bighash;
                   10798:     my $uri=&clutter($fn);
1.620     albertel 10799:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      10800: # is this cached?
1.599     albertel 10801:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      10802:     if (defined($cached)) { return $result; }
                   10803: # unfortunately not cached, or expired
1.620     albertel 10804:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      10805: 	    &GDBM_READER(),0640)) {
                   10806:  	if ($bighash{'version_'.$uri}) {
                   10807:  	    my $version=$bighash{'version_'.$uri};
1.444     www      10808:  	    unless (($version eq 'mostrecent') || 
                   10809: 		    ($version==&getversion($uri))) {
1.440     www      10810:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   10811:  	    }
                   10812:  	}
                   10813:  	untie %bighash;
1.413     www      10814:     }
1.599     albertel 10815:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      10816: }
                   10817: 
                   10818: sub deversion {
                   10819:     my $url=shift;
                   10820:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   10821:     return $url;
1.210     www      10822: }
                   10823: 
1.31      www      10824: # ------------------------------------------------------ Return symb list entry
                   10825: 
                   10826: sub symbread {
1.249     www      10827:     my ($thisfn,$donotrecurse)=@_;
1.1172.2.13  raeburn  10828:     my $cache_str;
                   10829:     if ($thisfn ne '') {
                   10830:         $cache_str='request.symbread.cached.'.$thisfn;
                   10831:         if ($env{$cache_str} ne '') {
1.1172.2.8  raeburn  10832:             return $env{$cache_str};
                   10833:         }
1.1172.2.13  raeburn  10834:    } else {
1.242     www      10835: # no filename provided? try from environment
1.620     albertel 10836:         if ($env{'request.symb'}) {
1.1172.2.13  raeburn  10837:             return $env{$cache_str}=&symbclean($env{'request.symb'});
                   10838:         }
                   10839:         $thisfn=$env{'request.filename'};
1.44      www      10840:     }
1.569     albertel 10841:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      10842: # is that filename actually a symb? Verify, clean, and return
                   10843:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 10844: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 10845: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 10846: 	}
1.242     www      10847:     }
1.44      www      10848:     $thisfn=declutter($thisfn);
1.31      www      10849:     my %hash;
1.37      www      10850:     my %bighash;
                   10851:     my $syval='';
1.620     albertel 10852:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  10853:         my $targetfn = $thisfn;
1.609     banghart 10854:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  10855:             $targetfn = 'adm/wrapper/'.$thisfn;
                   10856:         }
1.687     albertel 10857: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   10858: 	    $targetfn=$1;
                   10859: 	}
1.620     albertel 10860:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10861:                       &GDBM_READER(),0640)) {
1.481     raeburn  10862: 	    $syval=$hash{$targetfn};
1.37      www      10863:             untie(%hash);
                   10864:         }
                   10865: # ---------------------------------------------------------- There was an entry
                   10866:         if ($syval) {
1.601     albertel 10867: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 10868: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  10869: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10870: 		    #return $env{$cache_str}='';
1.601     albertel 10871: 		#}    
                   10872: 		#$syval.=$1;
                   10873: 	    #}
1.37      www      10874:         } else {
                   10875: # ------------------------------------------------------- Was not in symb table
1.620     albertel 10876:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10877:                             &GDBM_READER(),0640)) {
1.37      www      10878: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      10879:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      10880:               unless ($ids) { 
                   10881:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      10882:               }
                   10883:               unless ($ids) {
                   10884: # alias?
                   10885: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      10886:               }
1.37      www      10887:               if ($ids) {
                   10888: # ------------------------------------------------------------------- Has ID(s)
                   10889:                  my @possibilities=split(/\,/,$ids);
1.39      www      10890:                  if ($#possibilities==0) {
                   10891: # ----------------------------------------------- There is only one possibility
1.37      www      10892: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 10893: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10894: 						    $resid,$thisfn);
1.249     www      10895:                  } elsif (!$donotrecurse) {
1.39      www      10896: # ------------------------------------------ There is more than one possibility
                   10897:                      my $realpossible=0;
1.800     albertel 10898:                      foreach my $id (@possibilities) {
                   10899: 			 my $file=$bighash{'src_'.$id};
1.39      www      10900:                          if (&allowed('bre',$file)) {
1.800     albertel 10901:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      10902:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   10903: 				$realpossible++;
1.626     albertel 10904:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10905: 						    $resid,$thisfn);
1.39      www      10906:                             }
                   10907: 			 }
1.191     harris41 10908:                      }
1.39      www      10909: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      10910:                  } else {
                   10911:                      $syval='';
1.37      www      10912:                  }
                   10913: 	      }
                   10914:               untie(%bighash)
1.481     raeburn  10915:            }
1.31      www      10916:         }
1.62      www      10917:         if ($syval) {
1.620     albertel 10918: 	    return $env{$cache_str}=$syval;
1.62      www      10919:         }
1.31      www      10920:     }
1.949     raeburn  10921:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10922:     return $env{$cache_str}='';
1.31      www      10923: }
                   10924: 
                   10925: # ---------------------------------------------------------- Return random seed
                   10926: 
1.32      www      10927: sub numval {
                   10928:     my $txt=shift;
                   10929:     $txt=~tr/A-J/0-9/;
                   10930:     $txt=~tr/a-j/0-9/;
                   10931:     $txt=~tr/K-T/0-9/;
                   10932:     $txt=~tr/k-t/0-9/;
                   10933:     $txt=~tr/U-Z/0-5/;
                   10934:     $txt=~tr/u-z/0-5/;
                   10935:     $txt=~s/\D//g;
1.564     albertel 10936:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      10937:     return int($txt);
1.368     albertel 10938: }
                   10939: 
1.484     albertel 10940: sub numval2 {
                   10941:     my $txt=shift;
                   10942:     $txt=~tr/A-J/0-9/;
                   10943:     $txt=~tr/a-j/0-9/;
                   10944:     $txt=~tr/K-T/0-9/;
                   10945:     $txt=~tr/k-t/0-9/;
                   10946:     $txt=~tr/U-Z/0-5/;
                   10947:     $txt=~tr/u-z/0-5/;
                   10948:     $txt=~s/\D//g;
                   10949:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10950:     my $total;
                   10951:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 10952:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 10953:     return int($total);
                   10954: }
                   10955: 
1.575     albertel 10956: sub numval3 {
                   10957:     use integer;
                   10958:     my $txt=shift;
                   10959:     $txt=~tr/A-J/0-9/;
                   10960:     $txt=~tr/a-j/0-9/;
                   10961:     $txt=~tr/K-T/0-9/;
                   10962:     $txt=~tr/k-t/0-9/;
                   10963:     $txt=~tr/U-Z/0-5/;
                   10964:     $txt=~tr/u-z/0-5/;
                   10965:     $txt=~s/\D//g;
                   10966:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10967:     my $total;
                   10968:     foreach my $val (@txts) { $total+=$val; }
                   10969:     if ($_64bit) { $total=(($total<<32)>>32); }
                   10970:     return $total;
                   10971: }
                   10972: 
1.675     albertel 10973: sub digest {
                   10974:     my ($data)=@_;
                   10975:     my $digest=&Digest::MD5::md5($data);
                   10976:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   10977:     my ($e,$f);
                   10978:     {
                   10979:         use integer;
                   10980:         $e=($a+$b);
                   10981:         $f=($c+$d);
                   10982:         if ($_64bit) {
                   10983:             $e=(($e<<32)>>32);
                   10984:             $f=(($f<<32)>>32);
                   10985:         }
                   10986:     }
                   10987:     if (wantarray) {
                   10988: 	return ($e,$f);
                   10989:     } else {
                   10990: 	my $g;
                   10991: 	{
                   10992: 	    use integer;
                   10993: 	    $g=($e+$f);
                   10994: 	    if ($_64bit) {
                   10995: 		$g=(($g<<32)>>32);
                   10996: 	    }
                   10997: 	}
                   10998: 	return $g;
                   10999:     }
                   11000: }
                   11001: 
1.368     albertel 11002: sub latest_rnd_algorithm_id {
1.675     albertel 11003:     return '64bit5';
1.366     albertel 11004: }
1.32      www      11005: 
1.503     albertel 11006: sub get_rand_alg {
                   11007:     my ($courseid)=@_;
1.790     albertel 11008:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 11009:     if ($courseid) {
1.620     albertel 11010: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 11011:     }
                   11012:     return &latest_rnd_algorithm_id();
                   11013: }
                   11014: 
1.562     albertel 11015: sub validCODE {
                   11016:     my ($CODE)=@_;
                   11017:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   11018:     return 0;
                   11019: }
                   11020: 
1.491     albertel 11021: sub getCODE {
1.620     albertel 11022:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 11023:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   11024: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   11025: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 11026: 	return $Apache::lonhomework::history{'resource.CODE'};
                   11027:     }
                   11028:     return undef;
                   11029: }
1.1133    foxr     11030: #
                   11031: #  Determines the random seed for a specific context:
                   11032: #
                   11033: # parameters:
                   11034: #   symb      - in course context the symb for the seed.
                   11035: #   course_id - The course id of the form domain_coursenum.
                   11036: #   domain    - Domain for the user.
                   11037: #   course    - Course for the user.
                   11038: #   cenv      - environment of the course.
                   11039: #
                   11040: # NOTE:
                   11041: #   All parameters are picked out of the environment if missing
                   11042: #   or not defined.
                   11043: #   If a symb cannot be determined the current time is used instead.
                   11044: #
                   11045: #  For a given well defined symb, courside, domain, username,
                   11046: #  and course environment, the seed is reproducible.
                   11047: #
1.31      www      11048: sub rndseed {
1.1133    foxr     11049:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 11050:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 11051:     if (!defined($symb)) {
1.366     albertel 11052: 	unless ($symb=$wsymb) { return time; }
                   11053:     }
1.1146    foxr     11054:     if (!defined $courseid) { 
                   11055: 	$courseid=$wcourseid; 
                   11056:     }
                   11057:     if (!defined $domain) { $domain=$wdomain; }
                   11058:     if (!defined $username) { $username=$wusername }
1.1133    foxr     11059: 
                   11060:     my $which;
                   11061:     if (defined($cenv->{'rndseed'})) {
                   11062: 	$which = $cenv->{'rndseed'};
                   11063:     } else {
                   11064: 	$which =&get_rand_alg($courseid);
                   11065:     }
1.491     albertel 11066:     if (defined(&getCODE())) {
1.675     albertel 11067: 	if ($which eq '64bit5') {
                   11068: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   11069: 	} elsif ($which eq '64bit4') {
1.575     albertel 11070: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   11071: 	} else {
                   11072: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   11073: 	}
1.675     albertel 11074:     } elsif ($which eq '64bit5') {
                   11075: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 11076:     } elsif ($which eq '64bit4') {
                   11077: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 11078:     } elsif ($which eq '64bit3') {
                   11079: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 11080:     } elsif ($which eq '64bit2') {
                   11081: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 11082:     } elsif ($which eq '64bit') {
                   11083: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   11084:     }
                   11085:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   11086: }
                   11087: 
                   11088: sub rndseed_32bit {
                   11089:     my ($symb,$courseid,$domain,$username)=@_;
                   11090:     {
                   11091: 	use integer;
                   11092: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   11093: 	my $symbseed=numval($symb) << 22;
                   11094: 	my $namechck=unpack("%32C*",$username) << 17;
                   11095: 	my $nameseed=numval($username) << 12;
                   11096: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   11097: 	my $courseseed=unpack("%32C*",$courseid);
                   11098: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 11099: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11100: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 11101: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 11102: 	return $num;
                   11103:     }
                   11104: }
                   11105: 
                   11106: sub rndseed_64bit {
                   11107:     my ($symb,$courseid,$domain,$username)=@_;
                   11108:     {
                   11109: 	use integer;
                   11110: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   11111: 	my $symbseed=numval($symb) << 10;
                   11112: 	my $namechck=unpack("%32S*",$username);
                   11113: 	
                   11114: 	my $nameseed=numval($username) << 21;
                   11115: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   11116: 	my $courseseed=unpack("%32S*",$courseid);
                   11117: 	
                   11118: 	my $num1=$symbchck+$symbseed+$namechck;
                   11119: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11120: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11121: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 11122: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 11123: 	return "$num1,$num2";
1.155     albertel 11124:     }
1.366     albertel 11125: }
                   11126: 
1.443     albertel 11127: sub rndseed_64bit2 {
                   11128:     my ($symb,$courseid,$domain,$username)=@_;
                   11129:     {
                   11130: 	use integer;
                   11131: 	# strings need to be an even # of cahracters long, it it is odd the
                   11132:         # last characters gets thrown away
                   11133: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11134: 	my $symbseed=numval($symb) << 10;
                   11135: 	my $namechck=unpack("%32S*",$username.' ');
                   11136: 	
                   11137: 	my $nameseed=numval($username) << 21;
1.501     albertel 11138: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11139: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11140: 	
                   11141: 	my $num1=$symbchck+$symbseed+$namechck;
                   11142: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11143: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11144: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 11145: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 11146: 	return "$num1,$num2";
                   11147:     }
                   11148: }
                   11149: 
                   11150: sub rndseed_64bit3 {
                   11151:     my ($symb,$courseid,$domain,$username)=@_;
                   11152:     {
                   11153: 	use integer;
                   11154: 	# strings need to be an even # of cahracters long, it it is odd the
                   11155:         # last characters gets thrown away
                   11156: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11157: 	my $symbseed=numval2($symb) << 10;
                   11158: 	my $namechck=unpack("%32S*",$username.' ');
                   11159: 	
                   11160: 	my $nameseed=numval2($username) << 21;
1.443     albertel 11161: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11162: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11163: 	
                   11164: 	my $num1=$symbchck+$symbseed+$namechck;
                   11165: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11166: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11167: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 11168: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11169: 	
1.503     albertel 11170: 	return "$num1:$num2";
1.443     albertel 11171:     }
                   11172: }
                   11173: 
1.575     albertel 11174: sub rndseed_64bit4 {
                   11175:     my ($symb,$courseid,$domain,$username)=@_;
                   11176:     {
                   11177: 	use integer;
                   11178: 	# strings need to be an even # of cahracters long, it it is odd the
                   11179:         # last characters gets thrown away
                   11180: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11181: 	my $symbseed=numval3($symb) << 10;
                   11182: 	my $namechck=unpack("%32S*",$username.' ');
                   11183: 	
                   11184: 	my $nameseed=numval3($username) << 21;
                   11185: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11186: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11187: 	
                   11188: 	my $num1=$symbchck+$symbseed+$namechck;
                   11189: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11190: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11191: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 11192: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11193: 	
1.575     albertel 11194: 	return "$num1:$num2";
                   11195:     }
                   11196: }
                   11197: 
1.675     albertel 11198: sub rndseed_64bit5 {
                   11199:     my ($symb,$courseid,$domain,$username)=@_;
                   11200:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   11201:     return "$num1:$num2";
                   11202: }
                   11203: 
1.366     albertel 11204: sub rndseed_CODE_64bit {
                   11205:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 11206:     {
1.366     albertel 11207: 	use integer;
1.443     albertel 11208: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 11209: 	my $symbseed=numval2($symb);
1.491     albertel 11210: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11211: 	my $CODEseed=numval(&getCODE());
1.443     albertel 11212: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 11213: 	my $num1=$symbseed+$CODEchck;
                   11214: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11215: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11216: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 11217: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11218: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 11219: 	return "$num1:$num2";
1.366     albertel 11220:     }
                   11221: }
                   11222: 
1.575     albertel 11223: sub rndseed_CODE_64bit4 {
                   11224:     my ($symb,$courseid,$domain,$username)=@_;
                   11225:     {
                   11226: 	use integer;
                   11227: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   11228: 	my $symbseed=numval3($symb);
                   11229: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11230: 	my $CODEseed=numval3(&getCODE());
                   11231: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11232: 	my $num1=$symbseed+$CODEchck;
                   11233: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11234: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11235: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 11236: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11237: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   11238: 	return "$num1:$num2";
                   11239:     }
                   11240: }
                   11241: 
1.675     albertel 11242: sub rndseed_CODE_64bit5 {
                   11243:     my ($symb,$courseid,$domain,$username)=@_;
                   11244:     my $code = &getCODE();
                   11245:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   11246:     return "$num1:$num2";
                   11247: }
                   11248: 
1.366     albertel 11249: sub setup_random_from_rndseed {
                   11250:     my ($rndseed)=@_;
1.503     albertel 11251:     if ($rndseed =~/([,:])/) {
                   11252: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 11253: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   11254:     } else {
                   11255: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 11256:     }
1.36      albertel 11257: }
                   11258: 
1.474     albertel 11259: sub latest_receipt_algorithm_id {
1.835     albertel 11260:     return 'receipt3';
1.474     albertel 11261: }
                   11262: 
1.480     www      11263: sub recunique {
                   11264:     my $fucourseid=shift;
                   11265:     my $unique;
1.835     albertel 11266:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   11267: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11268: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      11269:     } else {
                   11270: 	$unique=$perlvar{'lonReceipt'};
                   11271:     }
                   11272:     return unpack("%32C*",$unique);
                   11273: }
                   11274: 
                   11275: sub recprefix {
                   11276:     my $fucourseid=shift;
                   11277:     my $prefix;
1.835     albertel 11278:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   11279: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11280: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      11281:     } else {
                   11282: 	$prefix=$perlvar{'lonHostID'};
                   11283:     }
                   11284:     return unpack("%32C*",$prefix);
                   11285: }
                   11286: 
1.76      www      11287: sub ireceipt {
1.474     albertel 11288:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 11289: 
                   11290:     my $return =&recprefix($fucourseid).'-';
                   11291: 
                   11292:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   11293: 	$env{'request.state'} eq 'construct') {
                   11294: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   11295: 	return $return;
                   11296:     }
                   11297: 
1.76      www      11298:     my $cuname=unpack("%32C*",$funame);
                   11299:     my $cudom=unpack("%32C*",$fudom);
                   11300:     my $cucourseid=unpack("%32C*",$fucourseid);
                   11301:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      11302:     my $cunique=&recunique($fucourseid);
1.474     albertel 11303:     my $cpart=unpack("%32S*",$part);
1.835     albertel 11304:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   11305: 
1.790     albertel 11306: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 11307: 			       
                   11308: 	$return.= ($cunique%$cuname+
                   11309: 		   $cunique%$cudom+
                   11310: 		   $cusymb%$cuname+
                   11311: 		   $cusymb%$cudom+
                   11312: 		   $cucourseid%$cuname+
                   11313: 		   $cucourseid%$cudom+
                   11314: 		   $cpart%$cuname+
                   11315: 		   $cpart%$cudom);
                   11316:     } else {
                   11317: 	$return.= ($cunique%$cuname+
                   11318: 		   $cunique%$cudom+
                   11319: 		   $cusymb%$cuname+
                   11320: 		   $cusymb%$cudom+
                   11321: 		   $cucourseid%$cuname+
                   11322: 		   $cucourseid%$cudom);
                   11323:     }
                   11324:     return $return;
1.76      www      11325: }
                   11326: 
                   11327: sub receipt {
1.474     albertel 11328:     my ($part)=@_;
1.790     albertel 11329:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 11330:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      11331: }
1.260     ng       11332: 
1.790     albertel 11333: sub whichuser {
                   11334:     my ($passedsymb)=@_;
                   11335:     my ($symb,$courseid,$domain,$name,$publicuser);
                   11336:     if (defined($env{'form.grade_symb'})) {
                   11337: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   11338: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   11339: 	if (!$allowed &&
                   11340: 	    exists($env{'request.course.sec'}) &&
                   11341: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   11342: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   11343: 			      '/'.$env{'request.course.sec'});
                   11344: 	}
                   11345: 	if ($allowed) {
                   11346: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   11347: 	    $courseid=$tmp_courseid;
                   11348: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   11349: 	    ($name)=&get_env_multiple('form.grade_username');
                   11350: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   11351: 	}
                   11352:     }
                   11353:     if (!$passedsymb) {
                   11354: 	$symb=&symbread();
                   11355:     } else {
                   11356: 	$symb=$passedsymb;
                   11357:     }
                   11358:     $courseid=$env{'request.course.id'};
                   11359:     $domain=$env{'user.domain'};
                   11360:     $name=$env{'user.name'};
                   11361:     if ($name eq 'public' && $domain eq 'public') {
                   11362: 	if (!defined($env{'form.username'})) {
                   11363: 	    $env{'form.username'}.=time.rand(10000000);
                   11364: 	}
                   11365: 	$name.=$env{'form.username'};
                   11366:     }
                   11367:     return ($symb,$courseid,$domain,$name,$publicuser);
                   11368: 
                   11369: }
                   11370: 
1.36      albertel 11371: # ------------------------------------------------------------ Serves up a file
1.472     albertel 11372: # returns either the contents of the file or 
                   11373: # -1 if the file doesn't exist
1.481     raeburn  11374: #
                   11375: # if the target is a file that was uploaded via DOCS, 
                   11376: # a check will be made to see if a current copy exists on the local server,
                   11377: # if it does this will be served, otherwise a copy will be retrieved from
                   11378: # the home server for the course and stored in /home/httpd/html/userfiles on
                   11379: # the local server.   
1.472     albertel 11380: 
1.36      albertel 11381: sub getfile {
1.538     albertel 11382:     my ($file) = @_;
1.609     banghart 11383:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 11384:     &repcopy($file);
                   11385:     return &readfile($file);
                   11386: }
                   11387: 
                   11388: sub repcopy_userfile {
                   11389:     my ($file)=@_;
1.1142    raeburn  11390:     my $londocroot = $perlvar{'lonDocRoot'};
                   11391:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  11392:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 11393:     my ($cdom,$cnum,$filename) = 
1.811     albertel 11394: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 11395:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   11396:     if (-e "$file") {
1.828     www      11397: # we already have a local copy, check it out
1.538     albertel 11398: 	my @fileinfo = stat($file);
1.828     www      11399: 	my $rtncode;
                   11400: 	my $info;
1.538     albertel 11401: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 11402: 	if ($lwpresp ne 'ok') {
1.828     www      11403: # there is no such file anymore, even though we had a local copy
1.482     albertel 11404: 	    if ($rtncode eq '404') {
1.538     albertel 11405: 		unlink($file);
1.482     albertel 11406: 	    }
                   11407: 	    return -1;
                   11408: 	}
                   11409: 	if ($info < $fileinfo[9]) {
1.828     www      11410: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  11411: 	    return 'ok';
1.828     www      11412: 	} else {
                   11413: # the file is outdated, get rid of it
                   11414: 	    unlink($file);
1.482     albertel 11415: 	}
1.828     www      11416:     }
                   11417: # one way or the other, at this point, we don't have the file
                   11418: # construct the correct path for the file
                   11419:     my @parts = ($cdom,$cnum); 
                   11420:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   11421: 	push @parts, split(/\//,$1);
                   11422:     }
                   11423:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   11424:     foreach my $part (@parts) {
                   11425: 	$path .= '/'.$part;
                   11426: 	if (!-e $path) {
                   11427: 	    mkdir($path,0770);
1.482     albertel 11428: 	}
                   11429:     }
1.828     www      11430: # now the path exists for sure
                   11431: # get a user agent
                   11432:     my $ua=new LWP::UserAgent;
                   11433:     my $transferfile=$file.'.in.transfer';
                   11434: # FIXME: this should flock
                   11435:     if (-e $transferfile) { return 'ok'; }
                   11436:     my $request;
                   11437:     $uri=~s/^\///;
1.980     raeburn  11438:     my $homeserver = &homeserver($cnum,$cdom);
                   11439:     my $protocol = $protocol{$homeserver};
                   11440:     $protocol = 'http' if ($protocol ne 'https');
                   11441:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      11442:     my $response=$ua->request($request,$transferfile);
                   11443: # did it work?
                   11444:     if ($response->is_error()) {
                   11445: 	unlink($transferfile);
                   11446: 	&logthis("Userfile repcopy failed for $uri");
                   11447: 	return -1;
                   11448:     }
                   11449: # worked, rename the transfer file
                   11450:     rename($transferfile,$file);
1.607     raeburn  11451:     return 'ok';
1.481     raeburn  11452: }
                   11453: 
1.517     albertel 11454: sub tokenwrapper {
                   11455:     my $uri=shift;
1.980     raeburn  11456:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 11457:     $uri=~s|^/||;
1.620     albertel 11458:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 11459:     my $token=$1;
1.552     albertel 11460:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   11461:     if ($udom && $uname && $file) {
                   11462: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  11463:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  11464:         my $homeserver = &homeserver($uname,$udom);
                   11465:         my $protocol = $protocol{$homeserver};
                   11466:         $protocol = 'http' if ($protocol ne 'https');
                   11467:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 11468:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   11469:                                '&tokenissued='.$perlvar{'lonHostID'};
                   11470:     } else {
                   11471:         return '/adm/notfound.html';
                   11472:     }
                   11473: }
                   11474: 
1.828     www      11475: # call with reqtype HEAD: get last modification time
                   11476: # call with reqtype GET: get the file contents
                   11477: # Do not call this with reqtype GET for large files! It loads everything into memory
                   11478: #
1.481     raeburn  11479: sub getuploaded {
                   11480:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   11481:     $uri=~s/^\///;
1.980     raeburn  11482:     my $homeserver = &homeserver($cnum,$cdom);
                   11483:     my $protocol = $protocol{$homeserver};
                   11484:     $protocol = 'http' if ($protocol ne 'https');
                   11485:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  11486:     my $ua=new LWP::UserAgent;
                   11487:     my $request=new HTTP::Request($reqtype,$uri);
                   11488:     my $response=$ua->request($request);
                   11489:     $$rtncode = $response->code;
1.482     albertel 11490:     if (! $response->is_success()) {
                   11491: 	return 'failed';
                   11492:     }      
                   11493:     if ($reqtype eq 'HEAD') {
1.486     www      11494: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 11495:     } elsif ($reqtype eq 'GET') {
                   11496: 	$$info = $response->content;
1.472     albertel 11497:     }
1.482     albertel 11498:     return 'ok';
1.36      albertel 11499: }
                   11500: 
1.481     raeburn  11501: sub readfile {
                   11502:     my $file = shift;
                   11503:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   11504:     my $fh;
                   11505:     open($fh,"<$file");
                   11506:     my $a='';
1.800     albertel 11507:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  11508:     return $a;
                   11509: }
                   11510: 
1.36      albertel 11511: sub filelocation {
1.590     banghart 11512:     my ($dir,$file) = @_;
                   11513:     my $location;
                   11514:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 11515: 
                   11516:     if ($file =~ m-^/adm/-) {
                   11517: 	$file=~s-^/adm/wrapper/-/-;
                   11518: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   11519:     }
1.882     albertel 11520: 
1.1139    www      11521:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  11522:         $location = $file;
1.609     banghart 11523:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 11524:         my ($udom,$uname,$filename)=
1.811     albertel 11525:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 11526:         my $home=&homeserver($uname,$udom);
                   11527:         my $is_me=0;
                   11528:         my @ids=&current_machine_ids();
                   11529:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   11530:         if ($is_me) {
1.1117    foxr     11531:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 11532:         } else {
                   11533:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   11534:   	      $udom.'/'.$uname.'/'.$filename;
                   11535:         }
1.882     albertel 11536:     } elsif ($file =~ m-^/adm/-) {
                   11537: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 11538:     } else {
                   11539:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      11540:         $file=~s:^/(res|priv)/:/:;
                   11541:         my $space=$1;
1.590     banghart 11542:         if ( !( $file =~ m:^/:) ) {
                   11543:             $location = $dir. '/'.$file;
                   11544:         } else {
1.1142    raeburn  11545:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 11546:         }
1.59      albertel 11547:     }
1.590     banghart 11548:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 11549:     while ($location=~m{/\.\./}) {
                   11550: 	if ($location =~ m{/[^/]+/\.\./}) {
                   11551: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   11552: 	} else {
                   11553: 	    $location=~ s{/\.\./}{/}g;
                   11554: 	}
                   11555:     } #remove dir/..
1.590     banghart 11556:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   11557:     return $location;
1.46      www      11558: }
1.36      albertel 11559: 
1.46      www      11560: sub hreflocation {
                   11561:     my ($dir,$file)=@_;
1.980     raeburn  11562:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 11563: 	$file=filelocation($dir,$file);
1.700     albertel 11564:     } elsif ($file=~m-^/adm/-) {
                   11565: 	$file=~s-^/adm/wrapper/-/-;
                   11566: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 11567:     }
                   11568:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   11569: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   11570:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  11571: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   11572: 	        {/uploaded/$1/$2/}x;
1.46      www      11573:     }
1.913     albertel 11574:     if ($file=~ m{^/userfiles/}) {
                   11575: 	$file =~ s{^/userfiles/}{/uploaded/};
                   11576:     }
1.462     albertel 11577:     return $file;
1.465     albertel 11578: }
                   11579: 
1.1139    www      11580: 
                   11581: 
                   11582: 
                   11583: 
1.465     albertel 11584: sub current_machine_domains {
1.853     albertel 11585:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   11586: }
                   11587: 
                   11588: sub machine_domains {
                   11589:     my ($hostname) = @_;
1.465     albertel 11590:     my @domains;
1.838     albertel 11591:     my %hostname = &all_hostnames();
1.465     albertel 11592:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  11593: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 11594: 	if ($hostname eq $name) {
1.844     albertel 11595: 	    push(@domains,&host_domain($id));
1.465     albertel 11596: 	}
                   11597:     }
                   11598:     return @domains;
                   11599: }
                   11600: 
                   11601: sub current_machine_ids {
1.853     albertel 11602:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   11603: }
                   11604: 
                   11605: sub machine_ids {
                   11606:     my ($hostname) = @_;
                   11607:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 11608:     my @ids;
1.888     albertel 11609:     my %name_to_host = &all_names();
1.889     albertel 11610:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   11611: 	return @{ $name_to_host{$hostname} };
                   11612:     }
                   11613:     return;
1.31      www      11614: }
                   11615: 
1.824     raeburn  11616: sub additional_machine_domains {
                   11617:     my @domains;
                   11618:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   11619:     while( my $line = <$fh>) {
                   11620:         $line =~ s/\s//g;
                   11621:         push(@domains,$line);
                   11622:     }
                   11623:     return @domains;
                   11624: }
                   11625: 
                   11626: sub default_login_domain {
                   11627:     my $domain = $perlvar{'lonDefDomain'};
                   11628:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   11629:     foreach my $posdom (&current_machine_domains(),
                   11630:                         &additional_machine_domains()) {
                   11631:         if (lc($posdom) eq lc($testdomain)) {
                   11632:             $domain=$posdom;
                   11633:             last;
                   11634:         }
                   11635:     }
                   11636:     return $domain;
                   11637: }
                   11638: 
1.31      www      11639: # ------------------------------------------------------------- Declutters URLs
                   11640: 
                   11641: sub declutter {
                   11642:     my $thisfn=shift;
1.569     albertel 11643:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 11644:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      11645:     $thisfn=~s/^\///;
1.697     albertel 11646:     $thisfn=~s|^adm/wrapper/||;
                   11647:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      11648:     $thisfn=~s/^res\///;
1.1172    bisitz   11649:     $thisfn=~s/^priv\///;
1.1032    raeburn  11650:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   11651:         $thisfn=~s/\?.+$//;
                   11652:     }
1.268     www      11653:     return $thisfn;
                   11654: }
                   11655: 
                   11656: # ------------------------------------------------------------- Clutter up URLs
                   11657: 
                   11658: sub clutter {
                   11659:     my $thisfn='/'.&declutter(shift);
1.887     albertel 11660:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 11661: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      11662:        $thisfn='/res'.$thisfn; 
                   11663:     }
1.1031    raeburn  11664:     if ($thisfn !~m|^/adm|) {
                   11665: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 11666: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 11667: 	} else {
                   11668: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   11669: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 11670: 	    if ($embstyle eq 'ssi'
                   11671: 		|| ($embstyle eq 'hdn')
                   11672: 		|| ($embstyle eq 'rat')
                   11673: 		|| ($embstyle eq 'prv')
                   11674: 		|| ($embstyle eq 'ign')) {
                   11675: 		#do nothing with these
                   11676: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 11677: 		|| ($embstyle eq 'emb')
                   11678: 		|| ($embstyle eq 'wrp')) {
                   11679: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 11680: 	    } elsif ($embstyle eq 'unk'
                   11681: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 11682: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 11683: 	    } else {
1.718     www      11684: #		&logthis("Got a blank emb style");
1.695     albertel 11685: 	    }
1.694     albertel 11686: 	}
                   11687:     }
1.31      www      11688:     return $thisfn;
1.12      www      11689: }
                   11690: 
1.787     albertel 11691: sub clutter_with_no_wrapper {
                   11692:     my $uri = &clutter(shift);
                   11693:     if ($uri =~ m-^/adm/-) {
                   11694: 	$uri =~ s-^/adm/wrapper/-/-;
                   11695: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   11696:     }
                   11697:     return $uri;
                   11698: }
                   11699: 
1.557     albertel 11700: sub freeze_escape {
                   11701:     my ($value)=@_;
                   11702:     if (ref($value)) {
                   11703: 	$value=&nfreeze($value);
                   11704: 	return '__FROZEN__'.&escape($value);
                   11705:     }
                   11706:     return &escape($value);
                   11707: }
                   11708: 
1.11      www      11709: 
1.557     albertel 11710: sub thaw_unescape {
                   11711:     my ($value)=@_;
                   11712:     if ($value =~ /^__FROZEN__/) {
                   11713: 	substr($value,0,10,undef);
                   11714: 	$value=&unescape($value);
                   11715: 	return &thaw($value);
                   11716:     }
                   11717:     return &unescape($value);
                   11718: }
                   11719: 
1.436     albertel 11720: sub correct_line_ends {
                   11721:     my ($result)=@_;
                   11722:     $$result =~s/\r\n/\n/mg;
                   11723:     $$result =~s/\r/\n/mg;
1.415     albertel 11724: }
1.1       albertel 11725: # ================================================================ Main Program
                   11726: 
1.184     www      11727: sub goodbye {
1.204     albertel 11728:    &logthis("Starting Shut down");
1.443     albertel 11729: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 11730:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 11731: #converted
1.599     albertel 11732: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 11733:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   11734: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   11735: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 11736: #1.1 only
1.870     albertel 11737: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   11738: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   11739: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   11740: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   11741:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 11742:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   11743:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      11744:    &flushcourselogs();
                   11745:    &logthis("Shutting down");
                   11746: }
                   11747: 
1.852     albertel 11748: sub get_dns {
1.1172.2.17  raeburn  11749:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 11750:     if (!$ignore_cache) {
                   11751: 	my ($content,$cached)=
                   11752: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   11753: 	if ($cached) {
1.1172.2.17  raeburn  11754: 	    &$func($content,$hashref);
1.869     albertel 11755: 	    return;
                   11756: 	}
                   11757:     }
                   11758: 
                   11759:     my %alldns;
1.852     albertel 11760:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11761:     foreach my $dns (<$config>) {
                   11762: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  11763:         my $line = $1;
                   11764:         my ($host,$protocol) = split(/:/,$line);
                   11765:         if ($protocol ne 'https') {
                   11766:             $protocol = 'http';
                   11767:         }
                   11768: 	$alldns{$host} = $protocol;
1.869     albertel 11769:     }
                   11770:     while (%alldns) {
                   11771: 	my ($dns) = keys(%alldns);
1.852     albertel 11772: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  11773:         $ua->timeout(30);
1.979     raeburn  11774: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 11775: 	my $response=$ua->request($request);
1.979     raeburn  11776:         delete($alldns{$dns});
1.852     albertel 11777: 	next if ($response->is_error());
                   11778: 	my @content = split("\n",$response->content);
1.1172.2.17  raeburn  11779:         unless ($nocache) {
1.1172.2.23  raeburn  11780: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  11781:         }
                   11782: 	&$func(\@content,$hashref);
1.869     albertel 11783: 	return;
1.852     albertel 11784:     }
                   11785:     close($config);
1.871     albertel 11786:     my $which = (split('/',$url))[3];
                   11787:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   11788:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 11789:     my @content = <$config>;
1.1172.2.17  raeburn  11790:     &$func(\@content,$hashref);
                   11791:     return;
                   11792: }
                   11793: 
                   11794: # ------------------------------------------------------Get DNS checksums file
                   11795: sub parse_dns_checksums_tab {
                   11796:     my ($lines,$hashref) = @_;
                   11797:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
                   11798:     my $loncaparev = &get_server_loncaparev($machine_dom);
                   11799:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   11800:     my (%chksum,%revnum);
                   11801:     if (ref($lines) eq 'ARRAY') {
                   11802:         chomp(@{$lines});
1.1172.2.34  raeburn  11803:         my $version = shift(@{$lines});
                   11804:         if ($version eq $release) {
1.1172.2.17  raeburn  11805:             foreach my $line (@{$lines}) {
1.1172.2.34  raeburn  11806:                 my ($file,$version,$shasum) = split(/,/,$line);
                   11807:                 $chksum{$file} = $shasum;
                   11808:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  11809:             }
                   11810:             if (ref($hashref) eq 'HASH') {
                   11811:                 %{$hashref} = (
                   11812:                                 sums     => \%chksum,
                   11813:                                 versions => \%revnum,
                   11814:                               );
                   11815:             }
                   11816:         }
                   11817:     }
1.869     albertel 11818:     return;
1.852     albertel 11819: }
1.1172.2.17  raeburn  11820: 
                   11821: sub fetch_dns_checksums {
                   11822:     my %checksums;
1.1172.2.34  raeburn  11823:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
                   11824:     my $loncaparev = &get_server_loncaparev($machine_dom);
                   11825:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   11826:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  11827:              \%checksums);
                   11828:     return \%checksums;
                   11829: }
                   11830: 
1.327     albertel 11831: # ------------------------------------------------------------ Read domain file
                   11832: {
1.852     albertel 11833:     my $loaded;
1.846     albertel 11834:     my %domain;
                   11835: 
1.852     albertel 11836:     sub parse_domain_tab {
                   11837: 	my ($lines) = @_;
                   11838: 	foreach my $line (@$lines) {
                   11839: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      11840: 
1.846     albertel 11841: 	    chomp($line);
1.852     albertel 11842: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 11843: 	    my %this_domain;
                   11844: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   11845: 			       'lang_def', 'city', 'longi', 'lati',
                   11846: 			       'primary') {
                   11847: 		$this_domain{$field} = shift(@elements);
                   11848: 	    }
                   11849: 	    $domain{$name} = \%this_domain;
1.852     albertel 11850: 	}
                   11851:     }
1.864     albertel 11852: 
                   11853:     sub reset_domain_info {
                   11854: 	undef($loaded);
                   11855: 	undef(%domain);
                   11856:     }
                   11857: 
1.852     albertel 11858:     sub load_domain_tab {
1.869     albertel 11859: 	my ($ignore_cache) = @_;
                   11860: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 11861: 	my $fh;
                   11862: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   11863: 	    my @lines = <$fh>;
                   11864: 	    &parse_domain_tab(\@lines);
1.448     albertel 11865: 	}
1.852     albertel 11866: 	close($fh);
                   11867: 	$loaded = 1;
1.327     albertel 11868:     }
1.846     albertel 11869: 
                   11870:     sub domain {
1.852     albertel 11871: 	&load_domain_tab() if (!$loaded);
                   11872: 
1.846     albertel 11873: 	my ($name,$what) = @_;
                   11874: 	return if ( !exists($domain{$name}) );
                   11875: 
                   11876: 	if (!$what) {
                   11877: 	    return $domain{$name}{'description'};
                   11878: 	}
                   11879: 	return $domain{$name}{$what};
                   11880:     }
1.974     raeburn  11881: 
                   11882:     sub domain_info {
                   11883:         &load_domain_tab() if (!$loaded);
                   11884:         return %domain;
                   11885:     }
                   11886: 
1.327     albertel 11887: }
                   11888: 
                   11889: 
1.1       albertel 11890: # ------------------------------------------------------------- Read hosts file
                   11891: {
1.838     albertel 11892:     my %hostname;
1.844     albertel 11893:     my %hostdom;
1.845     albertel 11894:     my %libserv;
1.852     albertel 11895:     my $loaded;
1.888     albertel 11896:     my %name_to_host;
1.1074    raeburn  11897:     my %internetdom;
1.1107    raeburn  11898:     my %LC_dns_serv;
1.852     albertel 11899: 
                   11900:     sub parse_hosts_tab {
                   11901: 	my ($file) = @_;
                   11902: 	foreach my $configline (@$file) {
                   11903: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  11904:             chomp($configline);
                   11905: 	    if ($configline =~ /^\^/) {
                   11906:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   11907:                     $LC_dns_serv{$1} = 1;
                   11908:                 }
                   11909:                 next;
                   11910:             }
1.1074    raeburn  11911: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 11912: 	    $name=~s/\s//g;
                   11913: 	    if ($id && $domain && $role && $name) {
                   11914: 		$hostname{$id}=$name;
1.888     albertel 11915: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 11916: 		$hostdom{$id}=$domain;
                   11917: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  11918:                 if (defined($protocol)) {
                   11919:                     if ($protocol eq 'https') {
                   11920:                         $protocol{$id} = $protocol;
                   11921:                     } else {
                   11922:                         $protocol{$id} = 'http'; 
                   11923:                     }
1.968     raeburn  11924:                 } else {
1.969     raeburn  11925:                     $protocol{$id} = 'http';
1.968     raeburn  11926:                 }
1.1074    raeburn  11927:                 if (defined($intdom)) {
                   11928:                     $internetdom{$id} = $intdom;
                   11929:                 }
1.852     albertel 11930: 	    }
                   11931: 	}
                   11932:     }
1.864     albertel 11933:     
                   11934:     sub reset_hosts_info {
1.897     albertel 11935: 	&purge_remembered();
1.864     albertel 11936: 	&reset_domain_info();
                   11937: 	&reset_hosts_ip_info();
1.892     albertel 11938: 	undef(%name_to_host);
1.864     albertel 11939: 	undef(%hostname);
                   11940: 	undef(%hostdom);
                   11941: 	undef(%libserv);
                   11942: 	undef($loaded);
                   11943:     }
1.1       albertel 11944: 
1.852     albertel 11945:     sub load_hosts_tab {
1.869     albertel 11946: 	my ($ignore_cache) = @_;
                   11947: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 11948: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11949: 	my @config = <$config>;
                   11950: 	&parse_hosts_tab(\@config);
                   11951: 	close($config);
                   11952: 	$loaded=1;
1.1       albertel 11953:     }
1.852     albertel 11954: 
1.838     albertel 11955:     sub hostname {
1.852     albertel 11956: 	&load_hosts_tab() if (!$loaded);
                   11957: 
1.838     albertel 11958: 	my ($lonid) = @_;
                   11959: 	return $hostname{$lonid};
                   11960:     }
1.845     albertel 11961: 
1.838     albertel 11962:     sub all_hostnames {
1.852     albertel 11963: 	&load_hosts_tab() if (!$loaded);
                   11964: 
1.838     albertel 11965: 	return %hostname;
                   11966:     }
1.845     albertel 11967: 
1.888     albertel 11968:     sub all_names {
                   11969: 	&load_hosts_tab() if (!$loaded);
                   11970: 
                   11971: 	return %name_to_host;
                   11972:     }
                   11973: 
1.974     raeburn  11974:     sub all_host_domain {
                   11975:         &load_hosts_tab() if (!$loaded);
                   11976:         return %hostdom;
                   11977:     }
                   11978: 
1.845     albertel 11979:     sub is_library {
1.852     albertel 11980: 	&load_hosts_tab() if (!$loaded);
                   11981: 
1.845     albertel 11982: 	return exists($libserv{$_[0]});
                   11983:     }
                   11984: 
                   11985:     sub all_library {
1.852     albertel 11986: 	&load_hosts_tab() if (!$loaded);
                   11987: 
1.845     albertel 11988: 	return %libserv;
                   11989:     }
                   11990: 
1.1062    droeschl 11991:     sub unique_library {
                   11992: 	#2x reverse removes all hostnames that appear more than once
                   11993:         my %unique = reverse &all_library();
                   11994:         return reverse %unique;
                   11995:     }
                   11996: 
1.841     albertel 11997:     sub get_servers {
1.852     albertel 11998: 	&load_hosts_tab() if (!$loaded);
                   11999: 
1.841     albertel 12000: 	my ($domain,$type) = @_;
                   12001: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   12002: 	                                          : %hostname;
                   12003: 	my %result;
1.842     albertel 12004: 	if (ref($domain) eq 'ARRAY') {
                   12005: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 12006: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 12007: 		    $result{$host} = $hostname;
                   12008: 		}
                   12009: 	    }
                   12010: 	} else {
                   12011: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   12012: 		if ($hostdom{$host} eq $domain) {
                   12013: 		    $result{$host} = $hostname;
                   12014: 		}
1.841     albertel 12015: 	    }
                   12016: 	}
                   12017: 	return %result;
                   12018:     }
1.845     albertel 12019: 
1.1062    droeschl 12020:     sub get_unique_servers {
                   12021:         my %unique = reverse &get_servers(@_);
                   12022: 	return reverse %unique;
                   12023:     }
                   12024: 
1.844     albertel 12025:     sub host_domain {
1.852     albertel 12026: 	&load_hosts_tab() if (!$loaded);
                   12027: 
1.844     albertel 12028: 	my ($lonid) = @_;
                   12029: 	return $hostdom{$lonid};
                   12030:     }
                   12031: 
1.841     albertel 12032:     sub all_domains {
1.852     albertel 12033: 	&load_hosts_tab() if (!$loaded);
                   12034: 
1.841     albertel 12035: 	my %seen;
                   12036: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   12037: 	return @uniq;
                   12038:     }
1.1074    raeburn  12039: 
                   12040:     sub internet_dom {
                   12041:         &load_hosts_tab() if (!$loaded);
                   12042: 
                   12043:         my ($lonid) = @_;
                   12044:         return $internetdom{$lonid};
                   12045:     }
1.1107    raeburn  12046: 
                   12047:     sub is_LC_dns {
                   12048:         &load_hosts_tab() if (!$loaded);
                   12049: 
                   12050:         my ($hostname) = @_;
                   12051:         return exists($LC_dns_serv{$hostname});
                   12052:     }
                   12053: 
1.1       albertel 12054: }
                   12055: 
1.847     albertel 12056: { 
                   12057:     my %iphost;
1.856     albertel 12058:     my %name_to_ip;
                   12059:     my %lonid_to_ip;
1.869     albertel 12060: 
1.847     albertel 12061:     sub get_hosts_from_ip {
                   12062: 	my ($ip) = @_;
                   12063: 	my %iphosts = &get_iphost();
                   12064: 	if (ref($iphosts{$ip})) {
                   12065: 	    return @{$iphosts{$ip}};
                   12066: 	}
                   12067: 	return;
1.839     albertel 12068:     }
1.864     albertel 12069:     
                   12070:     sub reset_hosts_ip_info {
                   12071: 	undef(%iphost);
                   12072: 	undef(%name_to_ip);
                   12073: 	undef(%lonid_to_ip);
                   12074:     }
1.856     albertel 12075: 
                   12076:     sub get_host_ip {
                   12077: 	my ($lonid) = @_;
                   12078: 	if (exists($lonid_to_ip{$lonid})) {
                   12079: 	    return $lonid_to_ip{$lonid};
                   12080: 	}
                   12081: 	my $name=&hostname($lonid);
                   12082:    	my $ip = gethostbyname($name);
                   12083: 	return if (!$ip || length($ip) ne 4);
                   12084: 	$ip=inet_ntoa($ip);
                   12085: 	$name_to_ip{$name}   = $ip;
                   12086: 	$lonid_to_ip{$lonid} = $ip;
                   12087: 	return $ip;
                   12088:     }
1.847     albertel 12089:     
                   12090:     sub get_iphost {
1.869     albertel 12091: 	my ($ignore_cache) = @_;
1.894     albertel 12092: 
1.869     albertel 12093: 	if (!$ignore_cache) {
                   12094: 	    if (%iphost) {
                   12095: 		return %iphost;
                   12096: 	    }
                   12097: 	    my ($ip_info,$cached)=
                   12098: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   12099: 	    if ($cached) {
                   12100: 		%iphost      = %{$ip_info->[0]};
                   12101: 		%name_to_ip  = %{$ip_info->[1]};
                   12102: 		%lonid_to_ip = %{$ip_info->[2]};
                   12103: 		return %iphost;
                   12104: 	    }
                   12105: 	}
1.894     albertel 12106: 
                   12107: 	# get yesterday's info for fallback
                   12108: 	my %old_name_to_ip;
                   12109: 	my ($ip_info,$cached)=
                   12110: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   12111: 	if ($cached) {
                   12112: 	    %old_name_to_ip = %{$ip_info->[1]};
                   12113: 	}
                   12114: 
1.888     albertel 12115: 	my %name_to_host = &all_names();
                   12116: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 12117: 	    my $ip;
                   12118: 	    if (!exists($name_to_ip{$name})) {
                   12119: 		$ip = gethostbyname($name);
                   12120: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 12121: 		    if (defined($old_name_to_ip{$name})) {
                   12122: 			$ip = $old_name_to_ip{$name};
                   12123: 			&logthis("Can't find $name defaulting to old $ip");
                   12124: 		    } else {
                   12125: 			&logthis("Name $name no IP found");
                   12126: 			next;
                   12127: 		    }
                   12128: 		} else {
                   12129: 		    $ip=inet_ntoa($ip);
1.847     albertel 12130: 		}
                   12131: 		$name_to_ip{$name} = $ip;
                   12132: 	    } else {
                   12133: 		$ip = $name_to_ip{$name};
1.653     albertel 12134: 	    }
1.888     albertel 12135: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   12136: 		$lonid_to_ip{$id} = $ip;
                   12137: 	    }
                   12138: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 12139: 	}
1.1172.2.23  raeburn  12140: 	&do_cache_new('iphost','iphost',
                   12141: 		      [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   12142: 		      48*60*60);
1.869     albertel 12143: 
1.847     albertel 12144: 	return %iphost;
1.598     albertel 12145:     }
                   12146: 
1.992     raeburn  12147:     #
                   12148:     #  Given a DNS returns the loncapa host name for that DNS 
                   12149:     # 
                   12150:     sub host_from_dns {
                   12151:         my ($dns) = @_;
                   12152:         my @hosts;
                   12153:         my $ip;
                   12154: 
1.993     raeburn  12155:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  12156:             $ip = $name_to_ip{$dns};
                   12157:         }
                   12158:         if (!$ip) {
                   12159:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   12160:             if (length($ip) == 4) { 
                   12161: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   12162:             }
                   12163:         }
                   12164:         if ($ip) {
                   12165: 	    @hosts = get_hosts_from_ip($ip);
                   12166: 	    return $hosts[0];
                   12167:         }
                   12168:         return undef;
1.986     foxr     12169:     }
1.992     raeburn  12170: 
1.1074    raeburn  12171:     sub get_internet_names {
                   12172:         my ($lonid) = @_;
                   12173:         return if ($lonid eq '');
                   12174:         my ($idnref,$cached)=
                   12175:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   12176:         if ($cached) {
                   12177:             return $idnref;
                   12178:         }
                   12179:         my $ip = &get_host_ip($lonid);
                   12180:         my @hosts = &get_hosts_from_ip($ip);
                   12181:         my %iphost = &get_iphost();
                   12182:         my (@idns,%seen);
                   12183:         foreach my $id (@hosts) {
                   12184:             my $dom = &host_domain($id);
                   12185:             my $prim_id = &domain($dom,'primary');
                   12186:             my $prim_ip = &get_host_ip($prim_id);
                   12187:             next if ($seen{$prim_ip});
                   12188:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   12189:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   12190:                     my $intdom = &internet_dom($id);
                   12191:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   12192:                         push(@idns,$intdom);
                   12193:                     }
                   12194:                 }
                   12195:             }
                   12196:             $seen{$prim_ip} = 1;
                   12197:         }
1.1172.2.23  raeburn  12198:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  12199:     }
                   12200: 
1.986     foxr     12201: }
                   12202: 
1.1079    raeburn  12203: sub all_loncaparevs {
                   12204:     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);
                   12205: }
                   12206: 
1.1172.2.27  raeburn  12207: # ------------------------------------------------------- Read loncaparev table
                   12208: {
                   12209:     sub load_loncaparevs {
                   12210:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   12211:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   12212:                 while (my $configline=<$config>) {
                   12213:                     chomp($configline);
                   12214:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   12215:                     $loncaparevs{$hostid}=$loncaparev;
                   12216:                 }
                   12217:                 close($config);
                   12218:             }
                   12219:         }
                   12220:     }
                   12221: }
                   12222: 
                   12223: # ----------------------------------------------------- Read serverhostID table
                   12224: {
                   12225:     sub load_serverhomeIDs {
                   12226:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   12227:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   12228:                 while (my $configline=<$config>) {
                   12229:                     chomp($configline);
                   12230:                     my ($name,$id)=split(/:/,$configline);
                   12231:                     $serverhomeIDs{$name}=$id;
                   12232:                 }
                   12233:                 close($config);
                   12234:             }
                   12235:         }
                   12236:     }
                   12237: }
                   12238: 
                   12239: 
1.862     albertel 12240: BEGIN {
                   12241: 
                   12242: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   12243:     unless ($readit) {
                   12244: {
                   12245:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   12246:     %perlvar = (%perlvar,%{$configvars});
                   12247: }
                   12248: 
                   12249: 
1.1       albertel 12250: # ------------------------------------------------------ Read spare server file
                   12251: {
1.448     albertel 12252:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 12253: 
                   12254:     while (my $configline=<$config>) {
                   12255:        chomp($configline);
1.284     matthew  12256:        if ($configline) {
1.784     albertel 12257: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 12258: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 12259: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 12260:        }
                   12261:     }
1.448     albertel 12262:     close($config);
1.1       albertel 12263: }
1.11      www      12264: # ------------------------------------------------------------ Read permissions
                   12265: {
1.448     albertel 12266:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      12267: 
                   12268:     while (my $configline=<$config>) {
1.448     albertel 12269: 	chomp($configline);
                   12270: 	if ($configline) {
                   12271: 	    my ($role,$perm)=split(/ /,$configline);
                   12272: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   12273: 	}
1.11      www      12274:     }
1.448     albertel 12275:     close($config);
1.11      www      12276: }
                   12277: 
                   12278: # -------------------------------------------- Read plain texts for permissions
                   12279: {
1.448     albertel 12280:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      12281: 
                   12282:     while (my $configline=<$config>) {
1.448     albertel 12283: 	chomp($configline);
                   12284: 	if ($configline) {
1.742     raeburn  12285: 	    my ($short,@plain)=split(/:/,$configline);
                   12286:             %{$prp{$short}} = ();
                   12287: 	    if (@plain > 0) {
                   12288:                 $prp{$short}{'std'} = $plain[0];
                   12289:                 for (my $i=1; $i<@plain; $i++) {
                   12290:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   12291:                 }
                   12292:             }
1.448     albertel 12293: 	}
1.135     www      12294:     }
1.448     albertel 12295:     close($config);
1.135     www      12296: }
                   12297: 
                   12298: # ---------------------------------------------------------- Read package table
                   12299: {
1.448     albertel 12300:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      12301: 
                   12302:     while (my $configline=<$config>) {
1.483     albertel 12303: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 12304: 	chomp($configline);
                   12305: 	my ($short,$plain)=split(/:/,$configline);
                   12306: 	my ($pack,$name)=split(/\&/,$short);
                   12307: 	if ($plain ne '') {
                   12308: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   12309: 	    $packagetab{$short}=$plain; 
                   12310: 	}
1.11      www      12311:     }
1.448     albertel 12312:     close($config);
1.329     matthew  12313: }
                   12314: 
1.1172.2.27  raeburn  12315: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  12316: 
1.1172.2.27  raeburn  12317: &load_loncaparevs();
                   12318: 
                   12319: # ------------------------------------------------------- Read serverhostID table
                   12320: 
                   12321: &load_serverhomeIDs();
1.1074    raeburn  12322: 
1.1172.2.27  raeburn  12323: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  12324: {
                   12325:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   12326:     if (-e $file) {
                   12327:         my $parser = HTML::LCParser->new($file);
                   12328:         while (my $token = $parser->get_token()) {
                   12329:             if ($token->[0] eq 'S') {
                   12330:                 my $item = $token->[1];
                   12331:                 my $name = $token->[2]{'name'};
                   12332:                 my $value = $token->[2]{'value'};
                   12333:                 if ($item ne '' && $name ne '' && $value ne '') {
                   12334:                     my $release = $parser->get_text();
                   12335:                     $release =~ s/(^\s*|\s*$ )//gx;
                   12336:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   12337:                 }
                   12338:             }
                   12339:         }
                   12340:     }
1.1073    raeburn  12341: }
                   12342: 
1.1138    raeburn  12343: # ---------------------------------------------------------- Read managers table
                   12344: {
                   12345:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   12346:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   12347:             while (my $configline=<$config>) {
                   12348:                 chomp($configline);
                   12349:                 next if ($configline =~ /^\#/);
                   12350:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   12351:                     $managerstab{$configline} = 1;
                   12352:                 }
                   12353:             }
                   12354:             close($config);
                   12355:         }
                   12356:     }
                   12357: }
                   12358: 
1.329     matthew  12359: # ------------- set up temporary directory
                   12360: {
1.1117    foxr     12361:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  12362: 
1.11      www      12363: }
                   12364: 
1.794     albertel 12365: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   12366: 				'compress_threshold'=> 20_000,
                   12367:  			        });
1.185     www      12368: 
1.281     www      12369: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      12370: $dumpcount=0;
1.958     www      12371: $locknum=0;
1.22      www      12372: 
1.163     harris41 12373: &logtouch();
1.672     albertel 12374: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      12375: $readit=1;
1.564     albertel 12376:     {
                   12377: 	use integer;
                   12378: 	my $test=(2**32)+1;
1.568     albertel 12379: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 12380: 	&logthis(" Detected 64bit platform ($_64bit)");
                   12381:     }
1.1172.2.18  raeburn  12382: 
                   12383:     {
                   12384:         eval {
                   12385:             ($apache) =
                   12386:                 (Apache2::ServerUtil::get_server_version() =~ m{Apache/(\d+\.\d+)});
                   12387:         };
                   12388:         if ($@) {
                   12389:            $apache = 1.3;
                   12390:         }
                   12391:     }
                   12392: 
1.195     www      12393: }
1.1       albertel 12394: }
1.179     www      12395: 
1.1       albertel 12396: 1;
1.191     harris41 12397: __END__
                   12398: 
1.243     albertel 12399: =pod
                   12400: 
1.191     harris41 12401: =head1 NAME
                   12402: 
1.243     albertel 12403: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 12404: 
                   12405: =head1 SYNOPSIS
                   12406: 
1.243     albertel 12407: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 12408: 
                   12409:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   12410: 
1.243     albertel 12411: Common parameters:
                   12412: 
                   12413: =over 4
                   12414: 
                   12415: =item *
                   12416: 
                   12417: $uname : an internal username (if $cname expecting a course Id specifically)
                   12418: 
                   12419: =item *
                   12420: 
                   12421: $udom : a domain (if $cdom expecting a course's domain specifically)
                   12422: 
                   12423: =item *
                   12424: 
                   12425: $symb : a resource instance identifier
                   12426: 
                   12427: =item *
                   12428: 
                   12429: $namespace : the name of a .db file that contains the data needed or
                   12430: being set.
                   12431: 
                   12432: =back
                   12433: 
1.394     bowersj2 12434: =head1 OVERVIEW
1.191     harris41 12435: 
1.394     bowersj2 12436: lonnet provides subroutines which interact with the
                   12437: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   12438: about classes, users, and resources.
1.243     albertel 12439: 
                   12440: For many of these objects you can also use this to store data about
                   12441: them or modify them in various ways.
1.191     harris41 12442: 
1.394     bowersj2 12443: =head2 Symbs
1.191     harris41 12444: 
1.394     bowersj2 12445: To identify a specific instance of a resource, LON-CAPA uses symbols
                   12446: or "symbs"X<symb>. These identifiers are built from the URL of the
                   12447: map, the resource number of the resource in the map, and the URL of
                   12448: the resource itself. The latter is somewhat redundant, but might help
                   12449: if maps change.
                   12450: 
                   12451: An example is
                   12452: 
                   12453:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   12454: 
                   12455: The respective map entry is
                   12456: 
                   12457:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   12458:   title="Problem 2">
                   12459:  </resource>
                   12460: 
                   12461: Symbs are used by the random number generator, as well as to store and
                   12462: restore data specific to a certain instance of for example a problem.
                   12463: 
                   12464: =head2 Storing And Retrieving Data
                   12465: 
                   12466: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   12467: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   12468: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   12469: is is the non-critical message twin of cstore. These functions are for
                   12470: handlers to store a perl hash to a user's permanent data space in an
                   12471: easy manner, and to retrieve it again on another call. It is expected
                   12472: that a handler would use this once at the beginning to retrieve data,
                   12473: and then again once at the end to send only the new data back.
                   12474: 
                   12475: The data is stored in the user's data directory on the user's
                   12476: homeserver under the ID of the course.
                   12477: 
                   12478: The hash that is returned by restore will have all of the previous
                   12479: value for all of the elements of the hash.
                   12480: 
                   12481: Example:
                   12482: 
                   12483:  #creating a hash
                   12484:  my %hash;
                   12485:  $hash{'foo'}='bar';
                   12486: 
                   12487:  #storing it
                   12488:  &Apache::lonnet::cstore(\%hash);
                   12489: 
                   12490:  #changing a value
                   12491:  $hash{'foo'}='notbar';
                   12492: 
                   12493:  #adding a new value
                   12494:  $hash{'bar'}='foo';
                   12495:  &Apache::lonnet::cstore(\%hash);
                   12496: 
                   12497:  #retrieving the hash
                   12498:  my %history=&Apache::lonnet::restore();
                   12499: 
                   12500:  #print the hash
                   12501:  foreach my $key (sort(keys(%history))) {
                   12502:    print("\%history{$key} = $history{$key}");
                   12503:  }
                   12504: 
                   12505: Will print out:
1.191     harris41 12506: 
1.394     bowersj2 12507:  %history{1:foo} = bar
                   12508:  %history{1:keys} = foo:timestamp
                   12509:  %history{1:timestamp} = 990455579
                   12510:  %history{2:bar} = foo
                   12511:  %history{2:foo} = notbar
                   12512:  %history{2:keys} = foo:bar:timestamp
                   12513:  %history{2:timestamp} = 990455580
                   12514:  %history{bar} = foo
                   12515:  %history{foo} = notbar
                   12516:  %history{timestamp} = 990455580
                   12517:  %history{version} = 2
                   12518: 
                   12519: Note that the special hash entries C<keys>, C<version> and
                   12520: C<timestamp> were added to the hash. C<version> will be equal to the
                   12521: total number of versions of the data that have been stored. The
                   12522: C<timestamp> attribute will be the UNIX time the hash was
                   12523: stored. C<keys> is available in every historical section to list which
                   12524: keys were added or changed at a specific historical revision of a
                   12525: hash.
                   12526: 
                   12527: B<Warning>: do not store the hash that restore returns directly. This
                   12528: will cause a mess since it will restore the historical keys as if the
                   12529: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 12530: 
1.394     bowersj2 12531: Calling convention:
1.191     harris41 12532: 
1.1172.2.27  raeburn  12533:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
                   12534:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname);
1.191     harris41 12535: 
1.394     bowersj2 12536: For more detailed information, see lonnet specific documentation.
1.191     harris41 12537: 
1.394     bowersj2 12538: =head1 RETURN MESSAGES
1.191     harris41 12539: 
1.394     bowersj2 12540: =over 4
1.191     harris41 12541: 
1.394     bowersj2 12542: =item * B<con_lost>: unable to contact remote host
1.191     harris41 12543: 
1.394     bowersj2 12544: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   12545: when the connection is brought back up
1.191     harris41 12546: 
1.394     bowersj2 12547: =item * B<con_failed>: unable to contact remote host and unable to save message
                   12548: for later delivery
1.191     harris41 12549: 
1.967     bisitz   12550: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 12551: 
1.394     bowersj2 12552: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 12553: that was requested
1.191     harris41 12554: 
1.243     albertel 12555: =back
1.191     harris41 12556: 
1.243     albertel 12557: =head1 PUBLIC SUBROUTINES
1.191     harris41 12558: 
1.243     albertel 12559: =head2 Session Environment Functions
1.191     harris41 12560: 
1.243     albertel 12561: =over 4
1.191     harris41 12562: 
1.394     bowersj2 12563: =item * 
                   12564: X<appenv()>
1.949     raeburn  12565: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 12566: the user envirnoment file, and will be restored for each access this
1.620     albertel 12567: user makes during this session, also modifies the %env for the current
1.949     raeburn  12568: process. Optional rolesarrayref - if defined contains a reference to an array
                   12569: of roles which are exempt from the restriction on modifying user.role entries 
                   12570: in the user's environment.db and in %env.    
1.191     harris41 12571: 
                   12572: =item *
1.394     bowersj2 12573: X<delenv()>
1.987     raeburn  12574: B<delenv($delthis,$regexp)>: removes all items from the session
                   12575: environment file that begin with $delthis. If the 
                   12576: optional second arg - $regexp - is true, $delthis is treated as a 
                   12577: regular expression, otherwise \Q$delthis\E is used. 
                   12578: The values are also deleted from the current processes %env.
1.191     harris41 12579: 
1.795     albertel 12580: =item * get_env_multiple($name) 
                   12581: 
                   12582: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   12583: values may be defined and end up as an array ref.
                   12584: 
                   12585: returns an array of values
                   12586: 
1.243     albertel 12587: =back
                   12588: 
                   12589: =head2 User Information
1.191     harris41 12590: 
1.243     albertel 12591: =over 4
1.191     harris41 12592: 
                   12593: =item *
1.394     bowersj2 12594: X<queryauthenticate()>
                   12595: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 12596: authentication scheme
                   12597: 
                   12598: =item *
1.394     bowersj2 12599: X<authenticate()>
1.1073    raeburn  12600: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 12601: authenticate user from domain's lib servers (first use the current
                   12602: one). C<$upass> should be the users password.
1.1073    raeburn  12603: $checkdefauth is optional (value is 1 if a check should be made to
                   12604:    authenticate user using default authentication method, and allow
                   12605:    account creation if username does not have account in the domain).
                   12606: $clientcancheckhost is optional (value is 1 if checking whether the
                   12607:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 12608: 
                   12609: =item *
1.394     bowersj2 12610: X<homeserver()>
                   12611: B<homeserver($uname,$udom)>: find the server which has
                   12612: the user's directory and files (there must be only one), this caches
                   12613: the answer, and also caches if there is a borken connection.
1.191     harris41 12614: 
                   12615: =item *
1.394     bowersj2 12616: X<idget()>
                   12617: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   12618: (IDs are a unique resource in a domain, there must be only 1 ID per
                   12619: username, and only 1 username per ID in a specific domain) (returns
                   12620: hash: id=>name,id=>name)
1.191     harris41 12621: 
                   12622: =item *
1.394     bowersj2 12623: X<idrget()>
                   12624: B<idrget($udom,@unames)>: find the IDs behind a list of
                   12625: usernames (returns hash: name=>id,name=>id)
1.191     harris41 12626: 
                   12627: =item *
1.394     bowersj2 12628: X<idput()>
                   12629: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 12630: 
                   12631: =item *
1.394     bowersj2 12632: X<rolesinit()>
1.1169    droeschl 12633: B<rolesinit($udom,$username)>: get user privileges.
                   12634: returns user role, first access and timer interval hashes
1.243     albertel 12635: 
                   12636: =item *
1.1171    droeschl 12637: X<privileged()>
                   12638: B<privileged($username,$domain)>: returns a true if user has a
                   12639: privileged and active role (i.e. su or dc), false otherwise.
                   12640: 
                   12641: =item *
1.551     albertel 12642: X<getsection()>
                   12643: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 12644: course $cname, return section name/number or '' for "not in course"
                   12645: and '-1' for "no section"
                   12646: 
                   12647: =item *
1.394     bowersj2 12648: X<userenvironment()>
                   12649: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 12650: passed in @what from the requested user's environment, returns a hash
                   12651: 
1.858     raeburn  12652: =item * 
                   12653: X<userlog_query()>
1.859     albertel 12654: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   12655: activity.log file. %filters defines filters applied when parsing the
                   12656: log file. These can be start or end timestamps, or the type of action
                   12657: - log to look for Login or Logout events, check for Checkin or
                   12658: Checkout, role for role selection. The response is in the form
                   12659: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   12660: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  12661: 
1.243     albertel 12662: =back
                   12663: 
                   12664: =head2 User Roles
                   12665: 
                   12666: =over 4
                   12667: 
                   12668: =item *
                   12669: 
1.810     raeburn  12670: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 12671:  F: full access
                   12672:  U,I,K: authentication modes (cxx only)
                   12673:  '': forbidden
                   12674:  1: user needs to choose course
                   12675:  2: browse allowed
1.766     albertel 12676:  A: passphrase authentication needed
1.243     albertel 12677: 
                   12678: =item *
                   12679: 
1.1172.2.13  raeburn  12680: constructaccess($url,$setpriv) : check for access to construction space URL
                   12681: 
                   12682: See if the owner domain and name in the URL match those in the
                   12683: expected environment.  If so, return three element list
                   12684: ($ownername,$ownerdomain,$ownerhome).
                   12685: 
                   12686: Otherwise return the null string.
                   12687: 
                   12688: If second argument 'setpriv' is true, it assigns the privileges,
                   12689: and returns the same three element list, unless the owner has
                   12690: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   12691: in which case the null string is returned.
                   12692: 
                   12693: =item *
                   12694: 
1.243     albertel 12695: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   12696: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   12697: and course level
                   12698: 
                   12699: =item *
                   12700: 
1.988     raeburn  12701: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   12702: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  12703: $type is Course (default) or Community.
1.988     raeburn  12704: If $forcedefault evaluates to true, text returned will be default 
                   12705: text for $type. Otherwise, if this is a course, the text returned 
                   12706: will be a custom name for the role (if defined in the course's 
                   12707: environment).  If no custom name is defined the default is returned.
                   12708:    
1.832     raeburn  12709: =item *
                   12710: 
1.1172.2.23  raeburn  12711: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  12712: All arguments are optional. Returns a hash of a roles, either for
                   12713: co-author/assistant author roles for a user's Construction Space
1.906     albertel 12714: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  12715: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   12716: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   12717: For each key, value is set to colon-separated start and end times for
                   12718: the role.  If no username and domain are specified, will default to
1.934     raeburn  12719: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  12720: of role statuses (active, future or previous), roles 
                   12721: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   12722: to restrict the list of roles reported. If no array ref is 
                   12723: provided for types, will default to return only active roles.
1.834     albertel 12724: 
1.1172.2.13  raeburn  12725: =item *
                   12726: 
                   12727: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   12728: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   12729: 
                   12730: Additional optional arguments are: $type (if role checking is to be restricted
                   12731: to certain user status types -- previous (expired roles), active (currently
                   12732: available roles) or future (roles available in the future), and
                   12733: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  12734: have active Domain Coordinator role in course's domain or in additional
                   12735: domains (specified in 'Domains to check for privileged users' in course
                   12736: environment -- set via:  Course Settings -> Classlists and staff listing).
                   12737: 
                   12738: =item *
                   12739: 
                   12740: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   12741: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   12742: $possdomains and $possroles are optional array refs -- to domains to check and
                   12743: roles to check.  If $possdomains is not specified, a dump will be done of the
                   12744: users' roles.db to check for a dc or su role in any domain. This can be
                   12745: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   12746: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   12747: this then allows &privileged_by_domain() to be used, which caches the identity
                   12748: of privileged users, eliminating the need for repeated calls to &dump().
                   12749: 
                   12750: =item *
                   12751: 
                   12752: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   12753: where the outer hash keys are domains specified in the $possdomains array ref,
                   12754: next inner hash keys are privileged roles specified in the $roles array ref,
                   12755: and the innermost hash contains key = value pairs for username:domain = end:start
                   12756: for active or future "privileged" users with that role in that domain. To avoid
                   12757: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   12758: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  12759: 
1.243     albertel 12760: =back
                   12761: 
                   12762: =head2 User Modification
                   12763: 
                   12764: =over 4
                   12765: 
                   12766: =item *
                   12767: 
1.957     raeburn  12768: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 12769: user for the level given by URL.  Optional start and end dates (leave empty
                   12770: string or zero for "no date")
1.191     harris41 12771: 
                   12772: =item *
                   12773: 
1.243     albertel 12774: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   12775: change a users, password, possible return values are: ok,
                   12776: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   12777: refused
1.191     harris41 12778: 
                   12779: =item *
                   12780: 
1.243     albertel 12781: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 12782: 
                   12783: =item *
                   12784: 
1.1058    raeburn  12785: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   12786:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   12787: 
                   12788: will update user information (firstname,middlename,lastname,generation,
                   12789: permanentemail), and if forceid is true, student/employee ID also.
                   12790: A user's institutional affiliation(s) can also be updated.
                   12791: User information fields will not be overwritten with empty entries 
                   12792: unless the field is included in the $candelete array reference.
                   12793: This array is included when a single user is modified via "Manage Users",
                   12794: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 12795: 
                   12796: =item *
                   12797: 
1.286     matthew  12798: modifystudent
                   12799: 
1.957     raeburn  12800: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  12801: The course id is resolved based on the current user's environment.  
                   12802: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  12803: associated with a course.
                   12804: 
1.297     matthew  12805: This call is essentially a wrapper for lonnet::modifyuser and
                   12806: lonnet::modify_student_enrollment
1.286     matthew  12807: 
                   12808: Inputs: 
                   12809: 
                   12810: =over 4
                   12811: 
1.957     raeburn  12812: =item B<$udom> Student's loncapa domain
1.286     matthew  12813: 
1.957     raeburn  12814: =item B<$uname> Student's loncapa login name
1.286     matthew  12815: 
1.964     bisitz   12816: =item B<$uid> Student/Employee ID
1.286     matthew  12817: 
1.957     raeburn  12818: =item B<$umode> Student's authentication mode
1.286     matthew  12819: 
1.957     raeburn  12820: =item B<$upass> Student's password
1.286     matthew  12821: 
1.957     raeburn  12822: =item B<$first> Student's first name
1.286     matthew  12823: 
1.957     raeburn  12824: =item B<$middle> Student's middle name
1.286     matthew  12825: 
1.957     raeburn  12826: =item B<$last> Student's last name
1.286     matthew  12827: 
1.957     raeburn  12828: =item B<$gene> Student's generation
1.286     matthew  12829: 
1.957     raeburn  12830: =item B<$usec> Student's section in course
1.286     matthew  12831: 
                   12832: =item B<$end> Unix time of the roles expiration
                   12833: 
                   12834: =item B<$start> Unix time of the roles start date
                   12835: 
                   12836: =item B<$forceid> If defined, allow $uid to be changed
                   12837: 
                   12838: =item B<$desiredhome> server to use as home server for student
                   12839: 
1.957     raeburn  12840: =item B<$email> Student's permanent e-mail address
                   12841: 
                   12842: =item B<$type> Type of enrollment (auto or manual)
                   12843: 
1.963     raeburn  12844: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   12845: 
                   12846: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  12847: 
1.963     raeburn  12848: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  12849: 
1.963     raeburn  12850: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  12851: 
1.1172.2.19  raeburn  12852: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   12853: 
                   12854: =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  12855: 
1.286     matthew  12856: =back
1.297     matthew  12857: 
                   12858: =item *
                   12859: 
                   12860: modify_student_enrollment
                   12861: 
1.1172.2.31  raeburn  12862: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  12863: 'role.request.course' must be defined for this function to proceed.
                   12864: 
                   12865: Inputs:
                   12866: 
                   12867: =over 4
                   12868: 
1.1172.2.31  raeburn  12869: =item $udom, student's domain
1.297     matthew  12870: 
1.1172.2.31  raeburn  12871: =item $uname, student's name
1.297     matthew  12872: 
1.1172.2.31  raeburn  12873: =item $uid, student's user id
1.297     matthew  12874: 
1.1172.2.31  raeburn  12875: =item $first, student's first name
1.297     matthew  12876: 
                   12877: =item $middle
                   12878: 
                   12879: =item $last
                   12880: 
                   12881: =item $gene
                   12882: 
                   12883: =item $usec
                   12884: 
                   12885: =item $end
                   12886: 
                   12887: =item $start
                   12888: 
1.957     raeburn  12889: =item $type
                   12890: 
                   12891: =item $locktype
                   12892: 
                   12893: =item $cid
                   12894: 
                   12895: =item $selfenroll
                   12896: 
                   12897: =item $context
                   12898: 
1.1172.2.19  raeburn  12899: =item $credits, number of credits student will earn from this class
                   12900: 
1.297     matthew  12901: =back
                   12902: 
1.191     harris41 12903: 
                   12904: =item *
                   12905: 
1.243     albertel 12906: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   12907: custom role; give a custom role to a user for the level given by URL.  Specify
                   12908: name and domain of role author, and role name
1.191     harris41 12909: 
                   12910: =item *
                   12911: 
1.243     albertel 12912: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 12913: 
                   12914: =item *
                   12915: 
1.243     albertel 12916: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   12917: 
                   12918: =back
                   12919: 
                   12920: =head2 Course Infomation
                   12921: 
                   12922: =over 4
1.191     harris41 12923: 
                   12924: =item *
                   12925: 
1.1118    foxr     12926: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 12927: specified course id, including all environment settings for the
                   12928: course, the description of the course will be in the hash under the
                   12929: key 'description'
1.191     harris41 12930: 
1.1118    foxr     12931: $options is an optional parameter that if supplied is a hash reference that controls
                   12932: what how this function works.  It has the following key/values:
                   12933: 
                   12934: =over 4
                   12935: 
                   12936: =item freshen_cache
                   12937: 
                   12938: If defined, and the environment cache for the course is valid, it is 
                   12939: returned in the returned hash.
                   12940: 
                   12941: =item one_time
                   12942: 
                   12943: If defined, the last cache time is set to _now_
                   12944: 
                   12945: =item user
                   12946: 
                   12947: If defined, the supplied username is used instead of the current user.
                   12948: 
                   12949: 
                   12950: =back
                   12951: 
1.191     harris41 12952: =item *
                   12953: 
1.624     albertel 12954: resdata($name,$domain,$type,@which) : request for current parameter
                   12955: setting for a specific $type, where $type is either 'course' or 'user',
                   12956: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  12957: answers for 10 minutes.
1.243     albertel 12958: 
1.877     foxr     12959: =item *
                   12960: 
                   12961: get_courseresdata($courseid, $domain) : dump the entire course resource
                   12962: data base, returning a hash that is keyed by the resource name and has
                   12963: values that are the resource value.  I believe that the timestamps and
                   12964: versions are also returned.
                   12965: 
1.1172.2.31  raeburn  12966: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   12967: supplemental content area. This routine caches the number of files for
                   12968: 10 minutes.
                   12969: 
1.243     albertel 12970: =back
                   12971: 
                   12972: =head2 Course Modification
                   12973: 
                   12974: =over 4
1.191     harris41 12975: 
                   12976: =item *
                   12977: 
1.243     albertel 12978: writecoursepref($courseid,%prefs) : write preferences (environment
                   12979: database) for a course
1.191     harris41 12980: 
                   12981: =item *
                   12982: 
1.1011    raeburn  12983: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   12984: 
                   12985: =item *
                   12986: 
1.1038    raeburn  12987: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 12988: 
1.1167    droeschl 12989: =item *
                   12990: 
                   12991: is_course($courseid), is_course($cdom, $cnum)
                   12992: 
                   12993: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   12994: two component version $cdom, $cnum. It checks if the specified course exists.
                   12995: 
                   12996: Returns:
                   12997:     undef if the course doesn't exist, otherwise
                   12998:     in scalar context the combined courseid.
                   12999:     in list context the two components of the course identifier, domain and 
                   13000:     courseid.    
                   13001: 
1.243     albertel 13002: =back
                   13003: 
                   13004: =head2 Resource Subroutines
                   13005: 
                   13006: =over 4
1.191     harris41 13007: 
                   13008: =item *
                   13009: 
1.243     albertel 13010: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 13011: 
                   13012: =item *
                   13013: 
1.243     albertel 13014: repcopy($filename) : subscribes to the requested file, and attempts to
                   13015: replicate from the owning library server, Might return
1.607     raeburn  13016: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   13017: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 13018: resource. Expects the local filesystem pathname
                   13019: (/home/httpd/html/res/....)
                   13020: 
                   13021: =back
                   13022: 
                   13023: =head2 Resource Information
                   13024: 
                   13025: =over 4
1.191     harris41 13026: 
                   13027: =item *
                   13028: 
1.1172.2.28  raeburn  13029: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   13030: and returns the value of a variety of different possible values,
                   13031: $varname should be a request string, and the other parameters can be
                   13032: used to specify who and what one is asking about. Ordinarily, $cid 
                   13033: does not need to be specified, as it is retrived from 
                   13034: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   13035: within lonuserstate::loadmap() when initializing a course, before
                   13036: $env{'request.course.id'} has been set, so it needs to be provided
                   13037: in that one case.
1.243     albertel 13038: 
                   13039: Possible values for $varname are environment.lastname (or other item
                   13040: from the envirnment hash), user.name (or someother aspect about the
                   13041: user), resource.0.maxtries (or some other part and parameter of a
                   13042: resource)
1.204     albertel 13043: 
                   13044: =item *
                   13045: 
1.243     albertel 13046: directcondval($number) : get current value of a condition; reads from a state
                   13047: string
1.204     albertel 13048: 
                   13049: =item *
                   13050: 
1.243     albertel 13051: condval($condidx) : value of condition index based on state
1.204     albertel 13052: 
                   13053: =item *
                   13054: 
1.243     albertel 13055: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   13056: resource's metadata, $what should be either a specific key, or either
                   13057: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   13058: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   13059: 
                   13060: this function automatically caches all requests
1.191     harris41 13061: 
                   13062: =item *
                   13063: 
1.243     albertel 13064: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   13065: network of library servers; returns file handle of where SQL and regex results
                   13066: will be stored for query
1.191     harris41 13067: 
                   13068: =item *
                   13069: 
1.243     albertel 13070: symbread($filename) : return symbolic list entry (filename argument optional);
                   13071: returns the data handle
1.191     harris41 13072: 
                   13073: =item *
                   13074: 
1.1172.2.17  raeburn  13075: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  13076: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 13077: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  13078: on failure, user must be in a course, as it assumes the existence of
                   13079: the course initial hash, and uses $env('request.course.id'}.  The third
                   13080: arg is an optional reference to a scalar.  If this arg is passed in the
                   13081: call to symbverify, it will be set to 1 if the symb has been set to be 
                   13082: encrypted; otherwise it will be null.
1.243     albertel 13083: 
1.191     harris41 13084: =item *
                   13085: 
1.243     albertel 13086: symbclean($symb) : removes versions numbers from a symb, returns the
                   13087: cleaned symb
1.191     harris41 13088: 
                   13089: =item *
                   13090: 
1.243     albertel 13091: is_on_map($uri) : checks if the $uri is somewhere on the current
                   13092: course map, user must be in a course for it to work.
1.191     harris41 13093: 
                   13094: =item *
                   13095: 
1.243     albertel 13096: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 13097: 
                   13098: =item *
                   13099: 
1.243     albertel 13100: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   13101: a random seed, all arguments are optional, if they aren't sent it uses the
                   13102: environment to derive them. Note: if symb isn't sent and it can't get one
                   13103: from &symbread it will use the current time as its return value
1.191     harris41 13104: 
                   13105: =item *
                   13106: 
1.243     albertel 13107: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   13108: unfakeable, receipt
1.191     harris41 13109: 
                   13110: =item *
                   13111: 
1.620     albertel 13112: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 13113: 
                   13114: =item *
                   13115: 
1.243     albertel 13116: countacc($url) : count the number of accesses to a given URL
1.191     harris41 13117: 
                   13118: =item *
                   13119: 
1.243     albertel 13120: 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 13121: 
                   13122: =item *
                   13123: 
1.243     albertel 13124: 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 13125: 
                   13126: =item *
                   13127: 
1.243     albertel 13128: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 13129: 
                   13130: =item *
                   13131: 
1.243     albertel 13132: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   13133: forcing spreadsheet to reevaluate the resource scores next time.
                   13134: 
1.1172.2.13  raeburn  13135: =item *
                   13136: 
                   13137: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   13138: when viewing in course context.
                   13139: 
                   13140:  input: six args -- filename (decluttered), course number, course domain,
                   13141:                     url, symb (if registered) and group (if this is a
                   13142:                     group item -- e.g., bulletin board, group page etc.).
                   13143: 
                   13144:  output: array of five scalars --
                   13145:          $cfile -- url for file editing if editable on current server
                   13146:          $home -- homeserver of resource (i.e., for author if published,
                   13147:                                           or course if uploaded.).
                   13148:          $switchserver --  1 if server switch will be needed.
                   13149:          $forceedit -- 1 if icon/link should be to go to edit mode
                   13150:          $forceview -- 1 if icon/link should be to go to view mode
                   13151: 
                   13152: =item *
                   13153: 
                   13154: is_course_upload($file,$cnum,$cdom)
                   13155: 
                   13156: Used in course context to determine if current file was uploaded to
                   13157: the course (i.e., would be found in /userfiles/docs on the course's
                   13158: homeserver.
                   13159: 
                   13160:   input: 3 args -- filename (decluttered), course number and course domain.
                   13161:   output: boolean -- 1 if file was uploaded.
                   13162: 
1.243     albertel 13163: =back
                   13164: 
                   13165: =head2 Storing/Retreiving Data
                   13166: 
                   13167: =over 4
1.191     harris41 13168: 
                   13169: =item *
                   13170: 
1.243     albertel 13171: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   13172: for this url; hashref needs to be given and should be a \%hashname; the
                   13173: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 13174: be derived from the env
1.191     harris41 13175: 
                   13176: =item *
                   13177: 
1.243     albertel 13178: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   13179: uses critical subroutine
1.191     harris41 13180: 
                   13181: =item *
                   13182: 
1.243     albertel 13183: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   13184: all args are optional
1.191     harris41 13185: 
                   13186: =item *
                   13187: 
1.717     albertel 13188: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   13189: dumps the complete (or key matching regexp) namespace into a hash
                   13190: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   13191: normally &store()ed into
                   13192: 
                   13193: $range should be either an integer '100' (give me the first 100
                   13194:                                            matching records)
                   13195:               or be  two integers sperated by a - with no spaces
                   13196:                  '30-50' (give me the 30th through the 50th matching
                   13197:                           records)
                   13198: 
                   13199: 
                   13200: =item *
                   13201: 
                   13202: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   13203: replaces a &store() version of data with a replacement set of data
                   13204: for a particular resource in a namespace passed in the $storehash hash 
                   13205: reference
                   13206: 
                   13207: =item *
                   13208: 
1.243     albertel 13209: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   13210: works very similar to store/cstore, but all data is stored in a
                   13211: temporary location and can be reset using tmpreset, $storehash should
                   13212: be a hash reference, returns nothing on success
1.191     harris41 13213: 
                   13214: =item *
                   13215: 
1.243     albertel 13216: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   13217: similar to restore, but all data is stored in a temporary location and
                   13218: can be reset using tmpreset. Returns a hash of values on success,
                   13219: error string otherwise.
1.191     harris41 13220: 
                   13221: =item *
                   13222: 
1.243     albertel 13223: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   13224: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 13225: 
                   13226: =item *
                   13227: 
1.243     albertel 13228: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13229: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 13230: 
                   13231: =item *
                   13232: 
1.243     albertel 13233: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   13234: namesp ($udom and $uname are optional)
1.191     harris41 13235: 
                   13236: =item *
                   13237: 
1.702     albertel 13238: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 13239: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 13240: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  13241: 
1.702     albertel 13242: $range should be either an integer '100' (give me the first 100
                   13243:                                            matching records)
                   13244:               or be  two integers sperated by a - with no spaces
                   13245:                  '30-50' (give me the 30th through the 50th matching
                   13246:                           records)
1.449     matthew  13247: =item *
                   13248: 
                   13249: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   13250: $store can be a scalar, an array reference, or if the amount to be 
                   13251: incremented is > 1, a hash reference.
                   13252: 
                   13253: ($udom and $uname are optional)
1.191     harris41 13254: 
                   13255: =item *
                   13256: 
1.243     albertel 13257: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   13258: ($udom and $uname are optional)
1.191     harris41 13259: 
                   13260: =item *
                   13261: 
1.243     albertel 13262: cput($namespace,$storehash,$udom,$uname) : critical put
                   13263: ($udom and $uname are optional)
1.191     harris41 13264: 
                   13265: =item *
                   13266: 
1.748     albertel 13267: newput($namespace,$storehash,$udom,$uname) :
                   13268: 
                   13269: Attempts to store the items in the $storehash, but only if they don't
                   13270: currently exist, if this succeeds you can be certain that you have 
                   13271: successfully created a new key value pair in the $namespace db.
                   13272: 
                   13273: 
                   13274: Args:
                   13275:  $namespace: name of database to store values to
                   13276:  $storehash: hashref to store to the db
                   13277:  $udom: (optional) domain of user containing the db
                   13278:  $uname: (optional) name of user caontaining the db
                   13279: 
                   13280: Returns:
                   13281:  'ok' -> succeeded in storing all keys of $storehash
                   13282:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   13283:                         least <key> already existed in the db (other
                   13284:                         requested keys may also already exist)
1.967     bisitz   13285:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 13286:  'con_lost' -> unable to contact request server
                   13287:  'refused' -> action was not allowed by remote machine
                   13288: 
                   13289: 
                   13290: =item *
                   13291: 
1.243     albertel 13292: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13293: reference filled in from namesp (encrypts the return communication)
                   13294: ($udom and $uname are optional)
1.191     harris41 13295: 
                   13296: =item *
                   13297: 
1.243     albertel 13298: log($udom,$name,$home,$message) : write to permanent log for user; use
                   13299: critical subroutine
                   13300: 
1.806     raeburn  13301: =item *
                   13302: 
1.860     raeburn  13303: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   13304: array reference filled in from namespace found in domain level on either
                   13305: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  13306: 
                   13307: =item *
                   13308: 
1.860     raeburn  13309: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   13310: domain level either on specified domain server ($uhome) or primary domain 
                   13311: server ($udom and $uhome are optional)
1.806     raeburn  13312: 
1.943     raeburn  13313: =item * 
                   13314: 
1.1172.2.35! raeburn  13315: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
        !          13316: for: authentication, language, quotas, timezone, date locale, and portal URL in
        !          13317: the target domain.
        !          13318: 
        !          13319: May also include additional key => value pairs for the following groups:
        !          13320: 
        !          13321: =over
        !          13322: 
        !          13323: =item
        !          13324: disk quotas (MB allocated by default to portfolios and authoring spaces).
        !          13325: 
        !          13326: =over
        !          13327: 
        !          13328: =item defaultquota, authorquota
        !          13329: 
        !          13330: =back
        !          13331: 
        !          13332: =item
        !          13333: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
        !          13334: portfolio for users).
        !          13335: 
        !          13336: =over
        !          13337: 
        !          13338: =item
        !          13339: aboutme, blog, webdav, portfolio
        !          13340: 
        !          13341: =back
        !          13342: 
        !          13343: =item
        !          13344: requestcourses: ability to request courses, and how requests are processed.
        !          13345: 
        !          13346: =over
        !          13347: 
        !          13348: =item
        !          13349: official, unofficial, community
        !          13350: 
        !          13351: =back
        !          13352: 
        !          13353: =item
        !          13354: inststatus: types of institutional affiliation, and order in which they are displayed.
        !          13355: 
        !          13356: =over
        !          13357: 
        !          13358: =item
        !          13359: inststatustypes, inststatusorder
        !          13360: 
        !          13361: =back
        !          13362: 
        !          13363: =item
        !          13364: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
        !          13365: for course's uploaded content.
        !          13366: 
        !          13367: =over
        !          13368: 
        !          13369: =item
        !          13370: canuse_pdfforms, officialcredits, unofficialcredits, officialquota, unofficialquota, communityquota
        !          13371: 
        !          13372: =back
        !          13373: 
        !          13374: =item
        !          13375: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
        !          13376: on your servers.
        !          13377: 
        !          13378: =over
        !          13379: 
        !          13380: =item
        !          13381: remotesessions, hostedsessions
        !          13382: 
        !          13383: =back
        !          13384: 
        !          13385: =back
        !          13386: 
        !          13387: In cases where a domain coordinator has never used the "Set Domain Configuration"
        !          13388: utility to create a configuration.db file on a domain's primary library server
        !          13389: only the following domain defaults: auth_def, auth_arg_def, lang_def
        !          13390: -- corresponding values are authentication type (internal, krb4, krb5,
        !          13391: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
        !          13392: will be available. Values are retrieved from cache (if current), unless the
        !          13393: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
        !          13394: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
        !          13395: 
        !          13396: Typical usage:
1.943     raeburn  13397: 
1.1172.2.35! raeburn  13398: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  13399: 
1.243     albertel 13400: =back
                   13401: 
                   13402: =head2 Network Status Functions
                   13403: 
                   13404: =over 4
1.191     harris41 13405: 
                   13406: =item *
                   13407: 
1.1137    raeburn  13408: dirlist() : return directory list based on URI (first arg).
                   13409: 
                   13410: Inputs: 1 required, 5 optional.
                   13411: 
                   13412: =over
                   13413: 
                   13414: =item 
                   13415: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   13416: 
                   13417: =item
                   13418: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   13419: 
                   13420: =item
                   13421: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   13422: 
                   13423: =item
                   13424: $getpropath - boolean: 1 if prepend path using &propath(). 
                   13425: 
                   13426: =item
                   13427: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   13428: 
                   13429: =item 
                   13430: $alternateRoot - path to prepend in place of path from $uri.
                   13431: 
                   13432: =back
                   13433: 
                   13434: Returns: Array of up to two items.
                   13435: 
                   13436: =over
                   13437: 
                   13438: a reference to an array of files/subdirectories
                   13439: 
                   13440: =over
                   13441: 
                   13442: Each element in the array of files/subdirectories is a & separated list of
                   13443: item name and the result of running stat on the item.  If dirlist was requested
                   13444: for a file instead of a directory, the item name will be ''. For a directory 
                   13445: listing, if the item is a metadata file, the element will end &N&M 
                   13446: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   13447: default copyright set (1).  
                   13448: 
                   13449: =back
                   13450: 
                   13451: a scalar containing error condition (if encountered).
                   13452: 
                   13453: =over
                   13454: 
                   13455: =item 
                   13456: no_host (no homeserver identified for $username:$domain).
                   13457: 
                   13458: =item 
                   13459: no_such_host (server contacted for listing not identified as valid host).
                   13460: 
                   13461: =item 
                   13462: con_lost (connection to remote server failed).
                   13463: 
                   13464: =item 
                   13465: refused (invalid $username:$domain received on lond side).
                   13466: 
                   13467: =item 
                   13468: no_such_dir (directory at specified path on lond side does not exist). 
                   13469: 
                   13470: =item 
                   13471: empty (directory at specified path on lond side is empty).
                   13472: 
                   13473: =over
                   13474: 
                   13475: This is currently not encountered because the &ls3, &ls2, 
                   13476: &ls (_handler) routines on the lond side do not filter out
                   13477: . and .. from a directory listing. 
                   13478: 
                   13479: =back
                   13480: 
                   13481: =back
                   13482: 
                   13483: =back
1.191     harris41 13484: 
                   13485: =item *
                   13486: 
1.243     albertel 13487: spareserver() : find server with least workload from spare.tab
                   13488: 
1.986     foxr     13489: 
                   13490: =item *
                   13491: 
                   13492: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   13493: if there is no corresponding loncapa host.
                   13494: 
1.243     albertel 13495: =back
                   13496: 
1.986     foxr     13497: 
1.243     albertel 13498: =head2 Apache Request
                   13499: 
                   13500: =over 4
1.191     harris41 13501: 
                   13502: =item *
                   13503: 
1.243     albertel 13504: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   13505: localhost, posts hash
                   13506: 
                   13507: =back
                   13508: 
                   13509: =head2 Data to String to Data
                   13510: 
                   13511: =over 4
1.191     harris41 13512: 
                   13513: =item *
                   13514: 
1.243     albertel 13515: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   13516: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 13517: 
                   13518: =item *
                   13519: 
1.243     albertel 13520: hashref2str($hashref) : convert a hashref into a string complete with
                   13521: escaping and '=' and '&' separators, supports elements that are
                   13522: arrayrefs and hashrefs
1.191     harris41 13523: 
                   13524: =item *
                   13525: 
1.243     albertel 13526: arrayref2str($arrayref) : convert an arrayref into a string complete
                   13527: with escaping and '&' separators, supports elements that are arrayrefs
                   13528: and hashrefs
1.191     harris41 13529: 
                   13530: =item *
                   13531: 
1.243     albertel 13532: str2hash($string) : convert string to hash using unescaping and
                   13533: splitting on '=' and '&', supports elements that are arrayrefs and
                   13534: hashrefs
1.191     harris41 13535: 
                   13536: =item *
                   13537: 
1.243     albertel 13538: str2array($string) : convert string to hash using unescaping and
                   13539: splitting on '&', supports elements that are arrayrefs and hashrefs
                   13540: 
                   13541: =back
                   13542: 
                   13543: =head2 Logging Routines
                   13544: 
                   13545: 
                   13546: These routines allow one to make log messages in the lonnet.log and
                   13547: lonnet.perm logfiles.
1.191     harris41 13548: 
1.1119    foxr     13549: =over 4
                   13550: 
1.191     harris41 13551: =item *
                   13552: 
1.243     albertel 13553: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 13554: 
                   13555: =item *
                   13556: 
1.243     albertel 13557: logthis() : append message to the normal lonnet.log file, it gets
                   13558: preiodically rolled over and deleted.
1.191     harris41 13559: 
                   13560: =item *
                   13561: 
1.243     albertel 13562: logperm() : append a permanent message to lonnet.perm.log, this log
                   13563: file never gets deleted by any automated portion of the system, only
                   13564: messages of critical importance should go in here.
                   13565: 
1.1119    foxr     13566: 
1.243     albertel 13567: =back
                   13568: 
                   13569: =head2 General File Helper Routines
                   13570: 
                   13571: =over 4
1.191     harris41 13572: 
                   13573: =item *
                   13574: 
1.481     raeburn  13575: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   13576: (a) files in /uploaded
                   13577:   (i) If a local copy of the file exists - 
                   13578:       compares modification date of local copy with last-modified date for 
                   13579:       definitive version stored on home server for course. If local copy is 
                   13580:       stale, requests a new version from the home server and stores it. 
                   13581:       If the original has been removed from the home server, then local copy 
                   13582:       is unlinked.
                   13583:   (ii) If local copy does not exist -
                   13584:       requests the file from the home server and stores it. 
                   13585:   
                   13586:   If $caller is 'uploadrep':  
                   13587:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   13588:     for request for files originally uploaded via DOCS. 
                   13589:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   13590:   
                   13591:   Otherwise:
                   13592:      This indicates a call from the content generation phase of the request.
                   13593:      -  returns the entire contents of the file or -1.
                   13594:      
                   13595: (b) files in /res
                   13596:    - returns the entire contents of a file or -1; 
                   13597:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 13598: 
1.712     albertel 13599: 
                   13600: =item *
                   13601: 
                   13602: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   13603:                   reference
                   13604: 
                   13605: returns either a stat() list of data about the file or an empty list
                   13606: if the file doesn't exist or couldn't find out about it (connection
                   13607: problems or user unknown)
                   13608: 
1.191     harris41 13609: =item *
                   13610: 
1.243     albertel 13611: filelocation($dir,$file) : returns file system location of a file
                   13612: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   13613: directory that relative $file lookups are to looked in ($dir of /a/dir
                   13614: and a file of ../bob will become /a/bob)
1.191     harris41 13615: 
                   13616: =item *
                   13617: 
                   13618: hreflocation($dir,$file) : returns file system location or a URL; same as
                   13619: filelocation except for hrefs
                   13620: 
                   13621: =item *
                   13622: 
                   13623: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   13624: 
1.243     albertel 13625: =back
                   13626: 
1.608     albertel 13627: =head2 Usererfile file routines (/uploaded*)
                   13628: 
                   13629: =over 4
                   13630: 
                   13631: =item *
                   13632: 
                   13633: userfileupload(): main rotine for putting a file in a user or course's
                   13634:                   filespace, arguments are,
                   13635: 
1.620     albertel 13636:  formname - required - this is the name of the element in $env where the
1.608     albertel 13637:            filename, and the contents of the file to create/modifed exist
1.620     albertel 13638:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   13639:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  13640:  context - if coursedoc, store the file in the course of the active role
                   13641:              of the current user; 
                   13642:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   13643:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 13644:  subdir - required - subdirectory to put the file in under ../userfiles/
                   13645:          if undefined, it will be placed in "unknown"
                   13646: 
                   13647:  (This routine calls clean_filename() to remove any dangerous
                   13648:  characters from the filename, and then calls finuserfileupload() to
                   13649:  complete the transaction)
                   13650: 
                   13651:  returns either the url of the uploaded file (/uploaded/....) if successful
                   13652:  and /adm/notfound.html if unsuccessful
                   13653: 
                   13654: =item *
                   13655: 
                   13656: clean_filename(): routine for cleaing a filename up for storage in
                   13657:                  userfile space, argument is:
                   13658: 
                   13659:  filename - proposed filename
                   13660: 
                   13661: returns: the new clean filename
                   13662: 
                   13663: =item *
                   13664: 
1.1090    raeburn  13665: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 13666: userspace, probably shouldn't be called directly
                   13667: 
                   13668:   docuname: username or courseid of destination for the file
                   13669:   docudom: domain of user/course of destination for the file
                   13670:   formname: same as for userfileupload()
1.1090    raeburn  13671:   fname: filename (including subdirectories) for the file
                   13672:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   13673:   allfiles: reference to hash used to store objects found by parser
                   13674:   codebase: reference to hash used for codebases of java objects found by parser
                   13675:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   13676:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   13677:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   13678:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   13679:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   13680:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  13681:   mimetype: reference to scalar to accommodate mime type determined
                   13682:             from File::MMagic if $parser = parse.
1.608     albertel 13683: 
                   13684:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  13685:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   13686:  was 'overwrite').
                   13687:  
1.608     albertel 13688: 
                   13689: =item *
                   13690: 
                   13691: renameuserfile(): renames an existing userfile to a new name
                   13692: 
                   13693:   Args:
                   13694:    docuname: username or courseid of destination for the file
                   13695:    docudom: domain of user/course of destination for the file
                   13696:    old: current file name (including any subdirs under userfiles)
                   13697:    new: desired file name (including any subdirs under userfiles)
                   13698: 
                   13699: =item *
                   13700: 
                   13701: mkdiruserfile(): creates a directory is a userfiles dir
                   13702: 
                   13703:   Args:
                   13704:    docuname: username or courseid of destination for the file
                   13705:    docudom: domain of user/course of destination for the file
                   13706:    dir: dir to create (including any subdirs under userfiles)
                   13707: 
                   13708: =item *
                   13709: 
                   13710: removeuserfile(): removes a file that exists in userfiles
                   13711: 
                   13712:   Args:
                   13713:    docuname: username or courseid of destination for the file
                   13714:    docudom: domain of user/course of destination for the file
                   13715:    fname: filname to delete (including any subdirs under userfiles)
                   13716: 
                   13717: =item *
                   13718: 
                   13719: removeuploadedurl(): convience function for removeuserfile()
                   13720: 
                   13721:   Args:
                   13722:    url:  a full /uploaded/... url to delete
                   13723: 
1.747     albertel 13724: =item * 
                   13725: 
                   13726: get_portfile_permissions():
                   13727:   Args:
                   13728:     domain: domain of user or course contain the portfolio files
                   13729:     user: name of user or num of course contain the portfolio files
                   13730:   Returns:
                   13731:     hashref of a dump of the proper file_permissions.db
                   13732:    
                   13733: 
                   13734: =item * 
                   13735: 
                   13736: get_access_controls():
                   13737: 
                   13738: Args:
                   13739:   current_permissions: the hash ref returned from get_portfile_permissions()
                   13740:   group: (optional) the group you want the files associated with
                   13741:   file: (optional) the file you want access info on
                   13742: 
                   13743: Returns:
1.749     raeburn  13744:     a hash (keys are file names) of hashes containing
                   13745:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   13746:         values are XML containing access control settings (see below) 
1.747     albertel 13747: 
                   13748: Internal notes:
                   13749: 
1.749     raeburn  13750:  access controls are stored in file_permissions.db as key=value pairs.
                   13751:     key -> path to file/file_name\0uniqueID:scope_end_start
                   13752:         where scope -> public,guest,course,group,domains or users.
                   13753:               end -> UNIX time for end of access (0 -> no end date)
                   13754:               start -> UNIX time for start of access
                   13755: 
                   13756:     value -> XML description of access control
                   13757:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   13758:             <start></start>
                   13759:             <end></end>
                   13760: 
                   13761:             <password></password>  for scope type = guest
                   13762: 
                   13763:             <domain></domain>     for scope type = course or group
                   13764:             <number></number>
                   13765:             <roles id="">
                   13766:              <role></role>
                   13767:              <access></access>
                   13768:              <section></section>
                   13769:              <group></group>
                   13770:             </roles>
                   13771: 
                   13772:             <dom></dom>         for scope type = domains
                   13773: 
                   13774:             <users>             for scope type = users
                   13775:              <user>
                   13776:               <uname></uname>
                   13777:               <udom></udom>
                   13778:              </user>
                   13779:             </users>
                   13780:            </scope> 
                   13781:               
                   13782:  Access data is also aggregated for each file in an additional key=value pair:
                   13783:  key -> path to file/file_name\0accesscontrol 
                   13784:  value -> reference to hash
                   13785:           hash contains key = value pairs
                   13786:           where key = uniqueID:scope_end_start
                   13787:                 value = UNIX time record was last updated
                   13788: 
                   13789:           Used to improve speed of look-ups of access controls for each file.  
                   13790:  
                   13791:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   13792: 
1.1172.2.13  raeburn  13793: =item *
                   13794: 
1.749     raeburn  13795: modify_access_controls():
                   13796: 
                   13797: Modifies access controls for a portfolio file
                   13798: Args
                   13799: 1. file name
                   13800: 2. reference to hash of required changes,
                   13801: 3. domain
                   13802: 4. username
                   13803:   where domain,username are the domain of the portfolio owner 
                   13804:   (either a user or a course) 
                   13805: 
                   13806: Returns:
                   13807: 1. result of additions or updates ('ok' or 'error', with error message). 
                   13808: 2. result of deletions ('ok' or 'error', with error message).
                   13809: 3. reference to hash of any new or updated access controls.
                   13810: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   13811:    key = integer (inbound ID)
1.1172.2.13  raeburn  13812:    value = uniqueID
                   13813: 
                   13814: =item *
                   13815: 
                   13816: get_timebased_id():
                   13817: 
                   13818: Attempts to get a unique timestamp-based suffix for use with items added to a
                   13819: course via the Course Editor (e.g., folders, composite pages,
                   13820: group bulletin boards).
                   13821: 
                   13822: Args: (first three required; six others optional)
                   13823: 
                   13824: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   13825:    docssequence, or name of group
                   13826: 
                   13827: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   13828:    e.g., num, boardids
                   13829: 
                   13830: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   13831:    file will be named nohist_namespace.db
                   13832: 
                   13833: 4. cdom: domain of course; default is current course domain from %env
                   13834: 
                   13835: 5. cnum: course number; default is current course number from %env
                   13836: 
                   13837: 6. idtype: set to concat if an additional digit is to be appended to the
                   13838:    unix timestamp to form the suffix, if the plain timestamp is already
                   13839:    in use.  Default is to not do this, but simply increment the unix
                   13840:    timestamp by 1 until a unique key is obtained.
                   13841: 
                   13842: 7. who: holder of locking key; defaults to user:domain for user.
                   13843: 
                   13844: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   13845:    retrying); default is 3.
                   13846: 
                   13847: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   13848: 
                   13849: Returns:
                   13850: 
                   13851: 1. suffix obtained (numeric)
                   13852: 
                   13853: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   13854: 
                   13855: 3. error: contains (localized) error message if an error occurred.
                   13856: 
1.747     albertel 13857: 
1.608     albertel 13858: =back
                   13859: 
1.243     albertel 13860: =head2 HTTP Helper Routines
                   13861: 
                   13862: =over 4
                   13863: 
1.191     harris41 13864: =item *
                   13865: 
                   13866: escape() : unpack non-word characters into CGI-compatible hex codes
                   13867: 
                   13868: =item *
                   13869: 
                   13870: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   13871: 
1.243     albertel 13872: =back
                   13873: 
                   13874: =head1 PRIVATE SUBROUTINES
                   13875: 
                   13876: =head2 Underlying communication routines (Shouldn't call)
                   13877: 
                   13878: =over 4
                   13879: 
                   13880: =item *
                   13881: 
                   13882: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   13883: 
                   13884: =item *
                   13885: 
                   13886: reply() : uses subreply to send a message to remote machine, logs all failures
                   13887: 
                   13888: =item *
                   13889: 
                   13890: critical() : passes a critical message to another server; if cannot
                   13891: get through then place message in connection buffer directory and
                   13892: returns con_delayed, if incapable of saving message, returns
                   13893: con_failed
                   13894: 
                   13895: =item *
                   13896: 
                   13897: reconlonc() : tries to reconnect lonc client processes.
                   13898: 
                   13899: =back
                   13900: 
                   13901: =head2 Resource Access Logging
                   13902: 
                   13903: =over 4
                   13904: 
                   13905: =item *
                   13906: 
                   13907: flushcourselogs() : flush (save) buffer logs and access logs
                   13908: 
                   13909: =item *
                   13910: 
                   13911: courselog($what) : save message for course in hash
                   13912: 
                   13913: =item *
                   13914: 
                   13915: courseacclog($what) : save message for course using &courselog().  Perform
                   13916: special processing for specific resource types (problems, exams, quizzes, etc).
                   13917: 
1.191     harris41 13918: =item *
                   13919: 
                   13920: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   13921: as a PerlChildExitHandler
1.243     albertel 13922: 
                   13923: =back
                   13924: 
                   13925: =head2 Other
                   13926: 
                   13927: =over 4
                   13928: 
                   13929: =item *
                   13930: 
                   13931: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 13932: 
                   13933: =back
                   13934: 
                   13935: =cut
1.877     foxr     13936: 

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