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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.24! raeburn     4: # $Id: lonnet.pm,v 1.1172.2.23 2013/05/11 23:08:27 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 {
                    355:     my ($lonhost,$name,$id) = @_;
1.1130    raeburn   356:     my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
1.1124    raeburn   357:     return $response;
                    358: }
                    359: 
1.1       albertel  360: # -------------------------------------------------- Non-critical communication
                    361: sub subreply {
                    362:     my ($cmd,$server)=@_;
1.838     albertel  363:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      364:     #
                    365:     #  With loncnew process trimming, there's a timing hole between lonc server
                    366:     #  process exit and the master server picking up the listen on the AF_UNIX
                    367:     #  socket.  In that time interval, a lock file will exist:
                    368: 
                    369:     my $lockfile=$peerfile.".lock";
                    370:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    371: 	sleep(1);
                    372:     }
                    373:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      374:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      375:     #
1.550     foxr      376:     #   We'll give the connection a few tries before abandoning it.  If
                    377:     #   connection is not possible, we'll con_lost back to the client.
                    378:     #   
                    379:     my $client;
                    380:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    381: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    382: 				      Type    => SOCK_STREAM,
                    383: 				      Timeout => 10);
1.869     albertel  384: 	if ($client) {
1.550     foxr      385: 	    last;		# Connected!
1.850     albertel  386: 	} else {
1.853     albertel  387: 	    &create_connection(&hostname($server),$server);
1.550     foxr      388: 	}
1.850     albertel  389:         sleep(1);		# Try again later if failed connection.
1.550     foxr      390:     }
                    391:     my $answer;
                    392:     if ($client) {
1.704     albertel  393: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      394: 	$answer=<$client>;
                    395: 	if (!$answer) { $answer="con_lost"; }
                    396: 	chomp($answer);
                    397:     } else {
                    398: 	$answer = 'con_lost';	# Failed connection.
                    399:     }
1.1       albertel  400:     return $answer;
                    401: }
                    402: 
                    403: sub reply {
                    404:     my ($cmd,$server)=@_;
1.838     albertel  405:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  406:     my $answer=subreply($cmd,$server);
1.65      www       407:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  408:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       409:                 " $cmd to $server returned $answer</font>");
                    410:     }
1.1       albertel  411:     return $answer;
                    412: }
                    413: 
                    414: # ----------------------------------------------------------- Send USR1 to lonc
                    415: 
                    416: sub reconlonc {
1.891     albertel  417:     my ($lonid) = @_;
                    418:     my $hostname = &hostname($lonid);
                    419:     if ($lonid) {
                    420: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    421: 	if ($hostname && -e $peerfile) {
                    422: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    423: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    424: 					     Type    => SOCK_STREAM,
                    425: 					     Timeout => 10);
                    426: 	    if ($client) {
                    427: 		print $client ("reset_retries\n");
                    428: 		my $answer=<$client>;
                    429: 		#reset just this one.
                    430: 	    }
                    431: 	}
                    432: 	return;
                    433:     }
                    434: 
1.836     www       435:     &logthis("Trying to reconnect lonc");
1.1       albertel  436:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  437:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  438: 	my $loncpid=<$fh>;
                    439:         chomp($loncpid);
                    440:         if (kill 0 => $loncpid) {
                    441: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    442:             kill USR1 => $loncpid;
                    443:             sleep 1;
1.836     www       444:          } else {
1.12      www       445: 	    &logthis(
1.672     albertel  446:                "<font color=\"blue\">WARNING:".
1.12      www       447:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  448:         }
                    449:     } else {
1.836     www       450: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  451:     }
                    452: }
                    453: 
                    454: # ------------------------------------------------------ Critical communication
1.12      www       455: 
1.1       albertel  456: sub critical {
                    457:     my ($cmd,$server)=@_;
1.838     albertel  458:     unless (&hostname($server)) {
1.672     albertel  459:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       460:                " Critical message to unknown server ($server)</font>");
                    461:         return 'no_such_host';
                    462:     }
1.1       albertel  463:     my $answer=reply($cmd,$server);
                    464:     if ($answer eq 'con_lost') {
                    465: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  466: 	my $answer=reply($cmd,$server);
1.1       albertel  467:         if ($answer eq 'con_lost') {
                    468:             my $now=time;
                    469:             my $middlename=$cmd;
1.5       www       470:             $middlename=substr($middlename,0,16);
1.1       albertel  471:             $middlename=~s/\W//g;
                    472:             my $dfilename=
1.305     www       473:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    474:             $dumpcount++;
1.1       albertel  475:             {
1.448     albertel  476: 		my $dfh;
                    477: 		if (open($dfh,">$dfilename")) {
                    478: 		    print $dfh "$cmd\n"; 
                    479: 		    close($dfh);
                    480: 		}
1.1       albertel  481:             }
                    482:             sleep 2;
                    483:             my $wcmd='';
                    484:             {
1.448     albertel  485: 		my $dfh;
                    486: 		if (open($dfh,"<$dfilename")) {
                    487: 		    $wcmd=<$dfh>; 
                    488: 		    close($dfh);
                    489: 		}
1.1       albertel  490:             }
                    491:             chomp($wcmd);
1.7       www       492:             if ($wcmd eq $cmd) {
1.672     albertel  493: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       494:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  495:                 &logperm("D:$server:$cmd");
                    496: 	        return 'con_delayed';
                    497:             } else {
1.672     albertel  498:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       499:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  500:                 &logperm("F:$server:$cmd");
                    501:                 return 'con_failed';
                    502:             }
                    503:         }
                    504:     }
                    505:     return $answer;
1.405     albertel  506: }
                    507: 
1.755     albertel  508: # ------------------------------------------- check if return value is an error
                    509: 
                    510: sub error {
                    511:     my ($result) = @_;
1.756     albertel  512:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  513: 	if ($2 == 2) { return undef; }
                    514: 	return $1;
                    515:     }
                    516:     return undef;
                    517: }
                    518: 
1.783     albertel  519: sub convert_and_load_session_env {
                    520:     my ($lonidsdir,$handle)=@_;
                    521:     my @profile;
                    522:     {
1.917     albertel  523: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    524: 	if (!$opened) {
1.915     albertel  525: 	    return 0;
                    526: 	}
1.783     albertel  527: 	flock($idf,LOCK_SH);
                    528: 	@profile=<$idf>;
                    529: 	close($idf);
                    530:     }
                    531:     my %temp_env;
                    532:     foreach my $line (@profile) {
1.786     albertel  533: 	if ($line !~ m/=/) {
                    534: 	    return 0;
                    535: 	}
1.783     albertel  536: 	chomp($line);
                    537: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    538: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    539:     }
                    540:     unlink("$lonidsdir/$handle.id");
                    541:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    542: 	    0640)) {
                    543: 	%disk_env = %temp_env;
                    544: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    545: 	untie(%disk_env);
                    546:     }
1.786     albertel  547:     return 1;
1.783     albertel  548: }
                    549: 
1.374     www       550: # ------------------------------------------- Transfer profile into environment
1.780     albertel  551: my $env_loaded;
                    552: sub transfer_profile_to_env {
1.788     albertel  553:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    554:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       555: 
1.720     albertel  556:     if (!defined($lonidsdir)) {
                    557: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    558:     }
                    559:     if (!defined($handle)) {
                    560:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    561:     }
                    562: 
1.786     albertel  563:     my $convert;
                    564:     {
1.917     albertel  565:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    566: 	if (!$opened) {
1.915     albertel  567: 	    return;
                    568: 	}
1.786     albertel  569: 	flock($idf,LOCK_SH);
                    570: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    571: 		&GDBM_READER(),0640)) {
                    572: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    573: 	    untie(%disk_env);
                    574: 	} else {
                    575: 	    $convert = 1;
                    576: 	}
                    577:     }
                    578:     if ($convert) {
                    579: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    580: 	    &logthis("Failed to load session, or convert session.");
                    581: 	}
1.374     www       582:     }
1.783     albertel  583: 
1.786     albertel  584:     my %remove;
1.783     albertel  585:     while ( my $envname = each(%env) ) {
1.433     matthew   586:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    587:             if ($time < time-300) {
1.783     albertel  588:                 $remove{$key}++;
1.433     matthew   589:             }
                    590:         }
                    591:     }
1.783     albertel  592: 
1.619     albertel  593:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  594:     $env_loaded=1;
1.783     albertel  595:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   596:         &delenv($expired_key);
1.374     www       597:     }
1.1       albertel  598: }
                    599: 
1.916     albertel  600: # ---------------------------------------------------- Check for valid session 
                    601: sub check_for_valid_session {
1.1155    raeburn   602:     my ($r,$name) = @_;
1.916     albertel  603:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155    raeburn   604:     if ($name eq '') {
                    605:         $name = 'lonID';
                    606:     }
                    607:     my $lonid=$cookies{$name};
1.916     albertel  608:     return undef if (!$lonid);
                    609: 
                    610:     my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155    raeburn   611:     my $lonidsdir;
                    612:     if ($name eq 'lonDAV') {
                    613:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    614:     } else {
                    615:         $lonidsdir=$r->dir_config('lonIDsDir');
                    616:     }
1.916     albertel  617:     return undef if (!-e "$lonidsdir/$handle.id");
                    618: 
1.917     albertel  619:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    620:     return undef if (!$opened);
1.916     albertel  621: 
                    622:     flock($idf,LOCK_SH);
                    623:     my %disk_env;
                    624:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    625: 	    &GDBM_READER(),0640)) {
                    626: 	return undef;	
                    627:     }
                    628: 
                    629:     if (!defined($disk_env{'user.name'})
                    630: 	|| !defined($disk_env{'user.domain'})) {
                    631: 	return undef;
                    632:     }
1.1172.2.18  raeburn   633: 
                    634:     if (($r->user() eq '') && ($apache >= 2.4)) {
                    635:         if ($disk_env{'user.domain'} eq $r->dir_config('lonDefDomain')) {
                    636:             $r->user($disk_env{'user.name'});
                    637:         } else {
                    638:             $r->user($disk_env{'user.name'}.':'.$disk_env{'user.domain'});
                    639:         }
                    640:     }
                    641: 
1.916     albertel  642:     return $handle;
                    643: }
                    644: 
1.830     albertel  645: sub timed_flock {
                    646:     my ($file,$lock_type) = @_;
                    647:     my $failed=0;
                    648:     eval {
                    649: 	local $SIG{__DIE__}='DEFAULT';
                    650: 	local $SIG{ALRM}=sub {
                    651: 	    $failed=1;
                    652: 	    die("failed lock");
                    653: 	};
                    654: 	alarm(13);
                    655: 	flock($file,$lock_type);
                    656: 	alarm(0);
                    657:     };
                    658:     if ($failed) {
                    659: 	return undef;
                    660:     } else {
                    661: 	return 1;
                    662:     }
                    663: }
                    664: 
1.5       www       665: # ---------------------------------------------------------- Append Environment
                    666: 
                    667: sub appenv {
1.949     raeburn   668:     my ($newenv,$roles) = @_;
                    669:     if (ref($newenv) eq 'HASH') {
                    670:         foreach my $key (keys(%{$newenv})) {
                    671:             my $refused = 0;
                    672: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    673:                 $refused = 1;
                    674:                 if (ref($roles) eq 'ARRAY') {
                    675:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
                    676:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    677:                         $refused = 0;
                    678:                     }
                    679:                 }
                    680:             }
                    681:             if ($refused) {
                    682:                 &logthis("<font color=\"blue\">WARNING: ".
                    683:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    684:                          .'</font>');
                    685: 	        delete($newenv->{$key});
                    686:             } else {
                    687:                 $env{$key}=$newenv->{$key};
                    688:             }
                    689:         }
                    690:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    691:         if ($opened
                    692: 	    && &timed_flock($env_file,LOCK_EX)
                    693: 	    &&
                    694: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    695: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    696: 	    while (my ($key,$value) = each(%{$newenv})) {
                    697: 	        $disk_env{$key} = $value;
                    698: 	    }
                    699: 	    untie(%disk_env);
1.35      www       700:         }
1.191     harris41  701:     }
1.56      www       702:     return 'ok';
                    703: }
                    704: # ----------------------------------------------------- Delete from Environment
                    705: 
                    706: sub delenv {
1.1104    raeburn   707:     my ($delthis,$regexp,$roles) = @_;
                    708:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    709:         my $refused = 1;
                    710:         if (ref($roles) eq 'ARRAY') {
                    711:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    712:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    713:                 $refused = 0;
                    714:             }
                    715:         }
                    716:         if ($refused) {
                    717:             &logthis("<font color=\"blue\">WARNING: ".
                    718:                      "Attempt to delete from environment ".$delthis);
                    719:             return 'error';
                    720:         }
1.56      www       721:     }
1.917     albertel  722:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    723:     if ($opened
1.915     albertel  724: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  725: 	&&
                    726: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    727: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  728: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   729: 	    if ($regexp) {
                    730:                 if ($key=~/^$delthis/) {
                    731:                     delete($env{$key});
                    732:                     delete($disk_env{$key});
                    733:                 } 
                    734:             } else {
                    735:                 if ($key=~/^\Q$delthis\E/) {
                    736: 		    delete($env{$key});
                    737: 		    delete($disk_env{$key});
                    738: 	        }
                    739:             }
1.448     albertel  740: 	}
1.783     albertel  741: 	untie(%disk_env);
1.5       www       742:     }
                    743:     return 'ok';
1.369     albertel  744: }
                    745: 
1.790     albertel  746: sub get_env_multiple {
                    747:     my ($name) = @_;
                    748:     my @values;
                    749:     if (defined($env{$name})) {
                    750:         # exists is it an array
                    751:         if (ref($env{$name})) {
                    752:             @values=@{ $env{$name} };
                    753:         } else {
                    754:             $values[0]=$env{$name};
                    755:         }
                    756:     }
                    757:     return(@values);
                    758: }
                    759: 
1.958     www       760: # ------------------------------------------------------------------- Locking
                    761: 
                    762: sub set_lock {
                    763:     my ($text)=@_;
                    764:     $locknum++;
                    765:     my $id=$$.'-'.$locknum;
                    766:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    767:              'session.lock.'.$id => $text});
                    768:     return $id;
                    769: }
                    770: 
                    771: sub get_locks {
                    772:     my $num=0;
                    773:     my %texts=();
                    774:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    775:        if ($lock=~/\w/) {
                    776:           $num++;
                    777:           $texts{$lock}=$env{'session.lock.'.$lock};
                    778:        }
                    779:    }
                    780:    return ($num,%texts);
                    781: }
                    782: 
                    783: sub remove_lock {
                    784:     my ($id)=@_;
                    785:     my $newlocks='';
                    786:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    787:        if (($lock=~/\w/) && ($lock ne $id)) {
                    788:           $newlocks.=','.$lock;
                    789:        }
                    790:     }
                    791:     &appenv({'session.locks' => $newlocks});
                    792:     &delenv('session.lock.'.$id);
                    793: }
                    794: 
                    795: sub remove_all_locks {
                    796:     my $activelocks=$env{'session.locks'};
                    797:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    798:        if ($lock=~/\w/) {
                    799:           &remove_lock($lock);
                    800:        }
                    801:     }
                    802: }
                    803: 
                    804: 
1.369     albertel  805: # ------------------------------------------ Find out current server userload
                    806: sub userload {
                    807:     my $numusers=0;
                    808:     {
                    809: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    810: 	my $filename;
                    811: 	my $curtime=time;
                    812: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  813: 	    next if ($filename eq '.' || $filename eq '..');
                    814: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  815: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  816: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  817: 	}
                    818: 	closedir(LONIDS);
                    819:     }
                    820:     my $userloadpercent=0;
                    821:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    822:     if ($maxuserload) {
1.371     albertel  823: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  824:     }
1.372     albertel  825:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  826:     return $userloadpercent;
1.283     www       827: }
                    828: 
1.1       albertel  829: # ------------------------------ Find server with least workload from spare.tab
1.11      www       830: 
1.1       albertel  831: sub spareserver {
1.1083    raeburn   832:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  833:     my $spare_server;
1.370     albertel  834:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  835:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    836:                                                      :  $userloadpercent;
1.1083    raeburn   837:     my ($uint_dom,$remotesessions);
                    838:     if (($udom ne '') && (&domain($udom) ne '')) {
                    839:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    840:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    841:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    842:         $remotesessions = $udomdefaults{'remotesessions'};
                    843:     }
1.1123    raeburn   844:     my $spareshash = &this_host_spares($udom);
                    845:     if (ref($spareshash) eq 'HASH') {
                    846:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    847:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    848:                 if ($uint_dom) {
                    849:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    850:                                                  $try_server));
                    851:                 }
                    852: 	        ($spare_server, $lowest_load) =
                    853: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    854:             }
1.1083    raeburn   855:         }
1.784     albertel  856: 
1.1123    raeburn   857:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    858: 
                    859:         if (!$found_server) {
                    860:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    861: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
                    862:                     if ($uint_dom) {
                    863:                         next unless (&spare_can_host($udom,$uint_dom,
                    864:                                                      $remotesessions,$try_server));
                    865:                     }
                    866: 	            ($spare_server, $lowest_load) =
                    867: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    868:                 }
                    869: 	    }
                    870:         }
1.784     albertel  871:     }
                    872: 
                    873:     if (!$want_server_name) {
1.968     raeburn   874:         my $protocol = 'http';
                    875:         if ($protocol{$spare_server} eq 'https') {
                    876:             $protocol = $protocol{$spare_server};
                    877:         }
1.1001    raeburn   878:         if (defined($spare_server)) {
                    879:             my $hostname = &hostname($spare_server);
1.1083    raeburn   880:             if (defined($hostname)) {
1.1001    raeburn   881: 	        $spare_server = $protocol.'://'.$hostname;
                    882:             }
                    883:         }
1.784     albertel  884:     }
                    885:     return $spare_server;
                    886: }
                    887: 
                    888: sub compare_server_load {
                    889:     my ($try_server, $spare_server, $lowest_load) = @_;
                    890: 
                    891:     my $loadans     = &reply('load',    $try_server);
                    892:     my $userloadans = &reply('userload',$try_server);
                    893: 
                    894:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   895: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  896:     }
                    897: 
                    898:     my $load;
                    899:     if ($loadans =~ /\d/) {
                    900: 	if ($userloadans =~ /\d/) {
                    901: 	    #both are numbers, pick the bigger one
                    902: 	    $load = ($loadans > $userloadans) ? $loadans 
                    903: 		                              : $userloadans;
1.411     albertel  904: 	} else {
1.784     albertel  905: 	    $load = $loadans;
1.411     albertel  906: 	}
1.784     albertel  907:     } else {
                    908: 	$load = $userloadans;
                    909:     }
                    910: 
                    911:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    912: 	$spare_server = $try_server;
                    913: 	$lowest_load  = $load;
1.370     albertel  914:     }
1.784     albertel  915:     return ($spare_server,$lowest_load);
1.202     matthew   916: }
1.914     albertel  917: 
                    918: # --------------------------- ask offload servers if user already has a session
                    919: sub find_existing_session {
                    920:     my ($udom,$uname) = @_;
1.1123    raeburn   921:     my $spareshash = &this_host_spares($udom);
                    922:     if (ref($spareshash) eq 'HASH') {
                    923:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    924:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    925:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    926:             }
                    927:         }
                    928:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                    929:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                    930:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    931:             }
                    932:         }
1.914     albertel  933:     }
                    934:     return;
                    935: }
                    936: 
                    937: # -------------------------------- ask if server already has a session for user
                    938: sub has_user_session {
                    939:     my ($lonid,$udom,$uname) = @_;
                    940:     my $result = &reply(join(':','userhassession',
                    941: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    942:     return 1 if ($result eq 'ok');
                    943: 
                    944:     return 0;
                    945: }
                    946: 
1.1076    raeburn   947: # --------- determine least loaded server in a user's domain which allows login
                    948: 
                    949: sub choose_server {
1.1115    raeburn   950:     my ($udom,$checkloginvia) = @_;
1.1076    raeburn   951:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn   952:     my %servers = &get_servers($udom);
1.1076    raeburn   953:     my $lowest_load = 30000;
1.1151    raeburn   954:     my ($login_host,$hostname,$portal_path,$isredirect);
1.1076    raeburn   955:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn   956:         my $loginvia;
                    957:         if ($checkloginvia) {
                    958:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn   959:             if ($loginvia) {
                    960:                 my ($server,$path) = split(/:/,$loginvia);
                    961:                 ($login_host, $lowest_load) =
                    962:                     &compare_server_load($server, $login_host, $lowest_load);
                    963:                 if ($login_host eq $server) {
                    964:                     $portal_path = $path;
1.1151    raeburn   965:                     $isredirect = 1;
1.1116    raeburn   966:                 }
                    967:             } else {
                    968:                 ($login_host, $lowest_load) =
                    969:                     &compare_server_load($lonhost, $login_host, $lowest_load);
                    970:                 if ($login_host eq $lonhost) {
                    971:                     $portal_path = '';
1.1151    raeburn   972:                     $isredirect = ''; 
1.1116    raeburn   973:                 }
                    974:             }
                    975:         } else {
1.1076    raeburn   976:             ($login_host, $lowest_load) =
1.1116    raeburn   977:                 &compare_server_load($lonhost, $login_host, $lowest_load);
1.1076    raeburn   978:         }
                    979:     }
                    980:     if ($login_host ne '') {
1.1116    raeburn   981:         $hostname = &hostname($login_host);
1.1076    raeburn   982:     }
1.1151    raeburn   983:     return ($login_host,$hostname,$portal_path,$isredirect);
1.1076    raeburn   984: }
                    985: 
1.202     matthew   986: # --------------------------------------------- Try to change a user's password
                    987: 
                    988: sub changepass {
1.799     raeburn   989:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   990:     $currentpass = &escape($currentpass);
                    991:     $newpass     = &escape($newpass);
1.1030    raeburn   992:     my $lonhost = $perlvar{'lonHostID'};
                    993:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew   994: 		       $server);
                    995:     if (! $answer) {
                    996: 	&logthis("No reply on password change request to $server ".
                    997: 		 "by $uname in domain $udom.");
                    998:     } elsif ($answer =~ "^ok") {
                    999:         &logthis("$uname in $udom successfully changed their password ".
                   1000: 		 "on $server.");
                   1001:     } elsif ($answer =~ "^pwchange_failure") {
                   1002: 	&logthis("$uname in $udom was unable to change their password ".
                   1003: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1004: 		 "or pwchange");
                   1005:     } elsif ($answer =~ "^non_authorized") {
                   1006:         &logthis("$uname in $udom did not get their password correct when ".
                   1007: 		 "attempting to change it on $server.");
                   1008:     } elsif ($answer =~ "^auth_mode_error") {
                   1009:         &logthis("$uname in $udom attempted to change their password despite ".
                   1010: 		 "not being locally or internally authenticated on $server.");
                   1011:     } elsif ($answer =~ "^unknown_user") {
                   1012:         &logthis("$uname in $udom attempted to change their password ".
                   1013: 		 "on $server but were unable to because $server is not ".
                   1014: 		 "their home server.");
                   1015:     } elsif ($answer =~ "^refused") {
                   1016: 	&logthis("$server refused to change $uname in $udom password because ".
                   1017: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1018:     } elsif ($answer =~ "invalid_client") {
                   1019:         &logthis("$server refused to change $uname in $udom password because ".
                   1020:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1021:     }
                   1022:     return $answer;
1.1       albertel 1023: }
                   1024: 
1.169     harris41 1025: # ----------------------- Try to determine user's current authentication scheme
                   1026: 
                   1027: sub queryauthenticate {
                   1028:     my ($uname,$udom)=@_;
1.456     albertel 1029:     my $uhome=&homeserver($uname,$udom);
                   1030:     if (!$uhome) {
                   1031: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1032: 	return 'no_host';
                   1033:     }
                   1034:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1035:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1036: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1037:     }
1.456     albertel 1038:     return $answer;
1.169     harris41 1039: }
                   1040: 
1.1       albertel 1041: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1042: 
1.1       albertel 1043: sub authenticate {
1.1073    raeburn  1044:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1045:     $upass=&escape($upass);
                   1046:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1047:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1048:     my $newhome;
1.836     www      1049:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1050: # Maybe the machine was offline and only re-appeared again recently?
                   1051:         &reconlonc();
                   1052: # One more
1.952     raeburn  1053: 	$uhome=&homeserver($uname,$udom,1);
                   1054:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1055:             if (defined(&domain($udom,'primary'))) {
                   1056:                 $newhome=&domain($udom,'primary');
                   1057:             }
                   1058:             if ($newhome ne '') {
                   1059:                 $uhome = $newhome;
                   1060:             }
                   1061:         }
1.836     www      1062: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1063: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1064: 	    return 'no_host';
                   1065:         }
1.1       albertel 1066:     }
1.1073    raeburn  1067:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1068:     if ($answer eq 'authorized') {
1.952     raeburn  1069:         if ($newhome) {
                   1070:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1071:             return 'no_account_on_host'; 
                   1072:         } else {
                   1073:             &logthis("User $uname at $udom authorized by $uhome");
                   1074:             return $uhome;
                   1075:         }
1.471     albertel 1076:     }
                   1077:     if ($answer eq 'non_authorized') {
                   1078: 	&logthis("User $uname at $udom rejected by $uhome");
                   1079: 	return 'no_host'; 
1.9       www      1080:     }
1.471     albertel 1081:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1082:     return 'no_host';
                   1083: }
                   1084: 
1.1073    raeburn  1085: sub can_host_session {
1.1074    raeburn  1086:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1087:     my $canhost = 1;
1.1074    raeburn  1088:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1089:     if (ref($remotesessions) eq 'HASH') {
                   1090:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1091:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1092:                 $canhost = 0;
                   1093:             } else {
                   1094:                 $canhost = 1;
                   1095:             }
                   1096:         }
                   1097:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1098:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1099:                 $canhost = 1;
                   1100:             } else {
                   1101:                 $canhost = 0;
                   1102:             }
                   1103:         }
                   1104:         if ($canhost) {
                   1105:             if ($remotesessions->{'version'} ne '') {
                   1106:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1107:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1108:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1109:                         my $major = $1;
                   1110:                         my $minor = $2;
                   1111:                         if (($major < $reqmajor ) ||
                   1112:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1113:                             $canhost = 0;
                   1114:                         }
                   1115:                     } else {
                   1116:                         $canhost = 0;
                   1117:                     }
                   1118:                 }
                   1119:             }
                   1120:         }
                   1121:     }
                   1122:     if ($canhost) {
                   1123:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1124:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1125:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1126:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1127:                 if (($uint_dom ne '') && 
                   1128:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1129:                     $canhost = 0;
                   1130:                 } else {
                   1131:                     $canhost = 1;
                   1132:                 }
                   1133:             }
                   1134:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1135:                 if (($uint_dom ne '') && 
                   1136:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1137:                     $canhost = 1;
                   1138:                 } else {
                   1139:                     $canhost = 0;
                   1140:                 }
                   1141:             }
                   1142:         }
                   1143:     }
                   1144:     return $canhost;
                   1145: }
                   1146: 
1.1083    raeburn  1147: sub spare_can_host {
                   1148:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1149:     my $canhost=1;
                   1150:     my @intdoms;
                   1151:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
                   1152:     if (ref($internet_names) eq 'ARRAY') {
                   1153:         @intdoms = @{$internet_names};
                   1154:     }
                   1155:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1156:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
                   1157:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   1158:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   1159:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
                   1160:         $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1161:                                      $remotesessions,
                   1162:                                      $defdomdefaults{'hostedsessions'});
                   1163:     }
                   1164:     return $canhost;
                   1165: }
                   1166: 
1.1123    raeburn  1167: sub this_host_spares {
                   1168:     my ($dom) = @_;
1.1126    raeburn  1169:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1170:     my @hosts = &current_machine_ids();
                   1171:     foreach my $lonhost (@hosts) {
                   1172:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1173:             $dom_in_use = $dom;
                   1174:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1175:             last;
                   1176:         }
                   1177:     }
1.1126    raeburn  1178:     if ($dom_in_use ne '') {
                   1179:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1180:     }
                   1181:     if (ref($result) ne 'HASH') {
                   1182:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1183:         $dom_in_use = &host_domain($lonhost_in_use);
                   1184:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1185:         if (ref($result) ne 'HASH') {
                   1186:             $result = \%spareid;
                   1187:         }
                   1188:     }
                   1189:     return $result;
                   1190: }
                   1191: 
                   1192: sub spares_for_offload  {
                   1193:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1194:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1195:     if (defined($cached)) {
                   1196:         return $result;
                   1197:     } else {
1.1126    raeburn  1198:         my $cachetime = 60*60*24;
                   1199:         my %domconfig =
                   1200:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1201:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1202:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1203:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1204:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1205:                 }
                   1206:             }
                   1207:         }
                   1208:     }
1.1126    raeburn  1209:     return;
1.1123    raeburn  1210: }
                   1211: 
1.1129    raeburn  1212: sub get_lonbalancer_config {
                   1213:     my ($servers) = @_;
                   1214:     my ($currbalancer,$currtargets);
                   1215:     if (ref($servers) eq 'HASH') {
                   1216:         foreach my $server (keys(%{$servers})) {
                   1217:             my %what = (
                   1218:                          spareid => 1,
                   1219:                          perlvar => 1,
                   1220:                        );
                   1221:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1222:             if ($result eq 'ok') {
                   1223:                 if (ref($returnhash) eq 'HASH') {
                   1224:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1225:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1226:                             $currbalancer = $server;
                   1227:                             $currtargets = {};
                   1228:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1229:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1230:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1231:                                 }
                   1232:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1233:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1234:                                 }
                   1235:                             }
                   1236:                             last;
                   1237:                         }
                   1238:                     }
                   1239:                 }
                   1240:             }
                   1241:         }
                   1242:     }
                   1243:     return ($currbalancer,$currtargets);
                   1244: }
                   1245: 
                   1246: sub check_loadbalancing {
                   1247:     my ($uname,$udom) = @_;
1.1172.2.12  raeburn  1248:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
                   1249:         $rule_in_effect,$offloadto,$otherserver);
1.1129    raeburn  1250:     my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4  raeburn  1251:     my @hosts = &current_machine_ids();
1.1129    raeburn  1252:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1253:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1254:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1255:     my $serverhomedom = &host_domain($lonhost);
                   1256: 
                   1257:     my $cachetime = 60*60*24;
                   1258: 
                   1259:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1260:         $dom_in_use = $udom;
                   1261:         $homeintdom = 1;
                   1262:     } else {
                   1263:         $dom_in_use = $serverhomedom;
                   1264:     }
                   1265:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1266:     unless (defined($cached)) {
                   1267:         my %domconfig =
                   1268:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1269:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1270:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1271:         }
                   1272:     }
                   1273:     if (ref($result) eq 'HASH') {
1.1172.2.12  raeburn  1274:         ($is_balancer,$currtargets,$currrules) =
                   1275:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1276:         if ($is_balancer) {
                   1277:             if (ref($currrules) eq 'HASH') {
                   1278:                 if ($homeintdom) {
                   1279:                     if ($uname ne '') {
                   1280:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1281:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1282:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1283:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1284:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1285:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1286:                             }
                   1287:                         }
                   1288:                         if ($rule_in_effect eq '') {
                   1289:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1290:                             if ($userenv{'inststatus'} ne '') {
                   1291:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1292:                                 my ($othertitle,$usertypes,$types) =
                   1293:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1294:                                 if (ref($types) eq 'ARRAY') {
                   1295:                                     foreach my $type (@{$types}) {
                   1296:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1297:                                             if (exists($currrules->{$type})) {
                   1298:                                                 $rule_in_effect = $currrules->{$type};
                   1299:                                             }
                   1300:                                         }
                   1301:                                     }
                   1302:                                 }
                   1303:                             } else {
                   1304:                                 if (exists($currrules->{'default'})) {
                   1305:                                     $rule_in_effect = $currrules->{'default'};
                   1306:                                 }
                   1307:                             }
                   1308:                         }
                   1309:                     } else {
                   1310:                         if (exists($currrules->{'default'})) {
                   1311:                             $rule_in_effect = $currrules->{'default'};
                   1312:                         }
                   1313:                     }
                   1314:                 } else {
                   1315:                     if ($currrules->{'_LC_external'} ne '') {
                   1316:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1317:                     }
                   1318:                 }
                   1319:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1320:                                                        $uname,$udom);
                   1321:             }
                   1322:         }
                   1323:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
                   1324:         my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
                   1325:         unless (defined($cached)) {
                   1326:             my %domconfig =
                   1327:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1328:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1329:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1330:             }
                   1331:         }
                   1332:         if (ref($result) eq 'HASH') {
1.1172.2.12  raeburn  1333:             ($is_balancer,$currtargets,$currrules) =
                   1334:                 &check_balancer_result($result,@hosts);
                   1335:             if ($is_balancer) {
1.1129    raeburn  1336:                 if (ref($currrules) eq 'HASH') {
                   1337:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1338:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1339:                     }
                   1340:                 }
                   1341:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1342:                                                        $uname,$udom);
                   1343:             }
                   1344:         } else {
                   1345:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1346:                 $is_balancer = 1;
                   1347:                 $offloadto = &this_host_spares($dom_in_use);
                   1348:             }
                   1349:         }
                   1350:     } else {
                   1351:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1352:             $is_balancer = 1;
                   1353:             $offloadto = &this_host_spares($dom_in_use);
                   1354:         }
                   1355:     }
1.1172.2.5  raeburn  1356:     if ($is_balancer) {
                   1357:         my $lowest_load = 30000;
                   1358:         if (ref($offloadto) eq 'HASH') {
                   1359:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1360:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1361:                     ($otherserver,$lowest_load) =
                   1362:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1363:                 }
1.1129    raeburn  1364:             }
1.1172.2.5  raeburn  1365:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1366: 
1.1172.2.5  raeburn  1367:             if (!$found_server) {
                   1368:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1369:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1370:                         ($otherserver,$lowest_load) =
                   1371:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1372:                     }
                   1373:                 }
                   1374:             }
                   1375:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1376:             if (@{$offloadto} == 1) {
                   1377:                 $otherserver = $offloadto->[0];
                   1378:             } elsif (@{$offloadto} > 1) {
                   1379:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1380:                     ($otherserver,$lowest_load) =
                   1381:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1382:                 }
                   1383:             }
                   1384:         }
1.1172.2.5  raeburn  1385:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1386:             $is_balancer = 0;
                   1387:             if ($uname ne '' && $udom ne '') {
                   1388:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1389: 
                   1390:                     &appenv({'user.loadbalexempt'     => $lonhost,
                   1391:                              'user.loadbalcheck.time' => time});
                   1392:                 }
1.1129    raeburn  1393:             }
                   1394:         }
                   1395:     }
                   1396:     return ($is_balancer,$otherserver);
                   1397: }
                   1398: 
1.1172.2.12  raeburn  1399: sub check_balancer_result {
                   1400:     my ($result,@hosts) = @_;
                   1401:     my ($is_balancer,$currtargets,$currrules);
                   1402:     if (ref($result) eq 'HASH') {
                   1403:         if ($result->{'lonhost'} ne '') {
                   1404:             my $currbalancer = $result->{'lonhost'};
                   1405:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1406:                 $is_balancer = 1;
                   1407:                 $currtargets = $result->{'targets'};
                   1408:                 $currrules = $result->{'rules'};
                   1409:             }
                   1410:         } else {
                   1411:             foreach my $key (keys(%{$result})) {
                   1412:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1413:                     (ref($result->{$key}) eq 'HASH')) {
                   1414:                     $is_balancer = 1;
                   1415:                     $currrules = $result->{$key}{'rules'};
                   1416:                     $currtargets = $result->{$key}{'targets'};
                   1417:                     last;
                   1418:                 }
                   1419:             }
                   1420:         }
                   1421:     }
                   1422:     return ($is_balancer,$currtargets,$currrules);
                   1423: }
                   1424: 
1.1129    raeburn  1425: sub get_loadbalancer_targets {
                   1426:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1427:     my $offloadto;
1.1172.2.4  raeburn  1428:     if ($rule_in_effect eq 'none') {
                   1429:         return [$perlvar{'lonHostID'}];
                   1430:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1431:         $offloadto = $currtargets;
                   1432:     } else {
                   1433:         if ($rule_in_effect eq 'homeserver') {
                   1434:             my $homeserver = &homeserver($uname,$udom);
                   1435:             if ($homeserver ne 'no_host') {
                   1436:                 $offloadto = [$homeserver];
                   1437:             }
                   1438:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1439:             my %domconfig =
                   1440:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1441:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1442:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1443:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1444:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1445:                     }
                   1446:                 }
                   1447:             } else {
1.1172.2.7  raeburn  1448:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1449:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1450:                 if (&hostname($remotebalancer) ne '') {
                   1451:                     $offloadto = [$remotebalancer];
                   1452:                 }
                   1453:             }
                   1454:         } elsif (&hostname($rule_in_effect) ne '') {
                   1455:             $offloadto = [$rule_in_effect];
                   1456:         }
                   1457:     }
                   1458:     return $offloadto;
                   1459: }
                   1460: 
1.1127    raeburn  1461: sub internet_dom_servers {
                   1462:     my ($dom) = @_;
                   1463:     my (%uniqservers,%servers);
                   1464:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1465:     my @machinedoms = &machine_domains($primaryserver);
                   1466:     foreach my $mdom (@machinedoms) {
                   1467:         my %currservers = %servers;
                   1468:         my %server = &get_servers($mdom);
                   1469:         %servers = (%currservers,%server);
                   1470:     }
                   1471:     my %by_hostname;
                   1472:     foreach my $id (keys(%servers)) {
                   1473:         push(@{$by_hostname{$servers{$id}}},$id);
                   1474:     }
                   1475:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1476:         if (@{$by_hostname{$hostname}} > 1) {
                   1477:             my $match = 0;
                   1478:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1479:                 if (&host_domain($id) eq $dom) {
                   1480:                     $uniqservers{$id} = $hostname;
                   1481:                     $match = 1;
                   1482:                 }
                   1483:             }
                   1484:             unless ($match) {
                   1485:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1486:             }
                   1487:         } else {
                   1488:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1489:         }
                   1490:     }
                   1491:     return %uniqservers;
                   1492: }
                   1493: 
1.1       albertel 1494: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1495: 
1.599     albertel 1496: my %homecache;
1.1       albertel 1497: sub homeserver {
1.230     stredwic 1498:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1499:     my $index="$uname:$udom";
1.426     albertel 1500: 
1.599     albertel 1501:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1502: 
                   1503:     my %servers = &get_servers($udom,'library');
                   1504:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1505:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1506: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1507: 
                   1508: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1509: 	if ($answer eq 'found') {
                   1510: 	    delete($badServerCache{$tryserver}); 
                   1511: 	    return $homecache{$index}=$tryserver;
                   1512: 	} elsif ($answer eq 'no_host') {
                   1513: 	    $badServerCache{$tryserver}=1;
                   1514: 	}
1.1       albertel 1515:     }    
                   1516:     return 'no_host';
1.70      www      1517: }
                   1518: 
                   1519: # ------------------------------------- Find the usernames behind a list of IDs
                   1520: 
                   1521: sub idget {
                   1522:     my ($udom,@ids)=@_;
                   1523:     my %returnhash=();
                   1524:     
1.841     albertel 1525:     my %servers = &get_servers($udom,'library');
                   1526:     foreach my $tryserver (keys(%servers)) {
                   1527: 	my $idlist=join('&',@ids);
                   1528: 	$idlist=~tr/A-Z/a-z/; 
                   1529: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1530: 	my @answer=();
                   1531: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1532: 	    @answer=split(/\&/,$reply);
                   1533: 	}                    ;
                   1534: 	my $i;
                   1535: 	for ($i=0;$i<=$#ids;$i++) {
                   1536: 	    if ($answer[$i]) {
                   1537: 		$returnhash{$ids[$i]}=$answer[$i];
                   1538: 	    } 
                   1539: 	}
                   1540:     } 
1.70      www      1541:     return %returnhash;
                   1542: }
                   1543: 
                   1544: # ------------------------------------- Find the IDs behind a list of usernames
                   1545: 
                   1546: sub idrget {
                   1547:     my ($udom,@unames)=@_;
                   1548:     my %returnhash=();
1.800     albertel 1549:     foreach my $uname (@unames) {
                   1550:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1551:     }
1.70      www      1552:     return %returnhash;
                   1553: }
                   1554: 
                   1555: # ------------------------------- Store away a list of names and associated IDs
                   1556: 
                   1557: sub idput {
                   1558:     my ($udom,%ids)=@_;
                   1559:     my %servers=();
1.800     albertel 1560:     foreach my $uname (keys(%ids)) {
                   1561: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1562:         my $uhom=&homeserver($uname,$udom);
1.70      www      1563:         if ($uhom ne 'no_host') {
1.800     albertel 1564:             my $id=&escape($ids{$uname});
1.70      www      1565:             $id=~tr/A-Z/a-z/;
1.800     albertel 1566:             my $esc_unam=&escape($uname);
1.70      www      1567: 	    if ($servers{$uhom}) {
1.800     albertel 1568: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1569:             } else {
1.800     albertel 1570:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1571:             }
                   1572:         }
1.191     harris41 1573:     }
1.800     albertel 1574:     foreach my $server (keys(%servers)) {
                   1575:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1576:     }
1.344     www      1577: }
                   1578: 
1.1023    raeburn  1579: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1580: sub dump_dom {
1.1165    droeschl 1581:     my ($namespace, $udom, $regexp) = @_;
                   1582: 
                   1583:     $udom ||= $env{'user.domain'};
                   1584: 
                   1585:     return () unless $udom;
                   1586: 
                   1587:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1588: }
                   1589: 
1.1023    raeburn  1590: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1591: 
                   1592: sub get_dom {
1.860     raeburn  1593:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn  1594:     my $items='';
                   1595:     foreach my $item (@$storearr) {
                   1596:         $items.=&escape($item).'&';
                   1597:     }
                   1598:     $items=~s/\&$//;
1.860     raeburn  1599:     if (!$udom) {
                   1600:         $udom=$env{'user.domain'};
                   1601:         if (defined(&domain($udom,'primary'))) {
                   1602:             $uhome=&domain($udom,'primary');
                   1603:         } else {
1.874     albertel 1604:             undef($uhome);
1.860     raeburn  1605:         }
                   1606:     } else {
                   1607:         if (!$uhome) {
                   1608:             if (defined(&domain($udom,'primary'))) {
                   1609:                 $uhome=&domain($udom,'primary');
                   1610:             }
                   1611:         }
                   1612:     }
                   1613:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1614:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1615:         my %returnhash;
1.875     albertel 1616:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1617:             return %returnhash;
                   1618:         }
1.806     raeburn  1619:         my @pairs=split(/\&/,$rep);
                   1620:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1621:             return @pairs;
                   1622:         }
                   1623:         my $i=0;
                   1624:         foreach my $item (@$storearr) {
                   1625:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1626:             $i++;
                   1627:         }
                   1628:         return %returnhash;
                   1629:     } else {
1.880     banghart 1630:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1631:     }
                   1632: }
                   1633: 
                   1634: # -------------------------------------------- put items in domain db files 
                   1635: 
                   1636: sub put_dom {
1.860     raeburn  1637:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1638:     if (!$udom) {
                   1639:         $udom=$env{'user.domain'};
                   1640:         if (defined(&domain($udom,'primary'))) {
                   1641:             $uhome=&domain($udom,'primary');
                   1642:         } else {
1.874     albertel 1643:             undef($uhome);
1.860     raeburn  1644:         }
                   1645:     } else {
                   1646:         if (!$uhome) {
                   1647:             if (defined(&domain($udom,'primary'))) {
                   1648:                 $uhome=&domain($udom,'primary');
                   1649:             }
                   1650:         }
                   1651:     } 
                   1652:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1653:         my $items='';
                   1654:         foreach my $item (keys(%$storehash)) {
                   1655:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1656:         }
                   1657:         $items=~s/\&$//;
                   1658:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1659:     } else {
1.860     raeburn  1660:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1661:     }
                   1662: }
                   1663: 
1.1023    raeburn  1664: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1665: sub newput_dom {
1.1023    raeburn  1666:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1667:     my $result;
                   1668:     if (!$udom) {
                   1669:         $udom=$env{'user.domain'};
                   1670:     }
1.1023    raeburn  1671:     if ($udom) {
                   1672:         my $uname = &get_domainconfiguser($udom);
                   1673:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1674:     }
                   1675:     return $result;
                   1676: }
                   1677: 
1.1023    raeburn  1678: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1679: sub del_dom {
1.1023    raeburn  1680:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1681:     if (ref($storearr) eq 'ARRAY') {
                   1682:         if (!$udom) {
                   1683:             $udom=$env{'user.domain'};
                   1684:         }
1.1023    raeburn  1685:         if ($udom) {
                   1686:             my $uname = &get_domainconfiguser($udom); 
                   1687:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1688:         }
                   1689:     }
                   1690: }
                   1691: 
1.1023    raeburn  1692: # ----------------------------------construct domainconfig user for a domain 
                   1693: sub get_domainconfiguser {
                   1694:     my ($udom) = @_;
                   1695:     return $udom.'-domainconfig';
                   1696: }
                   1697: 
1.837     raeburn  1698: sub retrieve_inst_usertypes {
                   1699:     my ($udom) = @_;
                   1700:     my (%returnhash,@order);
1.989     raeburn  1701:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1702:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1703:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
                   1704:         %returnhash = %{$domdefs{'inststatustypes'}};
                   1705:         @order = @{$domdefs{'inststatusorder'}};
                   1706:     } else {
                   1707:         if (defined(&domain($udom,'primary'))) {
                   1708:             my $uhome=&domain($udom,'primary');
                   1709:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1710:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1711:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1712:                 return (\%returnhash,\@order);
                   1713:             }
                   1714:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1715:             my @pairs=split(/\&/,$hashitems);
                   1716:             foreach my $item (@pairs) {
                   1717:                 my ($key,$value)=split(/=/,$item,2);
                   1718:                 $key = &unescape($key);
                   1719:                 next if ($key =~ /^error: 2 /);
                   1720:                 $returnhash{$key}=&thaw_unescape($value);
                   1721:             }
                   1722:             my @esc_order = split(/\&/,$orderitems);
                   1723:             foreach my $item (@esc_order) {
                   1724:                 push(@order,&unescape($item));
                   1725:             }
                   1726:         } else {
                   1727:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1728:         }
                   1729:     }
                   1730:     return (\%returnhash,\@order);
                   1731: }
                   1732: 
1.868     raeburn  1733: sub is_domainimage {
                   1734:     my ($url) = @_;
                   1735:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1736:         if (&domain($1) ne '') {
                   1737:             return '1';
                   1738:         }
                   1739:     }
                   1740:     return;
                   1741: }
                   1742: 
1.899     raeburn  1743: sub inst_directory_query {
                   1744:     my ($srch) = @_;
                   1745:     my $udom = $srch->{'srchdomain'};
                   1746:     my %results;
                   1747:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1748:     my $outcome;
1.899     raeburn  1749:     if ($homeserver ne '') {
1.904     albertel 1750: 	my $queryid=&reply("querysend:instdirsearch:".
                   1751: 			   &escape($srch->{'srchby'}).':'.
                   1752: 			   &escape($srch->{'srchterm'}).':'.
                   1753: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1754: 	my $host=&hostname($homeserver);
                   1755: 	if ($queryid !~/^\Q$host\E\_/) {
                   1756: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1757: 	    return;
                   1758: 	}
                   1759: 	my $response = &get_query_reply($queryid);
                   1760: 	my $maxtries = 5;
                   1761: 	my $tries = 1;
                   1762: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1763: 	    $response = &get_query_reply($queryid);
                   1764: 	    $tries ++;
                   1765: 	}
                   1766: 
                   1767:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1768:             if ($response eq 'unavailable') {
                   1769:                 $outcome = $response;
                   1770:             } else {
                   1771:                 $outcome = 'ok';
                   1772:                 my @matches = split(/\n/,$response);
                   1773:                 foreach my $match (@matches) {
                   1774:                     my ($key,$value) = split(/=/,$match);
                   1775:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1776:                 }
1.899     raeburn  1777:             }
                   1778:         }
                   1779:     }
1.909     raeburn  1780:     return ($outcome,%results);
1.899     raeburn  1781: }
                   1782: 
                   1783: sub usersearch {
                   1784:     my ($srch) = @_;
                   1785:     my $dom = $srch->{'srchdomain'};
                   1786:     my %results;
                   1787:     my %libserv = &all_library();
                   1788:     my $query = 'usersearch';
                   1789:     foreach my $tryserver (keys(%libserv)) {
                   1790:         if (&host_domain($tryserver) eq $dom) {
                   1791:             my $host=&hostname($tryserver);
                   1792:             my $queryid=
1.911     raeburn  1793:                 &reply("querysend:".&escape($query).':'.
                   1794:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1795:                        &escape($srch->{'srchtype'}).':'.
                   1796:                        &escape($srch->{'srchterm'}),$tryserver);
                   1797:             if ($queryid !~/^\Q$host\E\_/) {
                   1798:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1799:                 next;
1.899     raeburn  1800:             }
                   1801:             my $reply = &get_query_reply($queryid);
                   1802:             my $maxtries = 1;
                   1803:             my $tries = 1;
                   1804:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1805:                 $reply = &get_query_reply($queryid);
                   1806:                 $tries ++;
                   1807:             }
                   1808:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1809:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1810:             } else {
1.911     raeburn  1811:                 my @matches;
                   1812:                 if ($reply =~ /\n/) {
                   1813:                     @matches = split(/\n/,$reply);
                   1814:                 } else {
                   1815:                     @matches = split(/\&/,$reply);
                   1816:                 }
1.899     raeburn  1817:                 foreach my $match (@matches) {
                   1818:                     my ($uname,$udom,%userhash);
1.911     raeburn  1819:                     foreach my $entry (split(/:/,$match)) {
                   1820:                         my ($key,$value) =
                   1821:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1822:                         $userhash{$key} = $value;
                   1823:                         if ($key eq 'username') {
                   1824:                             $uname = $value;
                   1825:                         } elsif ($key eq 'domain') {
                   1826:                             $udom = $value;
1.911     raeburn  1827:                         }
1.899     raeburn  1828:                     }
                   1829:                     $results{$uname.':'.$udom} = \%userhash;
                   1830:                 }
                   1831:             }
                   1832:         }
                   1833:     }
                   1834:     return %results;
                   1835: }
                   1836: 
1.912     raeburn  1837: sub get_instuser {
                   1838:     my ($udom,$uname,$id) = @_;
                   1839:     my $homeserver = &domain($udom,'primary');
                   1840:     my ($outcome,%results);
                   1841:     if ($homeserver ne '') {
                   1842:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1843:                            &escape($id).':'.&escape($udom),$homeserver);
                   1844:         my $host=&hostname($homeserver);
                   1845:         if ($queryid !~/^\Q$host\E\_/) {
                   1846:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1847:             return;
                   1848:         }
                   1849:         my $response = &get_query_reply($queryid);
                   1850:         my $maxtries = 5;
                   1851:         my $tries = 1;
                   1852:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1853:             $response = &get_query_reply($queryid);
                   1854:             $tries ++;
                   1855:         }
                   1856:         if (!&error($response) && $response ne 'refused') {
                   1857:             if ($response eq 'unavailable') {
                   1858:                 $outcome = $response;
                   1859:             } else {
                   1860:                 $outcome = 'ok';
                   1861:                 my @matches = split(/\n/,$response);
                   1862:                 foreach my $match (@matches) {
                   1863:                     my ($key,$value) = split(/=/,$match);
                   1864:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1865:                 }
                   1866:             }
                   1867:         }
                   1868:     }
                   1869:     my %userinfo;
                   1870:     if (ref($results{$uname}) eq 'HASH') {
                   1871:         %userinfo = %{$results{$uname}};
                   1872:     } 
                   1873:     return ($outcome,%userinfo);
                   1874: }
                   1875: 
                   1876: sub inst_rulecheck {
1.923     raeburn  1877:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1878:     my %returnhash;
                   1879:     if ($udom ne '') {
                   1880:         if (ref($rules) eq 'ARRAY') {
                   1881:             @{$rules} = map {&escape($_);} (@{$rules});
                   1882:             my $rulestr = join(':',@{$rules});
                   1883:             my $homeserver=&domain($udom,'primary');
                   1884:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1885:                 my $response;
                   1886:                 if ($item eq 'username') {                
                   1887:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1888:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1889:                                               $homeserver));
1.923     raeburn  1890:                 } elsif ($item eq 'id') {
                   1891:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1892:                                               ':'.&escape($id).':'.$rulestr,
                   1893:                                               $homeserver));
1.945     raeburn  1894:                 } elsif ($item eq 'selfcreate') {
                   1895:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1896:                                                &escape($udom).':'.&escape($uname).
                   1897:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1898:                 }
1.912     raeburn  1899:                 if ($response ne 'refused') {
                   1900:                     my @pairs=split(/\&/,$response);
                   1901:                     foreach my $item (@pairs) {
                   1902:                         my ($key,$value)=split(/=/,$item,2);
                   1903:                         $key = &unescape($key);
                   1904:                         next if ($key =~ /^error: 2 /);
                   1905:                         $returnhash{$key}=&thaw_unescape($value);
                   1906:                     }
                   1907:                 }
                   1908:             }
                   1909:         }
                   1910:     }
                   1911:     return %returnhash;
                   1912: }
                   1913: 
                   1914: sub inst_userrules {
1.923     raeburn  1915:     my ($udom,$check) = @_;
1.912     raeburn  1916:     my (%ruleshash,@ruleorder);
                   1917:     if ($udom ne '') {
                   1918:         my $homeserver=&domain($udom,'primary');
                   1919:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1920:             my $response;
                   1921:             if ($check eq 'id') {
                   1922:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1923:                                  $homeserver);
1.943     raeburn  1924:             } elsif ($check eq 'email') {
                   1925:                 $response=&reply('instemailrules:'.&escape($udom),
                   1926:                                  $homeserver);
1.923     raeburn  1927:             } else {
                   1928:                 $response=&reply('instuserrules:'.&escape($udom),
                   1929:                                  $homeserver);
                   1930:             }
1.912     raeburn  1931:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1932:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1933:                 ($response ne 'no_such_host')) {
                   1934:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1935:                 my @pairs=split(/\&/,$hashitems);
                   1936:                 foreach my $item (@pairs) {
                   1937:                     my ($key,$value)=split(/=/,$item,2);
                   1938:                     $key = &unescape($key);
                   1939:                     next if ($key =~ /^error: 2 /);
                   1940:                     $ruleshash{$key}=&thaw_unescape($value);
                   1941:                 }
                   1942:                 my @esc_order = split(/\&/,$orderitems);
                   1943:                 foreach my $item (@esc_order) {
                   1944:                     push(@ruleorder,&unescape($item));
                   1945:                 }
                   1946:             }
                   1947:         }
                   1948:     }
                   1949:     return (\%ruleshash,\@ruleorder);
                   1950: }
                   1951: 
1.976     raeburn  1952: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1953: 
                   1954: sub get_domain_defaults {
                   1955:     my ($domain) = @_;
                   1956:     my $cachetime = 60*60*24;
                   1957:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1958:     if (defined($cached)) {
                   1959:         if (ref($result) eq 'HASH') {
                   1960:             return %{$result};
                   1961:         }
                   1962:     }
                   1963:     my %domdefaults;
                   1964:     my %domconfig =
1.989     raeburn  1965:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  1966:                                   'requestcourses','inststatus',
1.1172.2.9  raeburn  1967:                                   'coursedefaults','usersessions',
                   1968:                                   'requestauthor'],$domain);
1.943     raeburn  1969:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1970:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1971:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1972:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  1973:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  1974:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  1975:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943     raeburn  1976:     } else {
                   1977:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1978:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1979:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1980:     }
1.976     raeburn  1981:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1982:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1983:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1984:         } else {
                   1985:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1986:         } 
1.1172.2.6  raeburn  1987:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  1988:         foreach my $item (@usertools) {
                   1989:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1990:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1991:             }
                   1992:         }
                   1993:     }
1.985     raeburn  1994:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006    raeburn  1995:         foreach my $item ('official','unofficial','community') {
1.985     raeburn  1996:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   1997:         }
                   1998:     }
1.1172.2.9  raeburn  1999:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2000:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2001:     }
1.989     raeburn  2002:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   2003:         foreach my $item ('inststatustypes','inststatusorder') {
                   2004:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2005:         }
                   2006:     }
1.1047    raeburn  2007:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.19  raeburn  2008:         if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2009:             $domdefaults{'officialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'official'};
                   2010:             $domdefaults{'unofficialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'unofficial'};
1.1047    raeburn  2011:         }
                   2012:     }
1.1073    raeburn  2013:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2014:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2015:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2016:         }
                   2017:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2018:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2019:         }
                   2020:     }
1.1172.2.23  raeburn  2021:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2022:     return %domdefaults;
                   2023: }
                   2024: 
1.344     www      2025: # --------------------------------------------------- Assign a key to a student
                   2026: 
                   2027: sub assign_access_key {
1.364     www      2028: #
                   2029: # a valid key looks like uname:udom#comments
                   2030: # comments are being appended
                   2031: #
1.498     www      2032:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2033:     $kdom=
1.620     albertel 2034:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2035:     $knum=
1.620     albertel 2036:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2037:     $cdom=
1.620     albertel 2038:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2039:     $cnum=
1.620     albertel 2040:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2041:     $udom=$env{'user.name'} unless (defined($udom));
                   2042:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2043:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2044:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2045:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2046:                                                   # assigned to this person
                   2047:                                                   # - this should not happen,
1.345     www      2048:                                                   # unless something went wrong
                   2049:                                                   # the first time around
                   2050: # ready to assign
1.364     www      2051:         $logentry=$1.'; '.$logentry;
1.496     www      2052:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2053:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2054: # key now belongs to user
1.346     www      2055: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2056:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2057:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2058:                 return 'ok';
                   2059:             } else {
                   2060:                 return 
                   2061:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2062: 	    }
                   2063:         } else {
                   2064:             return 'error: Could not assign key, try again later.';
                   2065:         }
1.364     www      2066:     } elsif (!$existing{$ckey}) {
1.345     www      2067: # the key does not exist
                   2068: 	return 'error: The key does not exist';
                   2069:     } else {
                   2070: # the key is somebody else's
                   2071: 	return 'error: The key is already in use';
                   2072:     }
1.344     www      2073: }
                   2074: 
1.364     www      2075: # ------------------------------------------ put an additional comment on a key
                   2076: 
                   2077: sub comment_access_key {
                   2078: #
                   2079: # a valid key looks like uname:udom#comments
                   2080: # comments are being appended
                   2081: #
                   2082:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2083:     $cdom=
1.620     albertel 2084:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2085:     $cnum=
1.620     albertel 2086:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2087:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2088:     if ($existing{$ckey}) {
                   2089:         $existing{$ckey}.='; '.$logentry;
                   2090: # ready to assign
1.367     www      2091:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2092:                                                  $cdom,$cnum) eq 'ok') {
                   2093: 	    return 'ok';
                   2094:         } else {
                   2095: 	    return 'error: Count not store comment.';
                   2096:         }
                   2097:     } else {
                   2098: # the key does not exist
                   2099: 	return 'error: The key does not exist';
                   2100:     }
                   2101: }
                   2102: 
1.344     www      2103: # ------------------------------------------------------ Generate a set of keys
                   2104: 
                   2105: sub generate_access_keys {
1.364     www      2106:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2107:     $cdom=
1.620     albertel 2108:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2109:     $cnum=
1.620     albertel 2110:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2111:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2112:     unless (($cdom) && ($cnum)) { return 0; }
                   2113:     if ($number>10000) { return 0; }
                   2114:     sleep(2); # make sure don't get same seed twice
                   2115:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2116:     my $total=0;
                   2117:     for (my $i=1;$i<=$number;$i++) {
                   2118:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2119:                   sprintf("%lx",int(100000*rand)).'-'.
                   2120:                   sprintf("%lx",int(100000*rand));
                   2121:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2122:        $newkey=~s/0/h/g; # and also 0 and O
                   2123:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2124:        if ($existing{$newkey}) {
                   2125:            $i--;
                   2126:        } else {
1.364     www      2127: 	  if (&put('accesskeys',
                   2128:               { $newkey => '# generated '.localtime().
1.620     albertel 2129:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2130:                            '; '.$logentry },
                   2131: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2132:               $total++;
                   2133: 	  }
                   2134:        }
                   2135:     }
1.620     albertel 2136:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2137:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2138:     return $total;
                   2139: }
                   2140: 
                   2141: # ------------------------------------------------------- Validate an accesskey
                   2142: 
                   2143: sub validate_access_key {
                   2144:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2145:     $cdom=
1.620     albertel 2146:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2147:     $cnum=
1.620     albertel 2148:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2149:     $udom=$env{'user.domain'} unless (defined($udom));
                   2150:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2151:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2152:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2153: }
                   2154: 
                   2155: # ------------------------------------- Find the section of student in a course
1.652     albertel 2156: sub devalidate_getsection_cache {
                   2157:     my ($udom,$unam,$courseid)=@_;
                   2158:     my $hashid="$udom:$unam:$courseid";
                   2159:     &devalidate_cache_new('getsection',$hashid);
                   2160: }
1.298     matthew  2161: 
1.815     albertel 2162: sub courseid_to_courseurl {
                   2163:     my ($courseid) = @_;
                   2164:     #already url style courseid
                   2165:     return $courseid if ($courseid =~ m{^/});
                   2166: 
                   2167:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2168: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2169: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2170: 	return "/$cdom/$cnum";
                   2171:     }
                   2172: 
                   2173:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2174:     if (exists($courseinfo{'num'})) {
                   2175: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2176:     }
                   2177: 
                   2178:     return undef;
                   2179: }
                   2180: 
1.298     matthew  2181: sub getsection {
                   2182:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2183:     my $cachetime=1800;
1.551     albertel 2184: 
                   2185:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2186:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2187:     if (defined($cached)) { return $result; }
                   2188: 
1.298     matthew  2189:     my %Pending; 
                   2190:     my %Expired;
                   2191:     #
                   2192:     # Each role can either have not started yet (pending), be active, 
                   2193:     #    or have expired.
                   2194:     #
                   2195:     # If there is an active role, we are done.
                   2196:     #
                   2197:     # If there is more than one role which has not started yet, 
                   2198:     #     choose the one which will start sooner
                   2199:     # If there is one role which has not started yet, return it.
                   2200:     #
                   2201:     # If there is more than one expired role, choose the one which ended last.
                   2202:     # If there is a role which has expired, return it.
                   2203:     #
1.815     albertel 2204:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2205:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2206:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2207:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2208:         my $section=$1;
                   2209:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2210:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2211:         my $now=time;
1.548     albertel 2212:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2213:             $Expired{$end}=$section;
                   2214:             next;
                   2215:         }
1.548     albertel 2216:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2217:             $Pending{$start}=$section;
                   2218:             next;
                   2219:         }
1.599     albertel 2220:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2221:     }
                   2222:     #
                   2223:     # Presumedly there will be few matching roles from the above
                   2224:     # loop and the sorting time will be negligible.
                   2225:     if (scalar(keys(%Pending))) {
                   2226:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2227:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2228:     } 
                   2229:     if (scalar(keys(%Expired))) {
                   2230:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2231:         my $time = pop(@sorted);
1.599     albertel 2232:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2233:     }
1.599     albertel 2234:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2235: }
1.70      www      2236: 
1.599     albertel 2237: sub save_cache {
                   2238:     &purge_remembered();
1.722     albertel 2239:     #&Apache::loncommon::validate_page();
1.620     albertel 2240:     undef(%env);
1.780     albertel 2241:     undef($env_loaded);
1.599     albertel 2242: }
1.452     albertel 2243: 
1.599     albertel 2244: my $to_remember=-1;
                   2245: my %remembered;
                   2246: my %accessed;
                   2247: my $kicks=0;
                   2248: my $hits=0;
1.849     albertel 2249: sub make_key {
                   2250:     my ($name,$id) = @_;
1.872     albertel 2251:     if (length($id) > 65 
                   2252: 	&& length(&escape($id)) > 200) {
                   2253: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2254:     }
1.849     albertel 2255:     return &escape($name.':'.$id);
                   2256: }
                   2257: 
1.599     albertel 2258: sub devalidate_cache_new {
                   2259:     my ($name,$id,$debug) = @_;
                   2260:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 2261:     $id=&make_key($name,$id);
1.599     albertel 2262:     $memcache->delete($id);
                   2263:     delete($remembered{$id});
                   2264:     delete($accessed{$id});
                   2265: }
                   2266: 
                   2267: sub is_cached_new {
                   2268:     my ($name,$id,$debug) = @_;
1.849     albertel 2269:     $id=&make_key($name,$id);
1.599     albertel 2270:     if (exists($remembered{$id})) {
1.1133    foxr     2271: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599     albertel 2272: 	$accessed{$id}=[&gettimeofday()];
                   2273: 	$hits++;
                   2274: 	return ($remembered{$id},1);
                   2275:     }
                   2276:     my $value = $memcache->get($id);
                   2277:     if (!(defined($value))) {
                   2278: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2279: 	return (undef,undef);
1.416     albertel 2280:     }
1.599     albertel 2281:     if ($value eq '__undef__') {
                   2282: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2283: 	$value=undef;
                   2284:     }
                   2285:     &make_room($id,$value,$debug);
                   2286:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2287:     return ($value,1);
                   2288: }
                   2289: 
                   2290: sub do_cache_new {
                   2291:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 2292:     $id=&make_key($name,$id);
1.599     albertel 2293:     my $setvalue=$value;
                   2294:     if (!defined($setvalue)) {
                   2295: 	$setvalue='__undef__';
                   2296:     }
1.623     albertel 2297:     if (!defined($time) ) {
                   2298: 	$time=600;
                   2299:     }
1.599     albertel 2300:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2301:     my $result = $memcache->set($id,$setvalue,$time);
                   2302:     if (! $result) {
1.872     albertel 2303: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2304: 	$memcache->disconnect_all();
1.872     albertel 2305:     }
1.600     albertel 2306:     # need to make a copy of $value
1.919     albertel 2307:     &make_room($id,$value,$debug);
1.599     albertel 2308:     return $value;
                   2309: }
                   2310: 
                   2311: sub make_room {
                   2312:     my ($id,$value,$debug)=@_;
1.919     albertel 2313: 
                   2314:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   2315:                                     : $value;
1.599     albertel 2316:     if ($to_remember<0) { return; }
                   2317:     $accessed{$id}=[&gettimeofday()];
                   2318:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2319:     my $to_kick;
                   2320:     my $max_time=0;
                   2321:     foreach my $other (keys(%accessed)) {
                   2322: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2323: 	    $to_kick=$other;
                   2324: 	    $max_time=&tv_interval($accessed{$other});
                   2325: 	}
                   2326:     }
                   2327:     delete($remembered{$to_kick});
                   2328:     delete($accessed{$to_kick});
                   2329:     $kicks++;
                   2330:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2331:     return;
                   2332: }
                   2333: 
1.599     albertel 2334: sub purge_remembered {
1.604     albertel 2335:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2336:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2337:     undef(%remembered);
                   2338:     undef(%accessed);
1.428     albertel 2339: }
1.70      www      2340: # ------------------------------------- Read an entry from a user's environment
                   2341: 
                   2342: sub userenvironment {
                   2343:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2344:     my $items;
                   2345:     foreach my $item (@what) {
                   2346:         $items.=&escape($item).'&';
                   2347:     }
                   2348:     $items=~s/\&$//;
1.70      www      2349:     my %returnhash=();
1.1009    raeburn  2350:     my $uhome = &homeserver($unam,$udom);
                   2351:     unless ($uhome eq 'no_host') {
                   2352:         my @answer=split(/\&/, 
                   2353:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2354:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2355:             return %returnhash;
                   2356:         }
1.1009    raeburn  2357:         my $i;
                   2358:         for ($i=0;$i<=$#what;$i++) {
                   2359: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2360:         }
1.70      www      2361:     }
                   2362:     return %returnhash;
1.1       albertel 2363: }
                   2364: 
1.617     albertel 2365: # ---------------------------------------------------------- Get a studentphoto
                   2366: sub studentphoto {
                   2367:     my ($udom,$unam,$ext) = @_;
                   2368:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2369:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2370:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2371:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2372:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2373:             } else {
                   2374:                 my ($result,$perm_reqd)=
1.707     albertel 2375: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2376:                 if ($result eq 'ok') {
                   2377:                     if (!($perm_reqd eq 'yes')) {
                   2378:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2379:                     }
                   2380:                 }
                   2381:             }
                   2382:         }
                   2383:     } else {
                   2384:         my ($result,$perm_reqd) = 
1.707     albertel 2385: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2386:         if ($result eq 'ok') {
                   2387:             if (!($perm_reqd eq 'yes')) {
                   2388:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2389:             }
                   2390:         }
                   2391:     }
                   2392:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2393: }
                   2394: 
                   2395: sub retrievestudentphoto {
                   2396:     my ($udom,$unam,$ext,$type) = @_;
                   2397:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2398:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2399:     if ($ret eq 'ok') {
                   2400:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2401:         if ($type eq 'thumbnail') {
                   2402:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2403:         }
                   2404:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2405:         return $tokenurl;
                   2406:     } else {
                   2407:         if ($type eq 'thumbnail') {
                   2408:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2409:         } else { 
                   2410:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2411:         }
1.617     albertel 2412:     }
                   2413: }
                   2414: 
1.263     www      2415: # -------------------------------------------------------------------- New chat
                   2416: 
                   2417: sub chatsend {
1.724     raeburn  2418:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2419:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2420:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2421:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2422:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2423: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2424: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2425: }
                   2426: 
                   2427: # ------------------------------------------ Find current version of a resource
                   2428: 
                   2429: sub getversion {
                   2430:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  2431:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2432:     return &currentversion(&filelocation('',$fname));
                   2433: }
                   2434: 
                   2435: sub currentversion {
                   2436:     my $fname=shift;
                   2437:     my $author=$fname;
                   2438:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2439:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2440:     my $home=&homeserver($uname,$udom);
1.292     www      2441:     if ($home eq 'no_host') { 
                   2442:         return -1; 
                   2443:     }
1.1112    www      2444:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2445:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2446: 	return -1;
                   2447:     }
1.1112    www      2448:     return $answer;
1.263     www      2449: }
                   2450: 
1.1111    www      2451: #
                   2452: # Return special version number of resource if set by override, empty otherwise
                   2453: #
                   2454: sub usedversion {
                   2455:     my $fname=shift;
                   2456:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2457:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2458:     if ($urlversion) { return $urlversion; }
                   2459:     return '';
                   2460: }
                   2461: 
1.1       albertel 2462: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2463: 
1.1       albertel 2464: sub subscribe {
                   2465:     my $fname=shift;
1.761     raeburn  2466:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2467:     $fname=~s/[\n\r]//g;
1.1       albertel 2468:     my $author=$fname;
                   2469:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2470:     my ($udom,$uname)=split(/\//,$author);
                   2471:     my $home=homeserver($uname,$udom);
1.335     albertel 2472:     if ($home eq 'no_host') {
                   2473:         return 'not_found';
1.1       albertel 2474:     }
                   2475:     my $answer=reply("sub:$fname",$home);
1.64      www      2476:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2477: 	$answer.=' by '.$home;
                   2478:     }
1.1       albertel 2479:     return $answer;
                   2480: }
                   2481:     
1.8       www      2482: # -------------------------------------------------------------- Replicate file
                   2483: 
                   2484: sub repcopy {
                   2485:     my $filename=shift;
1.23      www      2486:     $filename=~s/\/+/\//g;
1.1142    raeburn  2487:     my $londocroot = $perlvar{'lonDocRoot'};
                   2488:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2489:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2490:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2491: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2492: 	return &repcopy_userfile($filename);
                   2493:     }
1.532     albertel 2494:     $filename=~s/[\n\r]//g;
1.8       www      2495:     my $transname="$filename.in.transfer";
1.828     www      2496: # FIXME: this should flock
1.607     raeburn  2497:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2498:     my $remoteurl=subscribe($filename);
1.64      www      2499:     if ($remoteurl =~ /^con_lost by/) {
                   2500: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2501:            return 'unavailable';
1.8       www      2502:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2503: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2504: 	   return 'not_found';
1.64      www      2505:     } elsif ($remoteurl =~ /^rejected by/) {
                   2506: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2507:            return 'forbidden';
1.20      www      2508:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2509:            return 'ok';
1.8       www      2510:     } else {
1.290     www      2511:         my $author=$filename;
                   2512:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2513:         my ($udom,$uname)=split(/\//,$author);
                   2514:         my $home=homeserver($uname,$udom);
                   2515:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2516:            my @parts=split(/\//,$filename);
                   2517:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2518:            if ($path ne "$londocroot/res") {
1.8       www      2519:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2520: 	       return 'bad_request';
1.8       www      2521:            }
                   2522:            my $count;
                   2523:            for ($count=5;$count<$#parts;$count++) {
                   2524:                $path.="/$parts[$count]";
                   2525:                if ((-e $path)!=1) {
                   2526: 		   mkdir($path,0777);
                   2527:                }
                   2528:            }
                   2529:            my $ua=new LWP::UserAgent;
                   2530:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2531:            my $response=$ua->request($request,$transname);
                   2532:            if ($response->is_error()) {
                   2533: 	       unlink($transname);
                   2534:                my $message=$response->status_line;
1.672     albertel 2535:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2536:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2537:                return 'unavailable';
1.8       www      2538:            } else {
1.16      www      2539: 	       if ($remoteurl!~/\.meta$/) {
                   2540:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2541:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2542:                   if ($mresponse->is_error()) {
                   2543: 		      unlink($filename.'.meta');
                   2544:                       &logthis(
1.672     albertel 2545:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2546:                   }
                   2547: 	       }
1.8       www      2548:                rename($transname,$filename);
1.607     raeburn  2549:                return 'ok';
1.8       www      2550:            }
1.290     www      2551:        }
1.8       www      2552:     }
1.330     www      2553: }
                   2554: 
                   2555: # ------------------------------------------------ Get server side include body
                   2556: sub ssi_body {
1.381     albertel 2557:     my ($filelink,%form)=@_;
1.606     matthew  2558:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2559:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2560:     }
1.953     www      2561:     my $output='';
                   2562:     my $response;
1.980     raeburn  2563:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2564:        ($output,$response)=&externalssi($filelink);
1.953     www      2565:     } else {
1.1004    droeschl 2566:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2567:        $filelink .= 'inhibitmenu=yes';
1.953     www      2568:        ($output,$response)=&ssi($filelink,%form);
                   2569:     }
1.778     albertel 2570:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2571:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2572:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2573:     if (wantarray) {
                   2574:         return ($output, $response);
                   2575:     } else {
                   2576:         return $output;
                   2577:     }
1.8       www      2578: }
                   2579: 
1.15      www      2580: # --------------------------------------------------------- Server Side Include
                   2581: 
1.782     albertel 2582: sub absolute_url {
                   2583:     my ($host_name) = @_;
                   2584:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2585:     if ($host_name eq '') {
                   2586: 	$host_name = $ENV{'SERVER_NAME'};
                   2587:     }
                   2588:     return $protocol.$host_name;
                   2589: }
                   2590: 
1.942     foxr     2591: #
                   2592: #   Server side include.
                   2593: # Parameters:
                   2594: #  fn     Possibly encrypted resource name/id.
                   2595: #  form   Hash that describes how the rendering should be done
                   2596: #         and other things.
1.944     foxr     2597: # Returns:
1.950     raeburn  2598: #   Scalar context: The content of the response.
                   2599: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2600: #     
1.15      www      2601: sub ssi {
                   2602: 
1.944     foxr     2603:     my ($fn,%form)=@_;
1.15      www      2604:     my $ua=new LWP::UserAgent;
1.23      www      2605:     my $request;
1.711     albertel 2606: 
                   2607:     $form{'no_update_last_known'}=1;
1.895     albertel 2608:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2609:     if (%form) {
1.782     albertel 2610:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2611:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2612:     } else {
1.782     albertel 2613:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2614:     }
                   2615: 
1.15      www      2616:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.2  raeburn  2617:     my $response= $ua->request($request);
1.944     foxr     2618:     if (wantarray) {
1.1172.2.3  raeburn  2619: 	return ($response->content, $response);
1.944     foxr     2620:     } else {
1.1172.2.3  raeburn  2621: 	return $response->content;
1.942     foxr     2622:     }
1.324     www      2623: }
                   2624: 
                   2625: sub externalssi {
                   2626:     my ($url)=@_;
                   2627:     my $ua=new LWP::UserAgent;
                   2628:     my $request=new HTTP::Request('GET',$url);
                   2629:     my $response=$ua->request($request);
1.954     raeburn  2630:     if (wantarray) {
                   2631:         return ($response->content, $response);
                   2632:     } else {
                   2633:         return $response->content;
                   2634:     }
1.15      www      2635: }
1.254     www      2636: 
1.492     albertel 2637: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2638: 
                   2639: sub allowuploaded {
                   2640:     my ($srcurl,$url)=@_;
                   2641:     $url=&clutter(&declutter($url));
                   2642:     my $dir=$url;
                   2643:     $dir=~s/\/[^\/]+$//;
                   2644:     my %httpref=();
                   2645:     my $httpurl=&hreflocation('',$url);
                   2646:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2647:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2648: }
1.477     raeburn  2649: 
1.1172.2.13  raeburn  2650: #
                   2651: # Determine if the current user should be able to edit a particular resource,
                   2652: # when viewing in course context.
                   2653: # (a) When viewing resource used to determine if "Edit" item is included in
                   2654: #     Functions.
                   2655: # (b) When displaying folder contents in course editor, used to determine if
                   2656: #     "Edit" link will be displayed alongside resource.
                   2657: #
                   2658: #  input: six args -- filename (decluttered), course number, course domain,
                   2659: #                   url, symb (if registered) and group (if this is a group
                   2660: #                   item -- e.g., bulletin board, group page etc.).
                   2661: #  output: array of five scalars --
                   2662: #          $cfile -- url for file editing if editable on current server
                   2663: #          $home -- homeserver of resource (i.e., for author if published,
                   2664: #                                           or course if uploaded.).
                   2665: #          $switchserver --  1 if server switch will be needed.
                   2666: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   2667: #          $forceview -- 1 if icon/link should be to go to view mode
                   2668: #
                   2669: 
                   2670: sub can_edit_resource {
                   2671:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   2672:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   2673: #
                   2674: # For aboutme pages user can only edit his/her own.
                   2675: #
                   2676:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   2677:         my ($sdom,$sname) = ($1,$2);
                   2678:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   2679:             $home = $env{'user.home'};
                   2680:             $cfile = $resurl;
                   2681:             if ($env{'form.forceedit'}) {
                   2682:                 $forceview = 1;
                   2683:             } else {
                   2684:                 $forceedit = 1;
                   2685:             }
                   2686:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   2687:         } else {
                   2688:             return;
                   2689:         }
                   2690:     }
                   2691: 
                   2692:     if ($env{'request.course.id'}) {
                   2693:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   2694:         if ($group ne '') {
                   2695: # if this is a group homepage or group bulletin board, check group privs
                   2696:             my $allowed = 0;
                   2697:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   2698:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   2699:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   2700:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   2701:                     $allowed = 1;
                   2702:                 }
                   2703:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   2704:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   2705:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   2706:                     $allowed = 1;
                   2707:                 }
                   2708:             }
                   2709:             if ($allowed) {
                   2710:                 $home=&homeserver($cnum,$cdom);
                   2711:                 if ($env{'form.forceedit'}) {
                   2712:                     $forceview = 1;
                   2713:                 } else {
                   2714:                     $forceedit = 1;
                   2715:                 }
                   2716:                 $cfile = $resurl;
                   2717:             } else {
                   2718:                 return;
                   2719:             }
                   2720:         } else {
1.1172.2.15  raeburn  2721:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2722:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   2723:                     return;
                   2724:                 }
                   2725:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  2726: #
                   2727: # No edit allowed where CC has switched to student role.
                   2728: #
                   2729:                 return;
                   2730:             }
                   2731:         }
                   2732:     }
                   2733: 
                   2734:     if ($file ne '') {
                   2735:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   2736:             if (&is_course_upload($file,$cnum,$cdom)) {
                   2737:                 $uploaded = 1;
                   2738:                 $incourse = 1;
                   2739:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   2740:                     $cfile = &hreflocation('',$file);
                   2741:                     if ($env{'form.forceedit'}) {
                   2742:                         $forceview = 1;
                   2743:                     } else {
                   2744:                         $forceedit = 1;
                   2745:                     }
                   2746:                 }
                   2747:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   2748:                 $incourse = 1;
                   2749:                 if ($env{'form.forceedit'}) {
                   2750:                     $forceview = 1;
                   2751:                 } else {
                   2752:                     $forceedit = 1;
                   2753:                 }
                   2754:                 $cfile = $resurl;
                   2755:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   2756:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   2757:                     $incourse = 1;
                   2758:                     if ($env{'form.forceedit'}) {
                   2759:                         $forceview = 1;
                   2760:                     } else {
                   2761:                         $forceedit = 1;
                   2762:                     }
                   2763:                     $cfile = $resurl;
                   2764:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   2765:                     $incourse = 1;
                   2766:                     $cfile = $resurl.'/smpedit';
                   2767:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   2768:                     $incourse = 1;
                   2769:                     if ($env{'form.forceedit'}) {
                   2770:                         $forceview = 1;
                   2771:                     } else {
                   2772:                         $forceedit = 1;
                   2773:                     }
                   2774:                     $cfile = $resurl;
1.1172.2.15  raeburn  2775:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2776:                     $incourse = 1;
                   2777:                     if ($env{'form.forceedit'}) {
                   2778:                         $forceview = 1;
                   2779:                     } else {
                   2780:                         $forceedit = 1;
                   2781:                     }
                   2782:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  2783:                 }
                   2784:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   2785:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   2786:                 if (&is_on_map($template)) {
                   2787:                     $incourse = 1;
                   2788:                     $forceview = 1;
                   2789:                     $cfile = $template;
                   2790:                 }
                   2791:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   2792:                     $incourse = 1;
                   2793:                     if ($env{'form.forceedit'}) {
                   2794:                         $forceview = 1;
                   2795:                     } else {
                   2796:                         $forceedit = 1;
                   2797:                     }
                   2798:                     $cfile = $resurl;
                   2799:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   2800:                 $incourse = 1;
                   2801:                 $forceview = 1;
                   2802:                 if ($symb) {
                   2803:                     my ($map,$id,$res)=&decode_symb($symb);
                   2804:                     $env{'request.symb'} = $symb;
                   2805:                     $cfile = &clutter($res);
                   2806:                 } else {
                   2807:                     $cfile = $env{'form.suppurl'};
                   2808:                     $cfile =~ s{^http://}{};
                   2809:                     $cfile = '/adm/wrapper/ext/'.$cfile;
                   2810:                 }
                   2811:             }
                   2812:         }
                   2813:         if ($uploaded || $incourse) {
                   2814:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  2815:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  2816:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   2817:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   2818:             # Check that the user has permission to edit this resource
                   2819:             my $setpriv = 1;
                   2820:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   2821:             if (defined($cfudom)) {
                   2822:                 $home=&homeserver($cfuname,$cfudom);
                   2823:                 $cfile=$file;
                   2824:             }
                   2825:         }
                   2826:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   2827:             (($home ne '') && ($home ne 'no_host'))) {
                   2828:             my @ids=&current_machine_ids();
                   2829:             unless (grep(/^\Q$home\E$/,@ids)) {
                   2830:                 $switchserver=1;
                   2831:             }
                   2832:         }
                   2833:     }
                   2834:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   2835: }
                   2836: 
                   2837: sub is_course_upload {
                   2838:     my ($file,$cnum,$cdom) = @_;
                   2839:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   2840:     $uploadpath =~ s{^\/}{};
                   2841:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   2842:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   2843:         return 1;
                   2844:     }
                   2845:     return;
                   2846: }
                   2847: 
                   2848: sub in_course {
                   2849:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   2850:     if ($hideprivileged) {
                   2851:         my $skipuser;
1.1172.2.23  raeburn  2852:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   2853:         my @possdoms = ($cdom);
                   2854:         if ($coursehash{'checkforpriv'}) {
                   2855:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   2856:         }
                   2857:         if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13  raeburn  2858:             $skipuser = 1;
                   2859:             if ($coursehash{'nothideprivileged'}) {
                   2860:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2861:                     my $user;
                   2862:                     if ($item =~ /:/) {
                   2863:                         $user = $item;
                   2864:                     } else {
                   2865:                         $user = join(':',split(/[\@]/,$item));
                   2866:                     }
                   2867:                     if ($user eq $uname.':'.$udom) {
                   2868:                         undef($skipuser);
                   2869:                         last;
                   2870:                     }
                   2871:                 }
                   2872:             }
                   2873:             if ($skipuser) {
                   2874:                 return 0;
                   2875:             }
                   2876:         }
                   2877:     }
                   2878:     $type ||= 'any';
                   2879:     if (!defined($cdom) || !defined($cnum)) {
                   2880:         my $cid  = $env{'request.course.id'};
                   2881:         $cdom = $env{'course.'.$cid.'.domain'};
                   2882:         $cnum = $env{'course.'.$cid.'.num'};
                   2883:     }
                   2884:     my $typesref;
                   2885:     if (($type eq 'any') || ($type eq 'all')) {
                   2886:         $typesref = ['active','previous','future'];
                   2887:     } elsif ($type eq 'previous' || $type eq 'future') {
                   2888:         $typesref = [$type];
                   2889:     }
                   2890:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   2891:                               $typesref,undef,[$cdom]);
                   2892:     my ($tmp) = keys(%roles);
                   2893:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   2894:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   2895:     if (@course_roles > 0) {
                   2896:         return 1;
                   2897:     }
                   2898:     return 0;
                   2899: }
                   2900: 
1.478     albertel 2901: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2902: # input: action, courseID, current domain, intended
1.637     raeburn  2903: #        path to file, source of file, instruction to parse file for objects,
                   2904: #        ref to hash for embedded objects,
                   2905: #        ref to hash for codebase of java objects.
1.1095    raeburn  2906: #        reference to scalar to accommodate mime type determined
                   2907: #          from File::MMagic if $parser = parse.
1.637     raeburn  2908: #
1.485     raeburn  2909: # output: url to file (if action was uploaddoc), 
                   2910: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2911: #
1.478     albertel 2912: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2913: # course.
1.477     raeburn  2914: #
1.478     albertel 2915: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2916: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2917: #          course's home server.
1.477     raeburn  2918: #
1.478     albertel 2919: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2920: #          be copied from $source (current location) to 
                   2921: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2922: #         and will then be copied to
                   2923: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2924: #         course's home server.
1.485     raeburn  2925: #
1.481     raeburn  2926: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2927: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2928: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2929: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2930: #         in course's home server.
1.637     raeburn  2931: #
1.477     raeburn  2932: 
                   2933: sub process_coursefile {
1.1095    raeburn  2934:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   2935:         $mimetype)=@_;
1.477     raeburn  2936:     my $fetchresult;
1.638     albertel 2937:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2938:     if ($action eq 'propagate') {
1.638     albertel 2939:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2940: 			     $home);
1.481     raeburn  2941:     } else {
1.477     raeburn  2942:         my $fpath = '';
                   2943:         my $fname = $file;
1.478     albertel 2944:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2945:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2946:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2947:         if ($action eq 'copy') {
                   2948:             if ($source eq '') {
                   2949:                 $fetchresult = 'no source file';
                   2950:                 return $fetchresult;
                   2951:             } else {
                   2952:                 my $destination = $filepath.'/'.$fname;
                   2953:                 rename($source,$destination);
                   2954:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2955:                                  $home);
1.481     raeburn  2956:             }
                   2957:         } elsif ($action eq 'uploaddoc') {
                   2958:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2959:             print $fh $env{'form.'.$source};
1.481     raeburn  2960:             close($fh);
1.637     raeburn  2961:             if ($parser eq 'parse') {
1.1024    raeburn  2962:                 my $mm = new File::MMagic;
1.1095    raeburn  2963:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   2964:                 if ($type eq 'text/html') {
1.1024    raeburn  2965:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   2966:                     unless ($parse_result eq 'ok') {
                   2967:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2968:                     }
1.637     raeburn  2969:                 }
1.1095    raeburn  2970:                 if (ref($mimetype)) {
                   2971:                     $$mimetype = $type;
                   2972:                 } 
1.637     raeburn  2973:             }
1.477     raeburn  2974:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2975:                                  $home);
1.481     raeburn  2976:             if ($fetchresult eq 'ok') {
                   2977:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2978:             } else {
                   2979:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2980:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2981:                 return '/adm/notfound.html';
                   2982:             }
1.477     raeburn  2983:         }
                   2984:     }
1.485     raeburn  2985:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2986:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2987:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2988:     }
                   2989:     return $fetchresult;
                   2990: }
                   2991: 
1.637     raeburn  2992: sub build_filepath {
                   2993:     my ($fpath) = @_;
                   2994:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2995:     unless ($fpath eq '') {
                   2996:         my @parts=split('/',$fpath);
                   2997:         foreach my $part (@parts) {
                   2998:             $filepath.= '/'.$part;
                   2999:             if ((-e $filepath)!=1) {
                   3000:                 mkdir($filepath,0777);
                   3001:             }
                   3002:         }
                   3003:     }
                   3004:     return $filepath;
                   3005: }
                   3006: 
                   3007: sub store_edited_file {
1.638     albertel 3008:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3009:     my $file = $primary_url;
                   3010:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3011:     my $fpath = '';
                   3012:     my $fname = $file;
                   3013:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3014:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3015:     my $filepath = &build_filepath($fpath);
                   3016:     open(my $fh,'>'.$filepath.'/'.$fname);
                   3017:     print $fh $content;
                   3018:     close($fh);
1.638     albertel 3019:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3020:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3021: 			  $home);
1.637     raeburn  3022:     if ($$fetchresult eq 'ok') {
                   3023:         return '/uploaded/'.$fpath.'/'.$fname;
                   3024:     } else {
1.638     albertel 3025:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3026: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3027:         return '/adm/notfound.html';
                   3028:     }
                   3029: }
                   3030: 
1.531     albertel 3031: sub clean_filename {
1.831     albertel 3032:     my ($fname,$args)=@_;
1.315     www      3033: # Replace Windows backslashes by forward slashes
1.257     www      3034:     $fname=~s/\\/\//g;
1.831     albertel 3035:     if (!$args->{'keep_path'}) {
                   3036:         # Get rid of everything but the actual filename
                   3037: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3038:     }
1.315     www      3039: # Replace spaces by underscores
                   3040:     $fname=~s/\s+/\_/g;
                   3041: # Replace all other weird characters by nothing
1.831     albertel 3042:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3043: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3044: # numbers
                   3045:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3046:     return $fname;
                   3047: }
1.1051    raeburn  3048: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3049: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3050: # image with the same aspect ratio as the original, but with dimensions which do 
                   3051: # not exceed $resizewidth and $resizeheight.
                   3052:  
1.984     neumanie 3053: sub resizeImage {
1.1051    raeburn  3054:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3055:     my $ima = Image::Magick->new;
                   3056:     my $resized;
                   3057:     if (-e $img_path) {
                   3058:         $ima->Read($img_path);
                   3059:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3060:             my $width = $ima->Get('width');
                   3061:             my $height = $ima->Get('height');
                   3062:             if ($width > $resizewidth) {
                   3063: 	        my $factor = $width/$resizewidth;
                   3064:                 my $newheight = $height/$factor;
                   3065:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3066:                 $resized = 1;
                   3067:             }
                   3068:         }
                   3069:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3070:             my $width = $ima->Get('width');
                   3071:             my $height = $ima->Get('height');
                   3072:             if ($height > $resizeheight) {
                   3073:                 my $factor = $height/$resizeheight;
                   3074:                 my $newwidth = $width/$factor;
                   3075:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3076:                 $resized = 1;
                   3077:             }
                   3078:         }
                   3079:         if ($resized) {
                   3080:             $ima->Write($img_path);
                   3081:         }
                   3082:     }
                   3083:     return;
1.977     amueller 3084: }
                   3085: 
1.608     albertel 3086: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3087: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3088: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3089: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3090: #                                    canceloverwrite, or ''. 
                   3091: #                   if 'coursedoc': upload to the current course
                   3092: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3093: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3094: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3095: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3096: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3097: #        $allfiles - reference to hash for embedded objects
                   3098: #        $codebase - reference to hash for codebase of java objects
                   3099: #        $desuname - username for permanent storage of uploaded file
                   3100: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3101: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3102: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3103: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3104: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3105: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3106: #                    from File::MMagic.
1.858     raeburn  3107: # 
1.686     albertel 3108: # output: url of file in userspace, or error: <message> 
                   3109: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3110: 
1.531     albertel 3111: sub userfileupload {
1.1090    raeburn  3112:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3113:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3114:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3115:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3116:     $fname=&clean_filename($fname);
1.1090    raeburn  3117:     # See if there is anything left
1.257     www      3118:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3119:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3120:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3121:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3122:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3123:         my $now = time;
1.1090    raeburn  3124:         my $filepath;
1.1095    raeburn  3125:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3126:              $filepath = 'tmp/helprequests/'.$now;
                   3127:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3128:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3129:                          '_'.$env{'user.domain'}.'/pending';
                   3130:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3131:             my ($docuname,$docudom);
                   3132:             if ($destudom) {
                   3133:                 $docudom = $destudom;
                   3134:             } else {
                   3135:                 $docudom = $env{'user.domain'};
                   3136:             }
                   3137:             if ($destuname) {
                   3138:                 $docuname = $destuname;
                   3139:             } else {
                   3140:                 $docuname = $env{'user.name'};
                   3141:             }
                   3142:             if (exists($env{'form.group'})) {
                   3143:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3144:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3145:             }
                   3146:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3147:             if ($context eq 'canceloverwrite') {
                   3148:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3149:                 if (-e  $tempfile) {
                   3150:                     my @info = stat($tempfile);
                   3151:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3152:                         unlink($tempfile);
                   3153:                     }
                   3154:                 }
                   3155:                 return;
1.523     raeburn  3156:             }
                   3157:         }
1.1090    raeburn  3158:         # Create the directory if not present
1.741     raeburn  3159:         my @parts=split(/\//,$filepath);
                   3160:         my $fullpath = $perlvar{'lonDaemons'};
                   3161:         for (my $i=0;$i<@parts;$i++) {
                   3162:             $fullpath .= '/'.$parts[$i];
                   3163:             if ((-e $fullpath)!=1) {
                   3164:                 mkdir($fullpath,0777);
                   3165:             }
                   3166:         }
                   3167:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   3168:         print $fh $env{'form.'.$formname};
                   3169:         close($fh);
1.1090    raeburn  3170:         if ($context eq 'existingfile') {
                   3171:             my @info = stat($fullpath.'/'.$fname);
                   3172:             return ($fullpath.'/'.$fname,$info[9]);
                   3173:         } else {
                   3174:             return $fullpath.'/'.$fname;
                   3175:         }
1.523     raeburn  3176:     }
1.995     raeburn  3177:     if ($subdir eq 'scantron') {
                   3178:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3179:     } else {
1.995     raeburn  3180:         $fname="$subdir/$fname";
                   3181:     }
1.1090    raeburn  3182:     if ($context eq 'coursedoc') {
1.638     albertel 3183: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3184: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3185:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3186:             return &finishuserfileupload($docuname,$docudom,
                   3187: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3188: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3189:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3190:         } else {
1.1172.2.21  raeburn  3191:             if ($env{'form.folder'}) {
                   3192:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3193:             }
1.638     albertel 3194:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3195: 				       $fname,$formname,$parser,
1.1095    raeburn  3196: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3197:         }
1.719     banghart 3198:     } elsif (defined($destuname)) {
                   3199:         my $docuname=$destuname;
                   3200:         my $docudom=$destudom;
1.860     raeburn  3201: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3202: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3203:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3204:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3205:     } else {
1.638     albertel 3206:         my $docuname=$env{'user.name'};
                   3207:         my $docudom=$env{'user.domain'};
1.1172.2.23  raeburn  3208:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3209:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3210:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3211:         }
1.860     raeburn  3212: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3213: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3214:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3215:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3216:     }
1.271     www      3217: }
                   3218: 
                   3219: sub finishuserfileupload {
1.860     raeburn  3220:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3221:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3222:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3223:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3224:   
1.860     raeburn  3225:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3226:     $file=$fname;
                   3227:     if ($fname=~m|/|) {
                   3228:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3229: 	$path.=$fnamepath.'/';
                   3230:     }
1.259     www      3231:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3232:     my $count;
                   3233:     for ($count=4;$count<=$#parts;$count++) {
                   3234:         $filepath.="/$parts[$count]";
                   3235:         if ((-e $filepath)!=1) {
                   3236: 	    mkdir($filepath,0777);
                   3237:         }
                   3238:     }
1.984     neumanie 3239: 
1.258     www      3240: # Save the file
                   3241:     {
1.701     albertel 3242: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   3243: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3244: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3245: 	    return '/adm/notfound.html';
                   3246: 	}
1.1090    raeburn  3247:         if ($context eq 'overwrite') {
1.1117    foxr     3248:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3249:             my $target = $filepath.'/'.$file;
                   3250:             if (-e $source) {
                   3251:                 my @info = stat($source);
                   3252:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3253:                     unless (&File::Copy::move($source,$target)) {
                   3254:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3255:                         return "Moving from $source failed";
                   3256:                     }
                   3257:                 } else {
                   3258:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3259:                 }
                   3260:             } else {
                   3261:                 return "Temporary file: $source missing";
                   3262:             }
                   3263:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3264: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3265: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3266: 	    return '/adm/notfound.html';
                   3267: 	}
1.570     albertel 3268: 	close(FH);
1.1051    raeburn  3269:         if ($resizewidth && $resizeheight) {
                   3270:             my $mm = new File::MMagic;
                   3271:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3272:             if ($mime_type =~ m{^image/}) {
                   3273: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3274:             }  
1.977     amueller 3275: 	}
1.258     www      3276:     }
1.1152    raeburn  3277:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3278:         if (ref($mimetype)) {
                   3279:             if ($$mimetype eq '') {
                   3280:                 my $mm = new File::MMagic;
                   3281:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3282:                 $$mimetype = $type;
                   3283:             }
                   3284:         }
                   3285:     }
1.637     raeburn  3286:     if ($parser eq 'parse') {
1.1152    raeburn  3287:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3288:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3289:                                                        $allfiles,$codebase);
                   3290:             unless ($parse_result eq 'ok') {
                   3291:                 &logthis('Failed to parse '.$filepath.$file.
                   3292: 	   	         ' for embedded media: '.$parse_result); 
                   3293:             }
1.637     raeburn  3294:         }
                   3295:     }
1.860     raeburn  3296:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3297:         my $input = $filepath.'/'.$file;
                   3298:         my $output = $filepath.'/'.'tn-'.$file;
                   3299:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3300:         system("convert -sample $thumbsize $input $output");
                   3301:         if (-e $filepath.'/'.'tn-'.$file) {
                   3302:             $fetchthumb  = 1; 
                   3303:         }
                   3304:     }
1.858     raeburn  3305:  
1.259     www      3306: # Notify homeserver to grep it
                   3307: #
1.984     neumanie 3308:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3309:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3310:     if ($fetchresult eq 'ok') {
1.860     raeburn  3311:         if ($fetchthumb) {
                   3312:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3313:             if ($thumbresult ne 'ok') {
                   3314:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3315:                          $docuhome.': '.$thumbresult);
                   3316:             }
                   3317:         }
1.259     www      3318: #
1.258     www      3319: # Return the URL to it
1.494     albertel 3320:         return '/uploaded/'.$path.$file;
1.263     www      3321:     } else {
1.494     albertel 3322:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3323: 		 ': '.$fetchresult);
1.263     www      3324:         return '/adm/notfound.html';
1.858     raeburn  3325:     }
1.493     albertel 3326: }
                   3327: 
1.637     raeburn  3328: sub extract_embedded_items {
1.961     raeburn  3329:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3330:     my @state = ();
1.1164    raeburn  3331:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3332:     my %javafiles = (
                   3333:                       codebase => '',
                   3334:                       code => '',
                   3335:                       archive => ''
                   3336:                     );
                   3337:     my %mediafiles = (
                   3338:                       src => '',
                   3339:                       movie => '',
                   3340:                      );
1.648     raeburn  3341:     my $p;
                   3342:     if ($content) {
                   3343:         $p = HTML::LCParser->new($content);
                   3344:     } else {
1.961     raeburn  3345:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3346:     }
1.641     albertel 3347:     while (my $t=$p->get_token()) {
1.640     albertel 3348: 	if ($t->[0] eq 'S') {
                   3349: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3350: 	    push(@state, $tagname);
1.648     raeburn  3351:             if (lc($tagname) eq 'allow') {
                   3352:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3353:             }
1.640     albertel 3354: 	    if (lc($tagname) eq 'img') {
                   3355: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3356: 	    }
1.886     albertel 3357: 	    if (lc($tagname) eq 'a') {
1.1172.2.24! raeburn  3358:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
        !          3359: 		    &add_filetype($allfiles,$attr->{'href'},'href');
        !          3360:                 }
1.886     albertel 3361: 	    }
1.645     raeburn  3362:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3363:                 my $src;
1.645     raeburn  3364:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3365:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3366:                 } else {
1.1164    raeburn  3367:                     if ($attr->{'src'} ne '') {
                   3368:                         $src = $attr->{'src'};
                   3369:                         &add_filetype($allfiles,$src,'src');
                   3370:                     }
                   3371:                 }
                   3372:                 my $text = $p->get_trimmed_text();
                   3373:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3374:                     my @swfargs = split(/,/,$1);
                   3375:                     foreach my $item (@swfargs) {
                   3376:                         $item =~ s/["']//g;
                   3377:                         $item =~ s/^\s+//;
                   3378:                         $item =~ s/\s+$//;
                   3379:                     }
                   3380:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3381:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3382:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3383:                         } else {
                   3384:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3385:                         }
                   3386:                     }
1.645     raeburn  3387:                 }
                   3388:             }
                   3389:             if (lc($tagname) eq 'link') {
                   3390:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3391:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3392:                 }
                   3393:             }
1.640     albertel 3394: 	    if (lc($tagname) eq 'object' ||
                   3395: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3396: 		foreach my $item (keys(%javafiles)) {
                   3397: 		    $javafiles{$item} = '';
                   3398: 		}
1.1164    raeburn  3399:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3400:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3401:                 }
1.640     albertel 3402: 	    }
                   3403: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3404: 		my $name = lc($attr->{'name'});
                   3405: 		foreach my $item (keys(%javafiles)) {
                   3406: 		    if ($name eq $item) {
                   3407: 			$javafiles{$item} = $attr->{'value'};
                   3408: 			last;
                   3409: 		    }
                   3410: 		}
1.1164    raeburn  3411:                 my $pathfrom;
1.640     albertel 3412: 		foreach my $item (keys(%mediafiles)) {
                   3413: 		    if ($name eq $item) {
1.1164    raeburn  3414:                         $pathfrom = $attr->{'value'};
                   3415:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3416: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3417: 			last;
                   3418: 		    }
                   3419: 		}
1.1164    raeburn  3420:                 if ($name eq 'flashvars') {
                   3421:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3422:                 }
                   3423:                 if ($pathfrom ne '') {
                   3424:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3425:                                          $pathfrom);
                   3426:                 }
1.640     albertel 3427: 	    }
                   3428: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3429: 		foreach my $item (keys(%javafiles)) {
                   3430: 		    if ($attr->{$item}) {
                   3431: 			$javafiles{$item} = $attr->{$item};
                   3432: 			last;
                   3433: 		    }
                   3434: 		}
                   3435: 		foreach my $item (keys(%mediafiles)) {
                   3436: 		    if ($attr->{$item}) {
                   3437: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3438: 			last;
                   3439: 		    }
                   3440: 		}
1.1164    raeburn  3441:                 if (lc($tagname) eq 'embed') {
                   3442:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3443:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3444:                                              $attr->{'src'});
                   3445:                     }
                   3446:                 }
1.640     albertel 3447: 	    }
1.1164    raeburn  3448:             if ($t->[4] =~ m{/>$}) {
                   3449:                 pop(@state);  
                   3450:             }
1.640     albertel 3451: 	} elsif ($t->[0] eq 'E') {
                   3452: 	    my ($tagname) = ($t->[1]);
                   3453: 	    if ($javafiles{'codebase'} ne '') {
                   3454: 		$javafiles{'codebase'} .= '/';
                   3455: 	    }  
                   3456: 	    if (lc($tagname) eq 'applet' ||
                   3457: 		lc($tagname) eq 'object' ||
                   3458: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3459: 		) {
                   3460: 		foreach my $item (keys(%javafiles)) {
                   3461: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3462: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3463: 			&add_filetype($allfiles,$file,$item);
                   3464: 		    }
                   3465: 		}
                   3466: 	    } 
                   3467: 	    pop @state;
                   3468: 	}
                   3469:     }
1.1164    raeburn  3470:     foreach my $id (sort(keys(%flashvars))) {
                   3471:         if ($shockwave{$id} ne '') {
                   3472:             my @pairs = split(/\&/,$flashvars{$id});
                   3473:             foreach my $pair (@pairs) {
                   3474:                 my ($key,$value) = split(/\=/,$pair);
                   3475:                 if ($key eq 'thumb') {
                   3476:                     &add_filetype($allfiles,$value,$key);
                   3477:                 } elsif ($key eq 'content') {
                   3478:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3479:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3480:                     if ($ext ne '') {
                   3481:                         &add_filetype($allfiles,$path.$value,$ext);
                   3482:                     }
                   3483:                 }
                   3484:             }
                   3485:         }
                   3486:     }
1.637     raeburn  3487:     return 'ok';
                   3488: }
                   3489: 
1.639     albertel 3490: sub add_filetype {
                   3491:     my ($allfiles,$file,$type)=@_;
                   3492:     if (exists($allfiles->{$file})) {
                   3493: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3494: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3495: 	}
                   3496:     } else {
                   3497: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3498:     }
                   3499: }
                   3500: 
1.1164    raeburn  3501: sub embedded_dependency {
                   3502:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3503:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3504:         if (($identifier ne '') &&
                   3505:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3506:             ($pathfrom ne '')) {
                   3507:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3508:             foreach my $dep (@{$related->{$identifier}}) {
                   3509:                 &add_filetype($allfiles,$path.$dep,'object');
                   3510:             }
                   3511:         }
                   3512:     }
                   3513:     return;
                   3514: }
                   3515: 
1.493     albertel 3516: sub removeuploadedurl {
1.984     neumanie 3517:     my ($url)=@_;	
                   3518:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3519:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3520: }
                   3521: 
                   3522: sub removeuserfile {
                   3523:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3524:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3525:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3526:     if ($result eq 'ok') {	
1.798     raeburn  3527:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3528:             my $metafile = $fname.'.meta';
                   3529:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3530: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3531:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3532:             my $sqlresult = 
1.823     albertel 3533:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3534:                                         'portfolio_metadata',$group,
                   3535:                                         'delete');
1.798     raeburn  3536:         }
                   3537:     }
                   3538:     return $result;
1.257     www      3539: }
1.15      www      3540: 
1.530     albertel 3541: sub mkdiruserfile {
                   3542:     my ($docuname,$docudom,$dir)=@_;
                   3543:     my $home=&homeserver($docuname,$docudom);
                   3544:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3545: }
                   3546: 
1.531     albertel 3547: sub renameuserfile {
                   3548:     my ($docuname,$docudom,$old,$new)=@_;
                   3549:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3550:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3551:                         &escape("$old").':'.&escape("$new"),$home);
                   3552:     if ($result eq 'ok') {
                   3553:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3554:             my $oldmeta = $old.'.meta';
                   3555:             my $newmeta = $new.'.meta';
                   3556:             my $metaresult = 
                   3557:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3558: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3559:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3560:             my $sqlresult = 
1.823     albertel 3561:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3562:                                         'portfolio_metadata',$group,
                   3563:                                         'delete');
1.798     raeburn  3564:         }
                   3565:     }
                   3566:     return $result;
1.531     albertel 3567: }
                   3568: 
1.14      www      3569: # ------------------------------------------------------------------------- Log
                   3570: 
                   3571: sub log {
                   3572:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3573:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3574: }
                   3575: 
                   3576: # ------------------------------------------------------------------ Course Log
1.352     www      3577: #
                   3578: # This routine flushes several buffers of non-mission-critical nature
                   3579: #
1.157     www      3580: 
                   3581: sub flushcourselogs {
1.352     www      3582:     &logthis('Flushing log buffers');
                   3583: #
                   3584: # course logs
                   3585: # This is a log of all transactions in a course, which can be used
                   3586: # for data mining purposes
                   3587: #
                   3588: # It also collects the courseid database, which lists last transaction
                   3589: # times and course titles for all courseids
                   3590: #
                   3591:     my %courseidbuffer=();
1.921     raeburn  3592:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3593:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3594: 		          &escape($courselogs{$crsid}),
                   3595: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3596: 	    delete $courselogs{$crsid};
                   3597:         } else {
                   3598:             &logthis('Failed to flush log buffer for '.$crsid);
                   3599:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3600:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3601:                         " exceeded maximum size, deleting.</font>");
                   3602:                delete $courselogs{$crsid};
                   3603:             }
1.352     www      3604:         }
1.920     raeburn  3605:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3606:             'description' => $coursedescrbuf{$crsid},
                   3607:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3608:             'type'        => $coursetypebuf{$crsid},
                   3609:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3610:         };
1.191     harris41 3611:     }
1.352     www      3612: #
                   3613: # Write course id database (reverse lookup) to homeserver of courses 
                   3614: # Is used in pickcourse
                   3615: #
1.840     albertel 3616:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3617:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3618:                                     $courseidbuffer{$crs_home},
                   3619:                                     $crs_home,'timeonly');
1.352     www      3620:     }
                   3621: #
                   3622: # File accesses
                   3623: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3624: #
1.449     matthew  3625:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3626:         if ($entry =~ /___count$/) {
                   3627:             my ($dom,$name);
1.807     albertel 3628:             ($dom,$name,undef)=
1.811     albertel 3629: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3630:             if (! defined($dom) || $dom eq '' || 
                   3631:                 ! defined($name) || $name eq '') {
1.620     albertel 3632:                 my $cid = $env{'request.course.id'};
                   3633:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3634:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3635:             }
1.450     matthew  3636:             my $value = $accesshash{$entry};
                   3637:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   3638:             my %temphash=($url => $value);
1.449     matthew  3639:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   3640:             if ($result eq 'ok') {
                   3641:                 delete $accesshash{$entry};
                   3642:             }
                   3643:         } else {
1.811     albertel 3644:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      3645:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  3646:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3647:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3648:                 delete $accesshash{$entry};
                   3649:             }
1.185     www      3650:         }
1.191     harris41 3651:     }
1.352     www      3652: #
                   3653: # Roles
                   3654: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   3655: #
1.800     albertel 3656:     foreach my $entry (keys(%userrolehash)) {
1.351     www      3657:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      3658: 	    split(/\:/,$entry);
                   3659:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      3660:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      3661:                 $rudom,$runame) eq 'ok') {
                   3662: 	    delete $userrolehash{$entry};
                   3663:         }
                   3664:     }
1.662     raeburn  3665: #
                   3666: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   3667: #
                   3668:     my %domrolebuffer = ();
1.1000    raeburn  3669:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 3670:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  3671:         if ($domrolebuffer{$rudom}) {
                   3672:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   3673:                       '='.&escape($domainrolehash{$entry});
                   3674:         } else {
                   3675:             $domrolebuffer{$rudom}.=&escape($entry).
                   3676:                       '='.&escape($domainrolehash{$entry});
                   3677:         }
                   3678:         delete $domainrolehash{$entry};
                   3679:     }
                   3680:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 3681: 	my %servers = &get_servers($dom,'library');
                   3682: 	foreach my $tryserver (keys(%servers)) {
                   3683: 	    unless (&reply('domroleput:'.$dom.':'.
                   3684: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   3685: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   3686: 	    }
1.662     raeburn  3687:         }
                   3688:     }
1.186     www      3689:     $dumpcount++;
1.157     www      3690: }
                   3691: 
                   3692: sub courselog {
                   3693:     my $what=shift;
1.158     www      3694:     $what=time.':'.$what;
1.620     albertel 3695:     unless ($env{'request.course.id'}) { return ''; }
                   3696:     $coursedombuf{$env{'request.course.id'}}=
                   3697:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3698:     $coursenumbuf{$env{'request.course.id'}}=
                   3699:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   3700:     $coursehombuf{$env{'request.course.id'}}=
                   3701:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   3702:     $coursedescrbuf{$env{'request.course.id'}}=
                   3703:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   3704:     $courseinstcodebuf{$env{'request.course.id'}}=
                   3705:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   3706:     $courseownerbuf{$env{'request.course.id'}}=
                   3707:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  3708:     $coursetypebuf{$env{'request.course.id'}}=
                   3709:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 3710:     if (defined $courselogs{$env{'request.course.id'}}) {
                   3711: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      3712:     } else {
1.620     albertel 3713: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      3714:     }
1.620     albertel 3715:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      3716: 	&flushcourselogs();
                   3717:     }
1.158     www      3718: }
                   3719: 
                   3720: sub courseacclog {
                   3721:     my $fnsymb=shift;
1.620     albertel 3722:     unless ($env{'request.course.id'}) { return ''; }
                   3723:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      3724:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      3725:         $what.=':POST';
1.583     matthew  3726:         # FIXME: Probably ought to escape things....
1.800     albertel 3727: 	foreach my $key (keys(%env)) {
                   3728:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  3729:                 my $formitem = $1;
                   3730:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   3731:                     $what.=':'.$formitem.'='.$env{$key};
                   3732:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   3733:                     $what.=':'.$formitem.'='.$env{$key};
                   3734:                 }
1.158     www      3735:             }
1.191     harris41 3736:         }
1.583     matthew  3737:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   3738:         # FIXME: We should not be depending on a form parameter that someone
                   3739:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 3740:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  3741:             $what.= ':POST';
                   3742:             # FIXME: Probably ought to escape things....
                   3743:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   3744:                                  'crsdiscuss') {
1.620     albertel 3745:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  3746:             }
                   3747:         }
1.158     www      3748:     }
                   3749:     &courselog($what);
1.149     www      3750: }
                   3751: 
1.185     www      3752: sub countacc {
                   3753:     my $url=&declutter(shift);
1.458     matthew  3754:     return if (! defined($url) || $url eq '');
1.620     albertel 3755:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      3756: #
                   3757: # Mark that this url was used in this course
                   3758: #
1.620     albertel 3759:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      3760: #
                   3761: # Increase the access count for this resource in this child process
                   3762: #
1.281     www      3763:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  3764:     $accesshash{$key}++;
1.185     www      3765: }
1.349     www      3766: 
1.361     www      3767: sub linklog {
                   3768:     my ($from,$to)=@_;
                   3769:     $from=&declutter($from);
                   3770:     $to=&declutter($to);
                   3771:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   3772:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   3773: }
1.1160    www      3774: 
                   3775: sub statslog {
                   3776:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   3777:     if ($users<2) { return; }
                   3778:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   3779:             'course'       => $env{'request.course.id'},
                   3780:             'sections'     => '"all"',
                   3781:             'num_students' => $users,
                   3782:             'part'         => $part,
                   3783:             'symb'         => $symb,
                   3784:             'mean_tries'   => $av_attempts,
                   3785:             'deg_of_diff'  => $degdiff});
                   3786:     foreach my $key (keys(%dynstore)) {
                   3787:         $accesshash{$key}=$dynstore{$key};
                   3788:     }
                   3789: }
1.361     www      3790:   
1.349     www      3791: sub userrolelog {
                   3792:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 3793:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      3794:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3795:        $userrolehash
                   3796:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      3797:                     =$tend.':'.$tstart;
1.662     raeburn  3798:     }
1.1169    droeschl 3799:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 3800:        $userrolehash
                   3801:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   3802:                     =$tend.':'.$tstart;
                   3803:     }
1.1169    droeschl 3804:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662     raeburn  3805:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3806:        $domainrolehash
                   3807:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3808:                     = $tend.':'.$tstart;
                   3809:     }
1.351     www      3810: }
                   3811: 
1.957     raeburn  3812: sub courserolelog {
                   3813:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  3814:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3815:         my $cdom = $1;
                   3816:         my $cnum = $2;
                   3817:         my $sec = $3;
                   3818:         my $namespace = 'rolelog';
                   3819:         my %storehash = (
                   3820:                            role    => $trole,
                   3821:                            start   => $tstart,
                   3822:                            end     => $tend,
                   3823:                            selfenroll => $selfenroll,
                   3824:                            context    => $context,
                   3825:                         );
                   3826:         if ($trole eq 'gr') {
                   3827:             $namespace = 'groupslog';
                   3828:             $storehash{'group'} = $sec;
                   3829:         } else {
                   3830:             $storehash{'section'} = $sec;
                   3831:         }
                   3832:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   3833:                    $domain,$cnum,$cdom);
                   3834:         if (($trole ne 'st') || ($sec ne '')) {
                   3835:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  3836:         }
                   3837:     }
                   3838:     return;
                   3839: }
                   3840: 
1.1172.2.9  raeburn  3841: sub domainrolelog {
                   3842:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   3843:     if ($area =~ m{^/($match_domain)/$}) {
                   3844:         my $cdom = $1;
                   3845:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   3846:         my $namespace = 'rolelog';
                   3847:         my %storehash = (
                   3848:                            role    => $trole,
                   3849:                            start   => $tstart,
                   3850:                            end     => $tend,
                   3851:                            context => $context,
                   3852:                         );
                   3853:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   3854:                    $domain,$domconfiguser,$cdom);
                   3855:     }
                   3856:     return;
                   3857: 
                   3858: }
                   3859: 
                   3860: sub coauthorrolelog {
                   3861:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   3862:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   3863:         my $audom = $1;
                   3864:         my $auname = $2;
                   3865:         my $namespace = 'rolelog';
                   3866:         my %storehash = (
                   3867:                            role    => $trole,
                   3868:                            start   => $tstart,
                   3869:                            end     => $tend,
                   3870:                            context => $context,
                   3871:                         );
                   3872:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   3873:                    $domain,$auname,$audom);
                   3874:     }
                   3875:     return;
                   3876: }
                   3877: 
1.351     www      3878: sub get_course_adv_roles {
1.948     raeburn  3879:     my ($cid,$codes) = @_;
1.620     albertel 3880:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      3881:     my %coursehash=&coursedescription($cid);
1.988     raeburn  3882:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      3883:     my %nothide=();
1.800     albertel 3884:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  3885:         if ($user !~ /:/) {
                   3886: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   3887:         } else {
                   3888:             $nothide{$user}=1;
                   3889:         }
1.470     www      3890:     }
1.1172.2.23  raeburn  3891:     my @possdoms = ($coursehash{'domain'});
                   3892:     if ($coursehash{'checkforpriv'}) {
                   3893:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   3894:     }
1.351     www      3895:     my %returnhash=();
                   3896:     my %dumphash=
                   3897:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   3898:     my $now=time;
1.997     raeburn  3899:     my %privileged;
1.1000    raeburn  3900:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 3901: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      3902:         if (($tstart) && ($tstart<0)) { next; }
                   3903:         if (($tend) && ($tend<$now)) { next; }
                   3904:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 3905:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 3906: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  3907:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  3908:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 3909: 	if ($role eq 'cr') { next; }
1.948     raeburn  3910:         if ($codes) {
                   3911:             if ($section) { $role .= ':'.$section; }
                   3912:             if ($returnhash{$role}) {
                   3913:                 $returnhash{$role}.=','.$username.':'.$domain;
                   3914:             } else {
                   3915:                 $returnhash{$role}=$username.':'.$domain;
                   3916:             }
1.351     www      3917:         } else {
1.988     raeburn  3918:             my $key=&plaintext($role,$crstype);
1.973     bisitz   3919:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  3920:             if ($returnhash{$key}) {
                   3921: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   3922:             } else {
                   3923:                 $returnhash{$key}=$username.':'.$domain;
                   3924:             }
1.351     www      3925:         }
1.948     raeburn  3926:     }
1.400     www      3927:     return %returnhash;
                   3928: }
                   3929: 
                   3930: sub get_my_roles {
1.937     raeburn  3931:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 3932:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   3933:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  3934:     my (%dumphash,%nothide);
1.1086    raeburn  3935:     if ($context eq 'userroles') {
1.1166    raeburn  3936:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  3937:     } else {
1.1172.2.23  raeburn  3938:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  3939:         if ($hidepriv) {
                   3940:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   3941:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3942:                 if ($user !~ /:/) {
                   3943:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   3944:                 } else {
                   3945:                     $nothide{$user} = 1;
                   3946:                 }
                   3947:             }
                   3948:         }
1.858     raeburn  3949:     }
1.400     www      3950:     my %returnhash=();
                   3951:     my $now=time;
1.999     raeburn  3952:     my %privileged;
1.800     albertel 3953:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  3954:         my ($role,$tend,$tstart);
                   3955:         if ($context eq 'userroles') {
1.1149    raeburn  3956:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  3957: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   3958:         } else {
                   3959:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   3960:         }
1.400     www      3961:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  3962:         my $status = 'active';
1.939     raeburn  3963:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  3964:             $status = 'previous';
                   3965:         } 
                   3966:         if (($tstart) && ($now<$tstart)) {
                   3967:             $status = 'future';
                   3968:         }
                   3969:         if (ref($types) eq 'ARRAY') {
                   3970:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   3971:                 next;
                   3972:             } 
                   3973:         } else {
                   3974:             if ($status ne 'active') {
                   3975:                 next;
                   3976:             }
                   3977:         }
1.867     raeburn  3978:         my ($rolecode,$username,$domain,$section,$area);
                   3979:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  3980:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  3981:             (undef,$domain,$username,$section) = split(/\//,$area);
                   3982:         } else {
                   3983:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   3984:         }
1.832     raeburn  3985:         if (ref($roledoms) eq 'ARRAY') {
                   3986:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   3987:                 next;
                   3988:             }
                   3989:         }
                   3990:         if (ref($roles) eq 'ARRAY') {
                   3991:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  3992:                 if ($role =~ /^cr\//) {
                   3993:                     if (!grep(/^cr$/,@{$roles})) {
                   3994:                         next;
                   3995:                     }
1.1104    raeburn  3996:                 } elsif ($role =~ /^gr\//) {
                   3997:                     if (!grep(/^gr$/,@{$roles})) {
                   3998:                         next;
                   3999:                     }
1.922     raeburn  4000:                 } else {
                   4001:                     next;
                   4002:                 }
1.832     raeburn  4003:             }
1.867     raeburn  4004:         }
1.937     raeburn  4005:         if ($hidepriv) {
1.1172.2.23  raeburn  4006:             my @privroles = ('dc','su');
1.999     raeburn  4007:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  4008:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4009:             } else {
1.1172.2.23  raeburn  4010:                 my $possdoms = [$domain];
                   4011:                 if (ref($roledoms) eq 'ARRAY') {
                   4012:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  4013:                 }
1.1172.2.23  raeburn  4014:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4015:                     if (!$nothide{$username.':'.$domain}) {
                   4016:                         next;
                   4017:                     }
                   4018:                 }
1.937     raeburn  4019:             }
                   4020:         }
1.933     raeburn  4021:         if ($withsec) {
                   4022:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4023:                 $tstart.':'.$tend;
                   4024:         } else {
                   4025:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4026:         }
1.832     raeburn  4027:     }
1.373     www      4028:     return %returnhash;
1.399     www      4029: }
                   4030: 
                   4031: # ----------------------------------------------------- Frontpage Announcements
                   4032: #
                   4033: #
                   4034: 
                   4035: sub postannounce {
                   4036:     my ($server,$text)=@_;
1.844     albertel 4037:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4038:     unless ($text=~/\w/) { $text=''; }
                   4039:     return &reply('setannounce:'.&escape($text),$server);
                   4040: }
                   4041: 
                   4042: sub getannounce {
1.448     albertel 4043: 
                   4044:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4045: 	my $announcement='';
1.800     albertel 4046: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4047: 	close($fh);
1.399     www      4048: 	if ($announcement=~/\w/) { 
                   4049: 	    return 
                   4050:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4051:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4052: 	} else {
                   4053: 	    return '';
                   4054: 	}
                   4055:     } else {
                   4056: 	return '';
                   4057:     }
1.351     www      4058: }
1.353     www      4059: 
                   4060: # ---------------------------------------------------------- Course ID routines
                   4061: # Deal with domain's nohist_courseid.db files
                   4062: #
                   4063: 
                   4064: sub courseidput {
1.921     raeburn  4065:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4066:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4067:     my $outcome;
                   4068:     if ($caller eq 'timeonly') {
                   4069:         my $cids = '';
                   4070:         foreach my $item (keys(%$storehash)) {
                   4071:             $cids.=&escape($item).'&';
                   4072:         }
                   4073:         $cids=~s/\&$//;
                   4074:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4075:                           $coursehome);       
                   4076:     } else {
                   4077:         my $items = '';
                   4078:         foreach my $item (keys(%$storehash)) {
                   4079:             $items.= &escape($item).'='.
                   4080:                      &freeze_escape($$storehash{$item}).'&';
                   4081:         }
                   4082:         $items=~s/\&$//;
                   4083:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4084:                           $coursehome);
1.918     raeburn  4085:     }
                   4086:     if ($outcome eq 'unknown_cmd') {
                   4087:         my $what;
                   4088:         foreach my $cid (keys(%$storehash)) {
                   4089:             $what .= &escape($cid).'=';
1.921     raeburn  4090:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4091:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4092:             }
                   4093:             $what =~ s/\:$/&/;
                   4094:         }
                   4095:         $what =~ s/\&$//;  
                   4096:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4097:     } else {
                   4098:         return $outcome;
                   4099:     }
1.353     www      4100: }
                   4101: 
                   4102: sub courseiddump {
1.921     raeburn  4103:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4104:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4105:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071    raeburn  4106:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  4107:     my $as_hash = 1;
                   4108:     my %returnhash;
                   4109:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4110:     my %libserv = &all_library();
                   4111:     foreach my $tryserver (keys(%libserv)) {
                   4112:         if ( (  $hostidflag == 1 
                   4113: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4114: 	     || (!defined($hostidflag)) ) {
                   4115: 
1.918     raeburn  4116: 	    if (($domfilter eq '') ||
                   4117: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  4118:                 my $rep;
                   4119:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   4120:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   4121:                         join(":", (&host_domain($tryserver), $sincefilter,
                   4122:                                 &escape($descfilter), &escape($instcodefilter),
                   4123:                                 &escape($ownerfilter), &escape($coursefilter),
                   4124:                                 &escape($typefilter), &escape($regexp_ok),
                   4125:                                 $as_hash, &escape($selfenrollonly),
                   4126:                                 &escape($catfilter), $showhidden, $caller,
                   4127:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   4128:                                 &escape($createdbefore), &escape($createdafter),
                   4129:                                 &escape($creationcontext), $domcloner)));
                   4130:                 } else {
                   4131:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4132:                              $sincefilter.':'.&escape($descfilter).':'.
                   4133:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   4134:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   4135:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   4136:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   4137:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   4138:                              &escape($cc_clone).':'.$cloneonly.':'.
                   4139:                              &escape($createdbefore).':'.&escape($createdafter).':'.
                   4140:                              &escape($creationcontext).':'.$domcloner,
                   4141:                              $tryserver);
                   4142:                 }
                   4143: 
1.918     raeburn  4144:                 my @pairs=split(/\&/,$rep);
                   4145:                 foreach my $item (@pairs) {
                   4146:                     my ($key,$value)=split(/\=/,$item,2);
                   4147:                     $key = &unescape($key);
                   4148:                     next if ($key =~ /^error: 2 /);
                   4149:                     my $result = &thaw_unescape($value);
                   4150:                     if (ref($result) eq 'HASH') {
                   4151:                         $returnhash{$key}=$result;
                   4152:                     } else {
1.921     raeburn  4153:                         my @responses = split(/:/,$value);
                   4154:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4155:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4156:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4157:                         }
1.1008    raeburn  4158:                     }
1.353     www      4159:                 }
                   4160:             }
                   4161:         }
                   4162:     }
                   4163:     return %returnhash;
                   4164: }
                   4165: 
1.1055    raeburn  4166: sub courselastaccess {
                   4167:     my ($cdom,$cnum,$hostidref) = @_;
                   4168:     my %returnhash;
                   4169:     if ($cdom && $cnum) {
                   4170:         my $chome = &homeserver($cnum,$cdom);
                   4171:         if ($chome ne 'no_host') {
                   4172:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4173:             &extract_lastaccess(\%returnhash,$rep);
                   4174:         }
                   4175:     } else {
                   4176:         if (!$cdom) { $cdom=''; }
                   4177:         my %libserv = &all_library();
                   4178:         foreach my $tryserver (keys(%libserv)) {
                   4179:             if (ref($hostidref) eq 'ARRAY') {
                   4180:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4181:             } 
                   4182:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4183:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4184:                 &extract_lastaccess(\%returnhash,$rep);
                   4185:             }
                   4186:         }
                   4187:     }
                   4188:     return %returnhash;
                   4189: }
                   4190: 
                   4191: sub extract_lastaccess {
                   4192:     my ($returnhash,$rep) = @_;
                   4193:     if (ref($returnhash) eq 'HASH') {
                   4194:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4195:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4196:                  $rep eq '') {
                   4197:             my @pairs=split(/\&/,$rep);
                   4198:             foreach my $item (@pairs) {
                   4199:                 my ($key,$value)=split(/\=/,$item,2);
                   4200:                 $key = &unescape($key);
                   4201:                 next if ($key =~ /^error: 2 /);
                   4202:                 $returnhash->{$key} = &thaw_unescape($value);
                   4203:             }
                   4204:         }
                   4205:     }
                   4206:     return;
                   4207: }
                   4208: 
1.658     raeburn  4209: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4210: 
                   4211: sub dcmailput {
1.685     raeburn  4212:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4213:     my $status = &Apache::lonnet::critical(
1.740     www      4214:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4215:        &escape($message),$server);
1.662     raeburn  4216:     return $status;
                   4217: }
                   4218: 
1.658     raeburn  4219: sub dcmaildump {
                   4220:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4221:     my %returnhash=();
1.846     albertel 4222: 
                   4223:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4224:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4225:                                                          &escape($enddate).':';
                   4226: 	my @esc_senders=map { &escape($_)} @$senders;
                   4227: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4228: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4229:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4230:             if (($key) && ($value)) {
                   4231:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4232:             }
                   4233:         }
                   4234:     }
                   4235:     return %returnhash;
                   4236: }
1.662     raeburn  4237: # ---------------------------------------------------------- Domain roles
                   4238: 
                   4239: sub get_domain_roles {
                   4240:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4241:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4242:         $startdate = '.';
                   4243:     }
1.1018    raeburn  4244:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4245:         $enddate = '.';
                   4246:     }
1.922     raeburn  4247:     my $rolelist;
                   4248:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  4249:         $rolelist = join('&',@{$roles});
1.922     raeburn  4250:     }
1.662     raeburn  4251:     my %personnel = ();
1.841     albertel 4252: 
                   4253:     my %servers = &get_servers($dom,'library');
                   4254:     foreach my $tryserver (keys(%servers)) {
                   4255: 	%{$personnel{$tryserver}}=();
                   4256: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4257: 					    &escape($startdate).':'.
                   4258: 					    &escape($enddate).':'.
                   4259: 					    &escape($rolelist), $tryserver))) {
                   4260: 	    my ($key,$value) = split(/\=/,$line,2);
                   4261: 	    if (($key) && ($value)) {
                   4262: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4263: 	    }
                   4264: 	}
1.662     raeburn  4265:     }
                   4266:     return %personnel;
                   4267: }
1.658     raeburn  4268: 
1.1057    www      4269: # ----------------------------------------------------------- Interval timing 
1.149     www      4270: 
1.1153    www      4271: {
                   4272: # Caches needed for speedup of navmaps
                   4273: # We don't want to cache this for very long at all (5 seconds at most)
                   4274: # 
                   4275: # The user for whom we cache
                   4276: my $cachedkey='';
                   4277: # The cached times for this user
                   4278: my %cachedtimes=();
                   4279: # When this was last done
                   4280: my $cachedtime=();
                   4281: 
                   4282: sub load_all_first_access {
1.1154    raeburn  4283:     my ($uname,$udom)=@_;
1.1156    www      4284:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2  raeburn  4285:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  4286:         return;
                   4287:     }
                   4288:     $cachedtime=time;
                   4289:     $cachedkey=$uname.':'.$udom;
                   4290:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4291: }
                   4292: 
1.504     albertel 4293: sub get_first_access {
1.1162    raeburn  4294:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 4295:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4296:     if ($argsymb) { $symb=$argsymb; }
                   4297:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4298:     if ($argmap) { $map = $argmap; }
1.926     albertel 4299:     if ($type eq 'course') {
                   4300: 	$res='course';
                   4301:     } elsif ($type eq 'map') {
1.588     albertel 4302: 	$res=&symbread($map);
                   4303:     } else {
                   4304: 	$res=$symb;
                   4305:     }
1.1153    www      4306:     &load_all_first_access($uname,$udom);
                   4307:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4308: }
                   4309: 
                   4310: sub set_first_access {
1.1162    raeburn  4311:     my ($type,$interval)=@_;
1.790     albertel 4312:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4313:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4314:     if ($type eq 'course') {
                   4315: 	$res='course';
                   4316:     } elsif ($type eq 'map') {
1.588     albertel 4317: 	$res=&symbread($map);
                   4318:     } else {
                   4319: 	$res=$symb;
                   4320:     }
1.1153    www      4321:     $cachedkey='';
1.1162    raeburn  4322:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4323:     if (!$firstaccess) {
1.1162    raeburn  4324:         my $start = time;
                   4325: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4326:                           $udom,$uname);
                   4327:         if ($putres eq 'ok') {
                   4328:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4329:                  $udom,$uname); 
                   4330:             &appenv(
                   4331:                      {
                   4332:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4333:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4334:                      }
                   4335:                   );
                   4336:         }
                   4337:         return $putres;
1.505     albertel 4338:     }
                   4339:     return 'already_set';
1.504     albertel 4340: }
1.1153    www      4341: }
1.110     www      4342: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4343: 
                   4344: sub expirespread {
                   4345:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4346:     my $cid=$env{'request.course.id'}; 
1.110     www      4347:     if ($cid) {
                   4348:        my $now=time;
                   4349:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4350:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4351:                             $env{'course.'.$cid.'.num'}.
1.110     www      4352: 	        	    ':nohist_expirationdates:'.
                   4353:                             &escape($key).'='.$now,
1.620     albertel 4354:                             $env{'course.'.$cid.'.home'})
1.110     www      4355:     }
                   4356:     return 'ok';
1.14      www      4357: }
                   4358: 
1.109     www      4359: # ----------------------------------------------------- Devalidate Spreadsheets
                   4360: 
                   4361: sub devalidate {
1.325     www      4362:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4363:     my $cid=$env{'request.course.id'}; 
1.109     www      4364:     if ($cid) {
1.391     matthew  4365:         # delete the stored spreadsheets for
                   4366:         # - the student level sheet of this user in course's homespace
                   4367:         # - the assessment level sheet for this resource 
                   4368:         #   for this user in user's homespace
1.553     albertel 4369: 	# - current conditional state info
1.325     www      4370: 	my $key=$uname.':'.$udom.':';
1.109     www      4371:         my $status=
1.299     matthew  4372: 	    &del('nohist_calculatedsheets',
1.391     matthew  4373: 		 [$key.'studentcalc:'],
1.620     albertel 4374: 		 $env{'course.'.$cid.'.domain'},
                   4375: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4376: 		.' '.
                   4377: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4378: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4379:         unless ($status eq 'ok ok') {
                   4380:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4381:                     $uname.' at '.$udom.' for '.
1.109     www      4382: 		    $symb.': '.$status);
1.133     albertel 4383:         }
1.553     albertel 4384: 	&delenv('user.state.'.$cid);
1.109     www      4385:     }
                   4386: }
                   4387: 
1.265     albertel 4388: sub get_scalar {
                   4389:     my ($string,$end) = @_;
                   4390:     my $value;
                   4391:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4392: 	$value = $1;
                   4393:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4394: 	$value = $1;
                   4395:     }
                   4396:     return &unescape($value);
                   4397: }
                   4398: 
                   4399: sub array2str {
                   4400:   my (@array) = @_;
                   4401:   my $result=&arrayref2str(\@array);
                   4402:   $result=~s/^__ARRAY_REF__//;
                   4403:   $result=~s/__END_ARRAY_REF__$//;
                   4404:   return $result;
                   4405: }
                   4406: 
1.204     albertel 4407: sub arrayref2str {
                   4408:   my ($arrayref) = @_;
1.265     albertel 4409:   my $result='__ARRAY_REF__';
1.204     albertel 4410:   foreach my $elem (@$arrayref) {
1.265     albertel 4411:     if(ref($elem) eq 'ARRAY') {
                   4412:       $result.=&arrayref2str($elem).'&';
                   4413:     } elsif(ref($elem) eq 'HASH') {
                   4414:       $result.=&hashref2str($elem).'&';
                   4415:     } elsif(ref($elem)) {
                   4416:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4417:     } else {
                   4418:       $result.=&escape($elem).'&';
                   4419:     }
                   4420:   }
                   4421:   $result=~s/\&$//;
1.265     albertel 4422:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4423:   return $result;
                   4424: }
                   4425: 
1.168     albertel 4426: sub hash2str {
1.204     albertel 4427:   my (%hash) = @_;
                   4428:   my $result=&hashref2str(\%hash);
1.265     albertel 4429:   $result=~s/^__HASH_REF__//;
                   4430:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4431:   return $result;
                   4432: }
                   4433: 
                   4434: sub hashref2str {
                   4435:   my ($hashref)=@_;
1.265     albertel 4436:   my $result='__HASH_REF__';
1.800     albertel 4437:   foreach my $key (sort(keys(%$hashref))) {
                   4438:     if (ref($key) eq 'ARRAY') {
                   4439:       $result.=&arrayref2str($key).'=';
                   4440:     } elsif (ref($key) eq 'HASH') {
                   4441:       $result.=&hashref2str($key).'=';
                   4442:     } elsif (ref($key)) {
1.265     albertel 4443:       $result.='=';
1.800     albertel 4444:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 4445:     } else {
1.1132    raeburn  4446: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 4447:     }
                   4448: 
1.800     albertel 4449:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   4450:       $result.=&arrayref2str($hashref->{$key}).'&';
                   4451:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   4452:       $result.=&hashref2str($hashref->{$key}).'&';
                   4453:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4454:        $result.='&';
1.800     albertel 4455:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4456:     } else {
1.800     albertel 4457:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4458:     }
                   4459:   }
1.168     albertel 4460:   $result=~s/\&$//;
1.265     albertel 4461:   $result .= '__END_HASH_REF__';
1.168     albertel 4462:   return $result;
                   4463: }
                   4464: 
                   4465: sub str2hash {
1.265     albertel 4466:     my ($string)=@_;
                   4467:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4468:     return %$hash;
                   4469: }
                   4470: 
                   4471: sub str2hashref {
1.168     albertel 4472:   my ($string) = @_;
1.265     albertel 4473: 
                   4474:   my %hash;
                   4475: 
                   4476:   if($string !~ /^__HASH_REF__/) {
                   4477:       if (! ($string eq '' || !defined($string))) {
                   4478: 	  $hash{'error'}='Not hash reference';
                   4479:       }
                   4480:       return (\%hash, $string);
                   4481:   }
                   4482: 
                   4483:   $string =~ s/^__HASH_REF__//;
                   4484: 
                   4485:   while($string !~ /^__END_HASH_REF__/) {
                   4486:       #key
                   4487:       my $key='';
                   4488:       if($string =~ /^__HASH_REF__/) {
                   4489:           ($key, $string)=&str2hashref($string);
                   4490:           if(defined($key->{'error'})) {
                   4491:               $hash{'error'}='Bad data';
                   4492:               return (\%hash, $string);
                   4493:           }
                   4494:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4495:           ($key, $string)=&str2arrayref($string);
                   4496:           if($key->[0] eq 'Array reference error') {
                   4497:               $hash{'error'}='Bad data';
                   4498:               return (\%hash, $string);
                   4499:           }
                   4500:       } else {
                   4501:           $string =~ s/^(.*?)=//;
1.267     albertel 4502: 	  $key=&unescape($1);
1.265     albertel 4503:       }
                   4504:       $string =~ s/^=//;
                   4505: 
                   4506:       #value
                   4507:       my $value='';
                   4508:       if($string =~ /^__HASH_REF__/) {
                   4509:           ($value, $string)=&str2hashref($string);
                   4510:           if(defined($value->{'error'})) {
                   4511:               $hash{'error'}='Bad data';
                   4512:               return (\%hash, $string);
                   4513:           }
                   4514:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4515:           ($value, $string)=&str2arrayref($string);
                   4516:           if($value->[0] eq 'Array reference error') {
                   4517:               $hash{'error'}='Bad data';
                   4518:               return (\%hash, $string);
                   4519:           }
                   4520:       } else {
                   4521: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4522:       }
                   4523:       $string =~ s/^&//;
                   4524: 
                   4525:       $hash{$key}=$value;
1.204     albertel 4526:   }
1.265     albertel 4527: 
                   4528:   $string =~ s/^__END_HASH_REF__//;
                   4529: 
                   4530:   return (\%hash, $string);
1.204     albertel 4531: }
                   4532: 
                   4533: sub str2array {
1.265     albertel 4534:     my ($string)=@_;
                   4535:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4536:     return @$array;
                   4537: }
                   4538: 
                   4539: sub str2arrayref {
1.204     albertel 4540:   my ($string) = @_;
1.265     albertel 4541:   my @array;
                   4542: 
                   4543:   if($string !~ /^__ARRAY_REF__/) {
                   4544:       if (! ($string eq '' || !defined($string))) {
                   4545: 	  $array[0]='Array reference error';
                   4546:       }
                   4547:       return (\@array, $string);
                   4548:   }
                   4549: 
                   4550:   $string =~ s/^__ARRAY_REF__//;
                   4551: 
                   4552:   while($string !~ /^__END_ARRAY_REF__/) {
                   4553:       my $value='';
                   4554:       if($string =~ /^__HASH_REF__/) {
                   4555:           ($value, $string)=&str2hashref($string);
                   4556:           if(defined($value->{'error'})) {
                   4557:               $array[0] ='Array reference error';
                   4558:               return (\@array, $string);
                   4559:           }
                   4560:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4561:           ($value, $string)=&str2arrayref($string);
                   4562:           if($value->[0] eq 'Array reference error') {
                   4563:               $array[0] ='Array reference error';
                   4564:               return (\@array, $string);
                   4565:           }
                   4566:       } else {
                   4567: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   4568:       }
                   4569:       $string =~ s/^&//;
                   4570: 
                   4571:       push(@array, $value);
1.191     harris41 4572:   }
1.265     albertel 4573: 
                   4574:   $string =~ s/^__END_ARRAY_REF__//;
                   4575: 
                   4576:   return (\@array, $string);
1.168     albertel 4577: }
                   4578: 
1.167     albertel 4579: # -------------------------------------------------------------------Temp Store
                   4580: 
1.168     albertel 4581: sub tmpreset {
                   4582:   my ($symb,$namespace,$domain,$stuname) = @_;
                   4583:   if (!$symb) {
                   4584:     $symb=&symbread();
1.620     albertel 4585:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4586:   }
                   4587:   $symb=escape($symb);
                   4588: 
1.620     albertel 4589:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 4590:   $namespace=~s/\//\_/g;
                   4591:   $namespace=~s/\W//g;
                   4592: 
1.620     albertel 4593:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4594:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4595:   if ($domain eq 'public' && $stuname eq 'public') {
                   4596:       $stuname=$ENV{'REMOTE_ADDR'};
                   4597:   }
1.1117    foxr     4598:   my $path=LONCAPA::tempdir();
1.168     albertel 4599:   my %hash;
                   4600:   if (tie(%hash,'GDBM_File',
                   4601: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4602: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  4603:     foreach my $key (keys(%hash)) {
1.180     albertel 4604:       if ($key=~ /:$symb/) {
1.168     albertel 4605: 	delete($hash{$key});
                   4606:       }
                   4607:     }
                   4608:   }
                   4609: }
                   4610: 
1.167     albertel 4611: sub tmpstore {
1.168     albertel 4612:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4613: 
                   4614:   if (!$symb) {
                   4615:     $symb=&symbread();
1.620     albertel 4616:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4617:   }
                   4618:   $symb=escape($symb);
                   4619: 
                   4620:   if (!$namespace) {
                   4621:     # I don't think we would ever want to store this for a course.
                   4622:     # it seems this will only be used if we don't have a course.
1.620     albertel 4623:     #$namespace=$env{'request.course.id'};
1.168     albertel 4624:     #if (!$namespace) {
1.620     albertel 4625:       $namespace=$env{'request.state'};
1.168     albertel 4626:     #}
                   4627:   }
                   4628:   $namespace=~s/\//\_/g;
                   4629:   $namespace=~s/\W//g;
1.620     albertel 4630:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4631:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4632:   if ($domain eq 'public' && $stuname eq 'public') {
                   4633:       $stuname=$ENV{'REMOTE_ADDR'};
                   4634:   }
1.168     albertel 4635:   my $now=time;
                   4636:   my %hash;
1.1117    foxr     4637:   my $path=LONCAPA::tempdir();
1.168     albertel 4638:   if (tie(%hash,'GDBM_File',
                   4639: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4640: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 4641:     $hash{"version:$symb"}++;
                   4642:     my $version=$hash{"version:$symb"};
                   4643:     my $allkeys=''; 
                   4644:     foreach my $key (keys(%$storehash)) {
                   4645:       $allkeys.=$key.':';
1.591     albertel 4646:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 4647:     }
                   4648:     $hash{"$version:$symb:timestamp"}=$now;
                   4649:     $allkeys.='timestamp';
                   4650:     $hash{"$version:keys:$symb"}=$allkeys;
                   4651:     if (untie(%hash)) {
                   4652:       return 'ok';
                   4653:     } else {
                   4654:       return "error:$!";
                   4655:     }
                   4656:   } else {
                   4657:     return "error:$!";
                   4658:   }
                   4659: }
1.167     albertel 4660: 
1.168     albertel 4661: # -----------------------------------------------------------------Temp Restore
1.167     albertel 4662: 
1.168     albertel 4663: sub tmprestore {
                   4664:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 4665: 
1.168     albertel 4666:   if (!$symb) {
                   4667:     $symb=&symbread();
1.620     albertel 4668:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4669:   }
                   4670:   $symb=escape($symb);
                   4671: 
1.620     albertel 4672:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 4673: 
1.620     albertel 4674:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4675:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4676:   if ($domain eq 'public' && $stuname eq 'public') {
                   4677:       $stuname=$ENV{'REMOTE_ADDR'};
                   4678:   }
1.168     albertel 4679:   my %returnhash;
                   4680:   $namespace=~s/\//\_/g;
                   4681:   $namespace=~s/\W//g;
                   4682:   my %hash;
1.1117    foxr     4683:   my $path=LONCAPA::tempdir();
1.168     albertel 4684:   if (tie(%hash,'GDBM_File',
                   4685: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4686: 	  &GDBM_READER(),0640)) {
1.168     albertel 4687:     my $version=$hash{"version:$symb"};
                   4688:     $returnhash{'version'}=$version;
                   4689:     my $scope;
                   4690:     for ($scope=1;$scope<=$version;$scope++) {
                   4691:       my $vkeys=$hash{"$scope:keys:$symb"};
                   4692:       my @keys=split(/:/,$vkeys);
                   4693:       my $key;
                   4694:       $returnhash{"$scope:keys"}=$vkeys;
                   4695:       foreach $key (@keys) {
1.591     albertel 4696: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   4697: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 4698:       }
                   4699:     }
1.168     albertel 4700:     if (!(untie(%hash))) {
                   4701:       return "error:$!";
                   4702:     }
                   4703:   } else {
                   4704:     return "error:$!";
                   4705:   }
                   4706:   return %returnhash;
1.167     albertel 4707: }
                   4708: 
1.9       www      4709: # ----------------------------------------------------------------------- Store
                   4710: 
                   4711: sub store {
1.124     www      4712:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4713:     my $home='';
                   4714: 
1.168     albertel 4715:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4716: 
1.213     www      4717:     $symb=&symbclean($symb);
1.122     albertel 4718:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4719: 
1.620     albertel 4720:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4721:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4722: 
                   4723:     &devalidate($symb,$stuname,$domain);
1.109     www      4724: 
                   4725:     $symb=escape($symb);
1.187     www      4726:     if (!$namespace) { 
1.620     albertel 4727:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4728:           return ''; 
                   4729:        } 
                   4730:     }
1.620     albertel 4731:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4732: 
                   4733:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4734:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   4735: 
1.12      www      4736:     my $namevalue='';
1.800     albertel 4737:     foreach my $key (keys(%$storehash)) {
                   4738:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4739:     }
1.12      www      4740:     $namevalue=~s/\&$//;
1.187     www      4741:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      4742:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      4743: }
                   4744: 
1.47      www      4745: # -------------------------------------------------------------- Critical Store
                   4746: 
                   4747: sub cstore {
1.124     www      4748:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4749:     my $home='';
                   4750: 
1.168     albertel 4751:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4752: 
1.213     www      4753:     $symb=&symbclean($symb);
1.122     albertel 4754:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4755: 
1.620     albertel 4756:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4757:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4758: 
                   4759:     &devalidate($symb,$stuname,$domain);
1.109     www      4760: 
                   4761:     $symb=escape($symb);
1.187     www      4762:     if (!$namespace) { 
1.620     albertel 4763:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4764:           return ''; 
                   4765:        } 
                   4766:     }
1.620     albertel 4767:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4768: 
                   4769:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4770:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 4771: 
1.47      www      4772:     my $namevalue='';
1.800     albertel 4773:     foreach my $key (keys(%$storehash)) {
                   4774:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4775:     }
1.47      www      4776:     $namevalue=~s/\&$//;
1.187     www      4777:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      4778:     return critical
                   4779:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      4780: }
                   4781: 
1.9       www      4782: # --------------------------------------------------------------------- Restore
                   4783: 
                   4784: sub restore {
1.124     www      4785:     my ($symb,$namespace,$domain,$stuname) = @_;
                   4786:     my $home='';
                   4787: 
1.168     albertel 4788:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4789: 
1.122     albertel 4790:     if (!$symb) {
                   4791:       unless ($symb=escape(&symbread())) { return ''; }
                   4792:     } else {
1.213     www      4793:       $symb=&escape(&symbclean($symb));
1.122     albertel 4794:     }
1.188     www      4795:     if (!$namespace) { 
1.620     albertel 4796:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      4797:           return ''; 
                   4798:        } 
                   4799:     }
1.620     albertel 4800:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4801:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   4802:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 4803:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   4804: 
1.12      www      4805:     my %returnhash=();
1.800     albertel 4806:     foreach my $line (split(/\&/,$answer)) {
                   4807: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 4808:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 4809:     }
1.75      www      4810:     my $version;
                   4811:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 4812:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   4813:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 4814:        }
1.75      www      4815:     }
1.13      www      4816:     return %returnhash;
1.34      www      4817: }
                   4818: 
                   4819: # ---------------------------------------------------------- Course Description
1.1118    foxr     4820: #
                   4821: #  
1.34      www      4822: 
                   4823: sub coursedescription {
1.731     albertel 4824:     my ($courseid,$args)=@_;
1.34      www      4825:     $courseid=~s/^\///;
1.49      www      4826:     $courseid=~s/\_/\//g;
1.34      www      4827:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 4828:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 4829:     my $normalid=$cdomain.'_'.$cnum;
                   4830:     # need to always cache even if we get errors otherwise we keep 
                   4831:     # trying and trying and trying to get the course description.
                   4832:     my %envhash=();
                   4833:     my %returnhash=();
1.731     albertel 4834:     
                   4835:     my $expiretime=600;
                   4836:     if ($env{'request.course.id'} eq $normalid) {
                   4837: 	$expiretime=120;
                   4838:     }
                   4839: 
                   4840:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   4841:     if (!$args->{'freshen_cache'}
                   4842: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   4843: 	foreach my $key (keys(%env)) {
                   4844: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   4845: 	    my ($setting) = $1;
                   4846: 	    $returnhash{$setting} = $env{$key};
                   4847: 	}
                   4848: 	return %returnhash;
                   4849:     }
                   4850: 
1.1118    foxr     4851:     # get the data again
                   4852: 
1.731     albertel 4853:     if (!$args->{'one_time'}) {
                   4854: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   4855:     }
1.811     albertel 4856: 
1.34      www      4857:     if ($chome ne 'no_host') {
1.302     albertel 4858:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 4859:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     4860: 	   my $username = $env{'user.name'}; # Defult username
                   4861: 	   if(defined $args->{'user'}) {
                   4862: 	       $username = $args->{'user'};
                   4863: 	   }
1.129     albertel 4864:            $returnhash{'home'}= $chome;
                   4865: 	   $returnhash{'domain'} = $cdomain;
                   4866: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  4867:            if (!defined($returnhash{'type'})) {
                   4868:                $returnhash{'type'} = 'Course';
                   4869:            }
1.130     albertel 4870:            while (my ($name,$value) = each %returnhash) {
1.53      www      4871:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 4872:            }
1.270     www      4873:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     4874:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     4875: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      4876:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   4877:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   4878:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      4879:        }
                   4880:     }
1.731     albertel 4881:     if (!$args->{'one_time'}) {
1.949     raeburn  4882: 	&appenv(\%envhash);
1.731     albertel 4883:     }
1.302     albertel 4884:     return %returnhash;
1.461     www      4885: }
                   4886: 
1.1080    raeburn  4887: sub update_released_required {
                   4888:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   4889:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   4890:         $cid = $env{'request.course.id'};
                   4891:         $cdom = $env{'course.'.$cid.'.domain'};
                   4892:         $cnum = $env{'course.'.$cid.'.num'};
                   4893:         $chome = $env{'course.'.$cid.'.home'};
                   4894:     }
                   4895:     if ($needsrelease) {
                   4896:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   4897:         my $needsupdate;
                   4898:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   4899:             $needsupdate = 1;
                   4900:         } else {
                   4901:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   4902:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   4903:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   4904:                 $needsupdate = 1;
                   4905:             }
                   4906:         }
                   4907:         if ($needsupdate) {
                   4908:             my %needshash = (
                   4909:                              'internal.releaserequired' => $needsrelease,
                   4910:                             );
                   4911:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   4912:             if ($putresult eq 'ok') {
                   4913:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   4914:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   4915:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   4916:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   4917:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   4918:                 }
                   4919:             }
                   4920:         }
                   4921:     }
                   4922:     return;
                   4923: }
                   4924: 
1.461     www      4925: # -------------------------------------------------See if a user is privileged
                   4926: 
                   4927: sub privileged {
1.1172.2.23  raeburn  4928:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 4929:     my $now = time;
1.1172.2.23  raeburn  4930:     my $roles;
                   4931:     if (ref($possroles) eq 'ARRAY') {
                   4932:         $roles = $possroles;
                   4933:     } else {
                   4934:         $roles = ['dc','su'];
                   4935:     }
                   4936:     if (ref($possdomains) eq 'ARRAY') {
                   4937:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   4938:         foreach my $dom (@{$possdomains}) {
                   4939:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   4940:                 (ref($privileged{$dom}) eq 'HASH')) {
                   4941:                 foreach my $role (@{$roles}) {
                   4942:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   4943:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   4944:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   4945:                             return 1 unless (($end && $end < $now) ||
                   4946:                                              ($start && $start > $now));
                   4947:                         }
                   4948:                     }
                   4949:                 }
                   4950:             }
                   4951:         }
                   4952:     } else {
                   4953:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   4954:         my $now = time;
1.1170    droeschl 4955: 
1.1172.2.23  raeburn  4956:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
1.1170    droeschl 4957:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  4958:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   4959:                 return 1 unless ($tend && $tend < $now)
                   4960:                         or ($tstart && $tstart > $now);
1.1170    droeschl 4961:             }
1.1172.2.23  raeburn  4962:         }
                   4963:     }
1.461     www      4964:     return 0;
1.9       www      4965: }
1.1       albertel 4966: 
1.1172.2.23  raeburn  4967: sub privileged_by_domain {
                   4968:     my ($domains,$roles) = @_;
                   4969:     my %privileged = ();
                   4970:     my $cachetime = 60*60*24;
                   4971:     my $now = time;
                   4972:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   4973:         return %privileged;
                   4974:     }
                   4975:     foreach my $dom (@{$domains}) {
                   4976:         next if (ref($privileged{$dom}) eq 'HASH');
                   4977:         my $needroles;
                   4978:         foreach my $role (@{$roles}) {
                   4979:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   4980:             if (defined($cached)) {
                   4981:                 if (ref($result) eq 'HASH') {
                   4982:                     $privileged{$dom}{$role} = $result;
                   4983:                 }
                   4984:             } else {
                   4985:                 $needroles = 1;
                   4986:             }
                   4987:         }
                   4988:         if ($needroles) {
                   4989:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   4990:             $privileged{$dom} = {};
                   4991:             foreach my $server (keys(%dompersonnel)) {
                   4992:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   4993:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   4994:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   4995:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   4996:                         next if ($end && $end < $now);
                   4997:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   4998:                             $dompersonnel{$server}{$item};
                   4999:                     }
                   5000:                 }
                   5001:             }
                   5002:             if (ref($privileged{$dom}) eq 'HASH') {
                   5003:                 foreach my $role (@{$roles}) {
                   5004:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5005:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   5006:                     } else {
                   5007:                         my %hash = ();
                   5008:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   5009:                     }
                   5010:                 }
                   5011:             }
                   5012:         }
                   5013:     }
                   5014:     return %privileged;
                   5015: }
                   5016: 
1.103     harris41 5017: # -------------------------------------------------------- Get user privileges
1.11      www      5018: 
                   5019: sub rolesinit {
1.1169    droeschl 5020:     my ($domain, $username) = @_;
                   5021:     my %userroles = ('user.login.time' => time);
                   5022:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   5023: 
                   5024:     # firstaccess and timerinterval are related to timed maps/resources. 
                   5025:     # also, blocking can be triggered by an activating timer
                   5026:     # it's saved in the user's %env.
                   5027:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   5028:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   5029:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   5030:         %timerintchk, %timerintenv);
                   5031: 
1.1162    raeburn  5032:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 5033:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  5034:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   5035:     }
1.1169    droeschl 5036: 
1.1162    raeburn  5037:     foreach my $key (keys(%timerinterval)) {
                   5038:         my ($cid,$rest) = split(/\0/,$key);
                   5039:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   5040:     }
1.1169    droeschl 5041: 
1.11      www      5042:     my %allroles=();
1.1162    raeburn  5043:     my %allgroups=();
1.11      www      5044: 
1.1169    droeschl 5045:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
                   5046:         my $role = $rolesdump{$area};
                   5047:         $area =~ s/\_\w\w$//;
                   5048: 
                   5049:         my ($trole, $tend, $tstart, $group_privs);
                   5050: 
                   5051:         if ($role =~ /^cr/) {
                   5052:         # Custom role, defined by a user 
                   5053:         # e.g., user.role.cr/msu/smith/mynewrole
                   5054:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5055:                 $trole = $1;
                   5056:                 ($tend, $tstart) = split('_', $2);
                   5057:             } else {
                   5058:                 $trole = $role;
                   5059:             }
                   5060:         } elsif ($role =~ m|^gr/|) {
                   5061:         # Role of member in a group, defined within a course/community
                   5062:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5063:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5064:             next if $tstart eq '-1';
                   5065:             ($trole, $group_privs) = split(/\//, $trole);
                   5066:             $group_privs = &unescape($group_privs);
                   5067:         } else {
                   5068:         # Just a normal role, defined in roles.tab
                   5069:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5070:         }
                   5071: 
                   5072:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5073:                  $username);
                   5074:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5075: 
                   5076:         # role expired or not available yet?
                   5077:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5078:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5079: 
                   5080:         next if $area eq '' or $trole eq '';
                   5081: 
                   5082:         my $spec = "$trole.$area";
                   5083:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5084: 
                   5085:         if ($trole =~ /^cr\//) {
                   5086:         # Custom role, defined by a user
                   5087:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5088:         } elsif ($trole eq 'gr') {
                   5089:         # Role of a member in a group, defined within a course/community
                   5090:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5091:             next;
                   5092:         } else {
                   5093:         # Normal role, defined in roles.tab
                   5094:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5095:         }
                   5096: 
                   5097:         my $cid = $tdomain.'_'.$trest;
                   5098:         unless ($firstaccchk{$cid}) {
                   5099:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5100:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5101:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5102:                         $coursetimerstarts{$cid}{$item}; 
                   5103:                 }
                   5104:             }
                   5105:             $firstaccchk{$cid} = 1;
                   5106:         }
                   5107:         unless ($timerintchk{$cid}) {
                   5108:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5109:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5110:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5111:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5112:                 }
1.12      www      5113:             }
1.1169    droeschl 5114:             $timerintchk{$cid} = 1;
1.191     harris41 5115:         }
1.11      www      5116:     }
1.1169    droeschl 5117: 
                   5118:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
                   5119:         \%allroles, \%allgroups);
                   5120:     $env{'user.adv'} = $userroles{'user.adv'};
                   5121: 
1.1162    raeburn  5122:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5123: }
                   5124: 
1.567     raeburn  5125: sub set_arearole {
1.1172.2.19  raeburn  5126:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   5127:     unless ($nolog) {
1.567     raeburn  5128: # log the associated role with the area
1.1172.2.19  raeburn  5129:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   5130:     }
1.743     albertel 5131:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5132: }
                   5133: 
                   5134: sub custom_roleprivs {
                   5135:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5136:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   5137:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 5138:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5139:         my ($rdummy,$roledef)=
                   5140:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5141:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5142:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5143:             if (defined($syspriv)) {
1.1043    raeburn  5144:                 if ($trest =~ /^$match_community$/) {
                   5145:                     $syspriv =~ s/bre\&S//; 
                   5146:                 }
1.567     raeburn  5147:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5148:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5149:             }
                   5150:             if ($tdomain ne '') {
                   5151:                 if (defined($dompriv)) {
                   5152:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5153:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5154:                 }
                   5155:                 if (($trest ne '') && (defined($coursepriv))) {
                   5156:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5157:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5158:                 }
                   5159:             }
                   5160:         }
                   5161:     }
                   5162: }
                   5163: 
1.678     raeburn  5164: sub group_roleprivs {
                   5165:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   5166:     my $access = 1;
                   5167:     my $now = time;
                   5168:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   5169:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   5170:     if ($access) {
1.811     albertel 5171:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  5172:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   5173:     }
                   5174: }
1.567     raeburn  5175: 
                   5176: sub standard_roleprivs {
                   5177:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   5178:     if (defined($pr{$trole.':s'})) {
                   5179:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   5180:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   5181:     }
                   5182:     if ($tdomain ne '') {
                   5183:         if (defined($pr{$trole.':d'})) {
                   5184:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5185:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5186:         }
                   5187:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   5188:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   5189:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   5190:         }
                   5191:     }
                   5192: }
                   5193: 
                   5194: sub set_userprivs {
1.1064    raeburn  5195:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  5196:     my $author=0;
                   5197:     my $adv=0;
1.678     raeburn  5198:     my %grouproles = ();
                   5199:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  5200:         my @groupkeys; 
1.1000    raeburn  5201:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  5202:             push(@groupkeys,$role);
                   5203:         }
                   5204:         if (ref($groups_roles) eq 'HASH') {
                   5205:             foreach my $key (keys(%{$groups_roles})) {
                   5206:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   5207:                     push(@groupkeys,$key);
                   5208:                 }
                   5209:             }
                   5210:         }
                   5211:         if (@groupkeys > 0) {
                   5212:             foreach my $role (@groupkeys) {
                   5213:                 my ($trole,$area,$sec,$extendedarea);
                   5214:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   5215:                     $trole = $1;
                   5216:                     $area = $2;
                   5217:                     $sec = $3;
                   5218:                     $extendedarea = $area.$sec;
                   5219:                     if (exists($$allgroups{$area})) {
                   5220:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   5221:                             my $spec = $trole.'.'.$extendedarea;
                   5222:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  5223:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  5224:                         }
1.678     raeburn  5225:                     }
                   5226:                 }
                   5227:             }
                   5228:         }
                   5229:     }
1.800     albertel 5230:     foreach my $group (keys(%grouproles)) {
                   5231:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  5232:     }
1.800     albertel 5233:     foreach my $role (keys(%{$allroles})) {
                   5234:         my %thesepriv;
1.941     raeburn  5235:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 5236:         foreach my $item (split(/:/,$$allroles{$role})) {
                   5237:             if ($item ne '') {
                   5238:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  5239:                 if ($restrictions eq '') {
                   5240:                     $thesepriv{$privilege}='F';
                   5241:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   5242:                     $thesepriv{$privilege}.=$restrictions;
                   5243:                 }
                   5244:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   5245:             }
                   5246:         }
                   5247:         my $thesestr='';
1.1104    raeburn  5248:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 5249: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   5250: 	}
                   5251:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  5252:     }
                   5253:     return ($author,$adv);
                   5254: }
                   5255: 
1.994     raeburn  5256: sub role_status {
1.1104    raeburn  5257:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  5258:     my @pwhere = ();
                   5259:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   5260:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   5261:         unless (!defined($$role) || $$role eq '') {
                   5262:             $$where=join('.',@pwhere);
                   5263:             $$trolecode=$$role.'.'.$$where;
                   5264:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   5265:             $$tstatus='is';
1.1104    raeburn  5266:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  5267:                 $$tstatus='future';
1.1034    raeburn  5268:                 if ($$tstart<$now) {
                   5269:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  5270:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  5271:                             my (%allroles,%allgroups,$group_privs,
                   5272:                                 %groups_roles,@rolecodes);
1.1002    raeburn  5273:                             my %userroles = (
                   5274:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   5275:                             );
1.1064    raeburn  5276:                             @rolecodes = ('cm'); 
1.1002    raeburn  5277:                             my $spec=$$role.'.'.$$where;
                   5278:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   5279:                             if ($$role =~ /^cr\//) {
                   5280:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  5281:                                 push(@rolecodes,'cr');
1.1002    raeburn  5282:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  5283:                                 push(@rolecodes,$$role);
1.1002    raeburn  5284:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   5285:                                                     $env{'user.name'});
1.1064    raeburn  5286:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  5287:                                 (undef,my $group_privs) = split(/\//,$trole);
                   5288:                                 $group_privs = &unescape($group_privs);
                   5289:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  5290:                                 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  5291:                                 &get_groups_roles($tdomain,$trest,
                   5292:                                                   \%course_roles,\@rolecodes,
                   5293:                                                   \%groups_roles);
1.1002    raeburn  5294:                             } else {
1.1064    raeburn  5295:                                 push(@rolecodes,$$role);
1.1002    raeburn  5296:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   5297:                             }
1.1064    raeburn  5298:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   5299:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  5300:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   5301:                         }
                   5302:                     }
1.1034    raeburn  5303:                     $$tstatus = 'is';
1.1002    raeburn  5304:                 }
1.994     raeburn  5305:             }
                   5306:             if ($$tend) {
1.1104    raeburn  5307:                 if ($$tend<$update) {
1.994     raeburn  5308:                     $$tstatus='expired';
                   5309:                 } elsif ($$tend<$now) {
                   5310:                     $$tstatus='will_not';
                   5311:                 }
                   5312:             }
                   5313:         }
                   5314:     }
                   5315: }
                   5316: 
1.1104    raeburn  5317: sub get_groups_roles {
                   5318:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   5319:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   5320:                   (ref($rolecodes) eq 'ARRAY') && 
                   5321:                   (ref($groups_roles) eq 'HASH')); 
                   5322:     if (keys(%{$cdom_courseroles}) > 0) {
                   5323:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   5324:         if ($cdom ne '' && $cnum ne '') {
                   5325:             foreach my $key (keys(%{$cdom_courseroles})) {
                   5326:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   5327:                     my $crsrole = $1;
                   5328:                     my $crssec = $2;
                   5329:                     if ($crsrole =~ /^cr/) {
                   5330:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   5331:                             push(@{$rolecodes},'cr');
                   5332:                         }
                   5333:                     } else {
                   5334:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   5335:                             push(@{$rolecodes},$crsrole);
                   5336:                         }
                   5337:                     }
                   5338:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   5339:                     if ($crssec ne '') {
                   5340:                         $rolekey .= "/$crssec";
                   5341:                     }
                   5342:                     $rolekey .= './';
                   5343:                     $groups_roles->{$rolekey} = $rolecodes;
                   5344:                 }
                   5345:             }
                   5346:         }
                   5347:     }
                   5348:     return;
                   5349: }
                   5350: 
                   5351: sub delete_env_groupprivs {
                   5352:     my ($where,$courseroles,$possroles) = @_;
                   5353:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   5354:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   5355:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   5356:         %{$courseroles->{$udom}} =
                   5357:             &get_my_roles('','','userroles',['active'],
                   5358:                           $possroles,[$udom],1);
                   5359:     }
                   5360:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   5361:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   5362:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   5363:             my $area = '/'.$cdom.'/'.$cnum;
                   5364:             my $privkey = "user.priv.$crsrole.$area";
                   5365:             if ($crssec ne '') {
                   5366:                 $privkey .= '/'.$crssec;
                   5367:             }
                   5368:             $privkey .= ".$area/$group";
                   5369:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   5370:         }
                   5371:     }
                   5372:     return;
                   5373: }
                   5374: 
1.994     raeburn  5375: sub check_adhoc_privs {
1.1104    raeburn  5376:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  5377:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.9  raeburn  5378:     my $setprivs;
1.994     raeburn  5379:     if ($env{$cckey}) {
                   5380:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  5381:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  5382:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  5383:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9  raeburn  5384:             $setprivs = 1;
1.994     raeburn  5385:         }
                   5386:     } else {
1.1088    raeburn  5387:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9  raeburn  5388:         $setprivs = 1;
1.994     raeburn  5389:     }
1.1172.2.9  raeburn  5390:     return $setprivs;
1.994     raeburn  5391: }
                   5392: 
                   5393: sub set_adhoc_privileges {
                   5394: # role can be cc or ca
1.1088    raeburn  5395:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  5396:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   5397:     my $spec = $role.'.'.$area;
                   5398:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  5399:                                   $env{'user.name'},1);
1.994     raeburn  5400:     my %ccrole = ();
                   5401:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   5402:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   5403:     &appenv(\%userroles,[$role,'cm']);
                   5404:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  5405:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   5406:         &appenv( {'request.role'        => $spec,
                   5407:                   'request.role.domain' => $dcdom,
                   5408:                   'request.course.sec'  => ''
                   5409:                  }
                   5410:                );
                   5411:         my $tadv=0;
                   5412:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   5413:         &appenv({'request.role.adv'    => $tadv});
                   5414:     }
1.994     raeburn  5415: }
                   5416: 
1.12      www      5417: # --------------------------------------------------------------- get interface
                   5418: 
                   5419: sub get {
1.131     albertel 5420:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5421:    my $items='';
1.800     albertel 5422:    foreach my $item (@$storearr) {
                   5423:        $items.=&escape($item).'&';
1.191     harris41 5424:    }
1.12      www      5425:    $items=~s/\&$//;
1.620     albertel 5426:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5427:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 5428:    my $uhome=&homeserver($uname,$udomain);
                   5429: 
1.133     albertel 5430:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5431:    my @pairs=split(/\&/,$rep);
1.273     albertel 5432:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   5433:      return @pairs;
                   5434:    }
1.15      www      5435:    my %returnhash=();
1.42      www      5436:    my $i=0;
1.800     albertel 5437:    foreach my $item (@$storearr) {
                   5438:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5439:       $i++;
1.191     harris41 5440:    }
1.15      www      5441:    return %returnhash;
1.27      www      5442: }
                   5443: 
                   5444: # --------------------------------------------------------------- del interface
                   5445: 
                   5446: sub del {
1.133     albertel 5447:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      5448:    my $items='';
1.800     albertel 5449:    foreach my $item (@$storearr) {
                   5450:        $items.=&escape($item).'&';
1.191     harris41 5451:    }
1.984     neumanie 5452: 
1.27      www      5453:    $items=~s/\&$//;
1.620     albertel 5454:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5455:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5456:    my $uhome=&homeserver($uname,$udomain);
                   5457:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5458: }
                   5459: 
                   5460: # -------------------------------------------------------------- dump interface
                   5461: 
1.1172.2.22  raeburn  5462: sub unserialize {
                   5463:     my ($rep, $escapedkeys) = @_;
                   5464: 
                   5465:     return {} if $rep =~ /^error/;
                   5466: 
                   5467:     my %returnhash=();
                   5468:     foreach my $item (split(/\&/,$rep)) {
                   5469:         my ($key, $value) = split(/=/, $item, 2);
                   5470:         $key = unescape($key) unless $escapedkeys;
                   5471:         next if $key =~ /^error: 2 /;
                   5472:         $returnhash{$key} = &thaw_unescape($value);
                   5473:     }
                   5474:     return \%returnhash;
                   5475: }
                   5476: 
                   5477: # see Lond::dump_with_regexp
                   5478: # if $escapedkeys hash keys won't get unescaped.
1.15      www      5479: sub dump {
1.1172.2.22  raeburn  5480:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 5481:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5482:     if (!$uname) { $uname=$env{'user.name'}; }
                   5483:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 5484: 
1.1172.2.22  raeburn  5485:     my $reply;
                   5486:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   5487:         # user is hosted on this machine
                   5488:         $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
                   5489:                     $uname, $namespace, $regexp, $range)), $loncaparevs{$uhome});
                   5490:         return %{&unserialize($reply, $escapedkeys)};
                   5491:     }
1.755     albertel 5492:     if ($regexp) {
                   5493: 	$regexp=&escape($regexp);
                   5494:     } else {
                   5495: 	$regexp='.';
                   5496:     }
1.1166    raeburn  5497:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 5498:     my @pairs=split(/\&/,$rep);
                   5499:     my %returnhash=();
1.1098    foxr     5500:     if (!($rep =~ /^error/ )) {
                   5501: 	foreach my $item (@pairs) {
                   5502: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  5503:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     5504: 	    next if ($key =~ /^error: 2 /);
                   5505: 	    $returnhash{$key}=&thaw_unescape($value);
                   5506: 	}
1.755     albertel 5507:     }
                   5508:     return %returnhash;
1.407     www      5509: }
                   5510: 
1.1098    foxr     5511: 
1.717     albertel 5512: # --------------------------------------------------------- dumpstore interface
                   5513: 
                   5514: sub dumpstore {
                   5515:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  5516:    # same as dump but keys must be escaped. They may contain colon separated
                   5517:    # lists of values that may themself contain colons (e.g. symbs).
                   5518:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 5519: }
                   5520: 
1.407     www      5521: # -------------------------------------------------------------- keys interface
                   5522: 
                   5523: sub getkeys {
                   5524:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 5525:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5526:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      5527:    my $uhome=&homeserver($uname,$udomain);
                   5528:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   5529:    my @keyarray=();
1.800     albertel 5530:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  5531:       next if ($key =~ /^error: 2 /);
1.800     albertel 5532:       push(@keyarray,&unescape($key));
1.407     www      5533:    }
                   5534:    return @keyarray;
1.318     matthew  5535: }
                   5536: 
1.319     matthew  5537: # --------------------------------------------------------------- currentdump
                   5538: sub currentdump {
1.328     matthew  5539:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 5540:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   5541:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   5542:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  5543:    my $uhome = &homeserver($sname,$sdom);
                   5544:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  5545:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  5546:    #
1.318     matthew  5547:    my %returnhash=();
1.319     matthew  5548:    #
                   5549:    if ($rep eq "unknown_cmd") { 
                   5550:        # an old lond will not know currentdump
                   5551:        # Do a dump and make it look like a currentdump
1.822     albertel 5552:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  5553:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   5554:        my %hash = @tmp;
                   5555:        @tmp=();
1.424     matthew  5556:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  5557:    } else {
                   5558:        my @pairs=split(/\&/,$rep);
1.800     albertel 5559:        foreach my $pair (@pairs) {
                   5560:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  5561:            my ($symb,$param) = split(/:/,$key);
                   5562:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 5563:                                                         &thaw_unescape($value);
1.319     matthew  5564:        }
1.191     harris41 5565:    }
1.12      www      5566:    return %returnhash;
1.424     matthew  5567: }
                   5568: 
                   5569: sub convert_dump_to_currentdump{
                   5570:     my %hash = %{shift()};
                   5571:     my %returnhash;
                   5572:     # Code ripped from lond, essentially.  The only difference
                   5573:     # here is the unescaping done by lonnet::dump().  Conceivably
                   5574:     # we might run in to problems with parameter names =~ /^v\./
                   5575:     while (my ($key,$value) = each(%hash)) {
                   5576:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 5577: 	$symb  = &unescape($symb);
                   5578: 	$param = &unescape($param);
1.424     matthew  5579:         next if ($v eq 'version' || $symb eq 'keys');
                   5580:         next if (exists($returnhash{$symb}) &&
                   5581:                  exists($returnhash{$symb}->{$param}) &&
                   5582:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   5583:         $returnhash{$symb}->{$param}=$value;
                   5584:         $returnhash{$symb}->{'v.'.$param}=$v;
                   5585:     }
                   5586:     #
                   5587:     # Remove all of the keys in the hashes which keep track of
                   5588:     # the version of the parameter.
                   5589:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   5590:         # use a foreach because we are going to delete from the hash.
                   5591:         foreach my $key (keys(%$param_hash)) {
                   5592:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   5593:         }
                   5594:     }
                   5595:     return \%returnhash;
1.12      www      5596: }
                   5597: 
1.627     albertel 5598: # ------------------------------------------------------ critical inc interface
                   5599: 
                   5600: sub cinc {
                   5601:     return &inc(@_,'critical');
                   5602: }
                   5603: 
1.449     matthew  5604: # --------------------------------------------------------------- inc interface
                   5605: 
                   5606: sub inc {
1.627     albertel 5607:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 5608:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5609:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  5610:     my $uhome=&homeserver($uname,$udomain);
                   5611:     my $items='';
                   5612:     if (! ref($store)) {
                   5613:         # got a single value, so use that instead
                   5614:         $items = &escape($store).'=&';
                   5615:     } elsif (ref($store) eq 'SCALAR') {
                   5616:         $items = &escape($$store).'=&';        
                   5617:     } elsif (ref($store) eq 'ARRAY') {
                   5618:         $items = join('=&',map {&escape($_);} @{$store});
                   5619:     } elsif (ref($store) eq 'HASH') {
                   5620:         while (my($key,$value) = each(%{$store})) {
                   5621:             $items.= &escape($key).'='.&escape($value).'&';
                   5622:         }
                   5623:     }
                   5624:     $items=~s/\&$//;
1.627     albertel 5625:     if ($critical) {
                   5626: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5627:     } else {
                   5628: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5629:     }
1.449     matthew  5630: }
                   5631: 
1.12      www      5632: # --------------------------------------------------------------- put interface
                   5633: 
                   5634: sub put {
1.134     albertel 5635:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5636:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5637:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5638:    my $uhome=&homeserver($uname,$udomain);
1.12      www      5639:    my $items='';
1.800     albertel 5640:    foreach my $item (keys(%$storehash)) {
                   5641:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5642:    }
1.12      www      5643:    $items=~s/\&$//;
1.134     albertel 5644:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      5645: }
                   5646: 
1.631     albertel 5647: # ------------------------------------------------------------ newput interface
                   5648: 
                   5649: sub newput {
                   5650:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   5651:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5652:    if (!$uname) { $uname=$env{'user.name'}; }
                   5653:    my $uhome=&homeserver($uname,$udomain);
                   5654:    my $items='';
                   5655:    foreach my $key (keys(%$storehash)) {
                   5656:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   5657:    }
                   5658:    $items=~s/\&$//;
                   5659:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   5660: }
                   5661: 
                   5662: # ---------------------------------------------------------  putstore interface
                   5663: 
1.524     raeburn  5664: sub putstore {
1.715     albertel 5665:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 5666:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5667:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  5668:    my $uhome=&homeserver($uname,$udomain);
                   5669:    my $items='';
1.715     albertel 5670:    foreach my $key (keys(%$storehash)) {
                   5671:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  5672:    }
1.715     albertel 5673:    $items=~s/\&$//;
1.716     albertel 5674:    my $esc_symb=&escape($symb);
                   5675:    my $esc_v=&escape($version);
1.715     albertel 5676:    my $reply =
1.716     albertel 5677:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 5678: 	      $uhome);
                   5679:    if ($reply eq 'unknown_cmd') {
1.716     albertel 5680:        # gfall back to way things use to be done
1.715     albertel 5681:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   5682: 			    $uname);
1.524     raeburn  5683:    }
1.715     albertel 5684:    return $reply;
                   5685: }
                   5686: 
                   5687: sub old_putstore {
1.716     albertel 5688:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   5689:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5690:     if (!$uname) { $uname=$env{'user.name'}; }
                   5691:     my $uhome=&homeserver($uname,$udomain);
                   5692:     my %newstorehash;
1.800     albertel 5693:     foreach my $item (keys(%$storehash)) {
                   5694: 	my $key = $version.':'.&escape($symb).':'.$item;
                   5695: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 5696:     }
                   5697:     my $items='';
                   5698:     my %allitems = ();
1.800     albertel 5699:     foreach my $item (keys(%newstorehash)) {
                   5700: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 5701: 	    my $key = $1.':keys:'.$2;
                   5702: 	    $allitems{$key} .= $3.':';
                   5703: 	}
1.800     albertel 5704: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 5705:     }
1.800     albertel 5706:     foreach my $item (keys(%allitems)) {
                   5707: 	$allitems{$item} =~ s/\:$//;
                   5708: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 5709:     }
                   5710:     $items=~s/\&$//;
                   5711:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  5712: }
                   5713: 
1.47      www      5714: # ------------------------------------------------------ critical put interface
                   5715: 
                   5716: sub cput {
1.134     albertel 5717:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5718:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5719:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5720:    my $uhome=&homeserver($uname,$udomain);
1.47      www      5721:    my $items='';
1.800     albertel 5722:    foreach my $item (keys(%$storehash)) {
                   5723:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5724:    }
1.47      www      5725:    $items=~s/\&$//;
1.134     albertel 5726:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5727: }
                   5728: 
                   5729: # -------------------------------------------------------------- eget interface
                   5730: 
                   5731: sub eget {
1.133     albertel 5732:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5733:    my $items='';
1.800     albertel 5734:    foreach my $item (@$storearr) {
                   5735:        $items.=&escape($item).'&';
1.191     harris41 5736:    }
1.12      www      5737:    $items=~s/\&$//;
1.620     albertel 5738:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5739:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5740:    my $uhome=&homeserver($uname,$udomain);
                   5741:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5742:    my @pairs=split(/\&/,$rep);
                   5743:    my %returnhash=();
1.42      www      5744:    my $i=0;
1.800     albertel 5745:    foreach my $item (@$storearr) {
                   5746:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5747:       $i++;
1.191     harris41 5748:    }
1.12      www      5749:    return %returnhash;
                   5750: }
                   5751: 
1.667     albertel 5752: # ------------------------------------------------------------ tmpput interface
                   5753: sub tmpput {
1.802     raeburn  5754:     my ($storehash,$server,$context)=@_;
1.667     albertel 5755:     my $items='';
1.800     albertel 5756:     foreach my $item (keys(%$storehash)) {
                   5757: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 5758:     }
                   5759:     $items=~s/\&$//;
1.802     raeburn  5760:     if (defined($context)) {
                   5761:         $items .= ':'.&escape($context);
                   5762:     }
1.667     albertel 5763:     return &reply("tmpput:$items",$server);
                   5764: }
                   5765: 
                   5766: # ------------------------------------------------------------ tmpget interface
                   5767: sub tmpget {
1.688     albertel 5768:     my ($token,$server)=@_;
                   5769:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5770:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 5771:     my %returnhash;
                   5772:     foreach my $item (split(/\&/,$rep)) {
                   5773: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  5774:         next if ($key =~ /^error: 2 /);
1.667     albertel 5775: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   5776:     }
                   5777:     return %returnhash;
                   5778: }
                   5779: 
1.1113    raeburn  5780: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 5781: sub tmpdel {
                   5782:     my ($token,$server)=@_;
                   5783:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5784:     return &reply("tmpdel:$token",$server);
                   5785: }
                   5786: 
1.1172.2.13  raeburn  5787: # ------------------------------------------------------------ get_timebased_id
                   5788: 
                   5789: sub get_timebased_id {
                   5790:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   5791:         $maxtries) = @_;
                   5792:     my ($newid,$error,$dellock);
                   5793:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   5794:         return ('','ok','invalid call to get suffix');
                   5795:     }
                   5796: 
                   5797: # set defaults for any optional args for which values were not supplied
                   5798:     if ($who eq '') {
                   5799:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   5800:     }
                   5801:     if (!$locktries) {
                   5802:         $locktries = 3;
                   5803:     }
                   5804:     if (!$maxtries) {
                   5805:         $maxtries = 10;
                   5806:     }
                   5807: 
                   5808:     if (($cdom eq '') || ($cnum eq '')) {
                   5809:         if ($env{'request.course.id'}) {
                   5810:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5811:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5812:         }
                   5813:         if (($cdom eq '') || ($cnum eq '')) {
                   5814:             return ('','ok','call to get suffix not in course context');
                   5815:         }
                   5816:     }
                   5817: 
                   5818: # construct locking item
                   5819:     my $lockhash = {
                   5820:                       $prefix."\0".'locked_'.$keyid => $who,
                   5821:                    };
                   5822:     my $tries = 0;
                   5823: 
                   5824: # attempt to get lock on nohist_$namespace file
                   5825:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   5826:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   5827:         $tries ++;
                   5828:         sleep 1;
                   5829:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   5830:     }
                   5831: 
                   5832: # attempt to get unique identifier, based on current timestamp
                   5833:     if ($gotlock eq 'ok') {
                   5834:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   5835:         my $id = time;
                   5836:         $newid = $id;
                   5837:         my $idtries = 0;
                   5838:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   5839:             if ($idtype eq 'concat') {
                   5840:                 $newid = $id.$idtries;
                   5841:             } else {
                   5842:                 $newid ++;
                   5843:             }
                   5844:             $idtries ++;
                   5845:         }
                   5846:         if (!exists($inuse{$prefix."\0".$newid})) {
                   5847:             my %new_item =  (
                   5848:                               $prefix."\0".$newid => $who,
                   5849:                             );
                   5850:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   5851:                                                  $cdom,$cnum);
                   5852:             if ($putresult ne 'ok') {
                   5853:                 undef($newid);
                   5854:                 $error = 'error saving new item: '.$putresult;
                   5855:             }
                   5856:         } else {
                   5857:              $error = ('error: no unique suffix available for the new item ');
                   5858:         }
                   5859: #  remove lock
                   5860:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   5861:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   5862:     } else {
                   5863:         $error = "error: could not obtain lockfile\n";
                   5864:         $dellock = 'ok';
                   5865:     }
                   5866:     return ($newid,$dellock,$error);
                   5867: }
                   5868: 
1.765     albertel 5869: # -------------------------------------------------- portfolio access checking
                   5870: 
                   5871: sub portfolio_access {
1.766     albertel 5872:     my ($requrl) = @_;
1.765     albertel 5873:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   5874:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  5875:     if ($result) {
                   5876:         my %setters;
                   5877:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5878:             my ($startblock,$endblock) =
                   5879:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   5880:             if ($startblock && $endblock) {
                   5881:                 return 'B';
                   5882:             }
                   5883:         } else {
                   5884:             my ($startblock,$endblock) =
                   5885:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   5886:             if ($startblock && $endblock) {
                   5887:                 return 'B';
                   5888:             }
                   5889:         }
                   5890:     }
1.765     albertel 5891:     if ($result eq 'ok') {
1.766     albertel 5892:        return 'F';
1.765     albertel 5893:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 5894:        return 'A';
1.765     albertel 5895:     }
1.766     albertel 5896:     return '';
1.765     albertel 5897: }
                   5898: 
                   5899: sub get_portfolio_access {
1.767     albertel 5900:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   5901: 
                   5902:     if (!ref($access_hash)) {
                   5903: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   5904: 	my %access_controls = &get_access_controls($current_perms,$group,
                   5905: 						   $file_name);
                   5906: 	$access_hash = $access_controls{$file_name};
                   5907:     }
                   5908: 
1.765     albertel 5909:     my ($public,$guest,@domains,@users,@courses,@groups);
                   5910:     my $now = time;
                   5911:     if (ref($access_hash) eq 'HASH') {
                   5912:         foreach my $key (keys(%{$access_hash})) {
                   5913:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5914:             if ($start > $now) {
                   5915:                 next;
                   5916:             }
                   5917:             if ($end && $end<$now) {
                   5918:                 next;
                   5919:             }
                   5920:             if ($scope eq 'public') {
                   5921:                 $public = $key;
                   5922:                 last;
                   5923:             } elsif ($scope eq 'guest') {
                   5924:                 $guest = $key;
                   5925:             } elsif ($scope eq 'domains') {
                   5926:                 push(@domains,$key);
                   5927:             } elsif ($scope eq 'users') {
                   5928:                 push(@users,$key);
                   5929:             } elsif ($scope eq 'course') {
                   5930:                 push(@courses,$key);
                   5931:             } elsif ($scope eq 'group') {
                   5932:                 push(@groups,$key);
                   5933:             }
                   5934:         }
                   5935:         if ($public) {
                   5936:             return 'ok';
                   5937:         }
                   5938:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5939:             if ($guest) {
                   5940:                 return $guest;
                   5941:             }
                   5942:         } else {
                   5943:             if (@domains > 0) {
                   5944:                 foreach my $domkey (@domains) {
                   5945:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   5946:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   5947:                             return 'ok';
                   5948:                         }
                   5949:                     }
                   5950:                 }
                   5951:             }
                   5952:             if (@users > 0) {
                   5953:                 foreach my $userkey (@users) {
1.865     raeburn  5954:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   5955:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   5956:                             if (ref($item) eq 'HASH') {
                   5957:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   5958:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   5959:                                     return 'ok';
                   5960:                                 }
                   5961:                             }
                   5962:                         }
                   5963:                     } 
1.765     albertel 5964:                 }
                   5965:             }
                   5966:             my %roleshash;
                   5967:             my @courses_and_groups = @courses;
                   5968:             push(@courses_and_groups,@groups); 
                   5969:             if (@courses_and_groups > 0) {
                   5970:                 my (%allgroups,%allroles); 
                   5971:                 my ($start,$end,$role,$sec,$group);
                   5972:                 foreach my $envkey (%env) {
1.1060    raeburn  5973:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5974:                         my $cid = $2.'_'.$3; 
                   5975:                         if ($1 eq 'gr') {
                   5976:                             $group = $4;
                   5977:                             $allgroups{$cid}{$group} = $env{$envkey};
                   5978:                         } else {
                   5979:                             if ($4 eq '') {
                   5980:                                 $sec = 'none';
                   5981:                             } else {
                   5982:                                 $sec = $4;
                   5983:                             }
                   5984:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5985:                         }
1.811     albertel 5986:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5987:                         my $cid = $2.'_'.$3;
                   5988:                         if ($4 eq '') {
                   5989:                             $sec = 'none';
                   5990:                         } else {
                   5991:                             $sec = $4;
                   5992:                         }
                   5993:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5994:                     }
                   5995:                 }
                   5996:                 if (keys(%allroles) == 0) {
                   5997:                     return;
                   5998:                 }
                   5999:                 foreach my $key (@courses_and_groups) {
                   6000:                     my %content = %{$$access_hash{$key}};
                   6001:                     my $cnum = $content{'number'};
                   6002:                     my $cdom = $content{'domain'};
                   6003:                     my $cid = $cdom.'_'.$cnum;
                   6004:                     if (!exists($allroles{$cid})) {
                   6005:                         next;
                   6006:                     }    
                   6007:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   6008:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   6009:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   6010:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   6011:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   6012:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   6013:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   6014:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   6015:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   6016:                                         if (grep/^all$/,@sections) {
                   6017:                                             return 'ok';
                   6018:                                         } else {
                   6019:                                             if (grep/^$sec$/,@sections) {
                   6020:                                                 return 'ok';
                   6021:                                             }
                   6022:                                         }
                   6023:                                     }
                   6024:                                 }
                   6025:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   6026:                                     if (grep/^none$/,@groups) {
                   6027:                                         return 'ok';
                   6028:                                     }
                   6029:                                 } else {
                   6030:                                     if (grep/^all$/,@groups) {
                   6031:                                         return 'ok';
                   6032:                                     } 
                   6033:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   6034:                                         if (grep/^$group$/,@groups) {
                   6035:                                             return 'ok';
                   6036:                                         }
                   6037:                                     }
                   6038:                                 } 
                   6039:                             }
                   6040:                         }
                   6041:                     }
                   6042:                 }
                   6043:             }
                   6044:             if ($guest) {
                   6045:                 return $guest;
                   6046:             }
                   6047:         }
                   6048:     }
                   6049:     return;
                   6050: }
                   6051: 
                   6052: sub course_group_datechecker {
                   6053:     my ($dates,$now,$status) = @_;
                   6054:     my ($start,$end) = split(/\./,$dates);
                   6055:     if (!$start && !$end) {
                   6056:         return 'ok';
                   6057:     }
                   6058:     if (grep/^active$/,@{$status}) {
                   6059:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   6060:             return 'ok';
                   6061:         }
                   6062:     }
                   6063:     if (grep/^previous$/,@{$status}) {
                   6064:         if ($end > $now ) {
                   6065:             return 'ok';
                   6066:         }
                   6067:     }
                   6068:     if (grep/^future$/,@{$status}) {
                   6069:         if ($start > $now) {
                   6070:             return 'ok';
                   6071:         }
                   6072:     }
                   6073:     return; 
                   6074: }
                   6075: 
                   6076: sub parse_portfolio_url {
                   6077:     my ($url) = @_;
                   6078: 
                   6079:     my ($type,$udom,$unum,$group,$file_name);
                   6080:     
1.823     albertel 6081:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 6082: 	$type = 1;
                   6083:         $udom = $1;
                   6084:         $unum = $2;
                   6085:         $file_name = $3;
1.823     albertel 6086:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 6087: 	$type = 2;
                   6088:         $udom = $1;
                   6089:         $unum = $2;
                   6090:         $group = $3;
                   6091:         $file_name = $3.'/'.$4;
                   6092:     }
                   6093:     if (wantarray) {
                   6094: 	return ($type,$udom,$unum,$file_name,$group);
                   6095:     }
                   6096:     return $type;
                   6097: }
                   6098: 
                   6099: sub is_portfolio_url {
                   6100:     my ($url) = @_;
                   6101:     return scalar(&parse_portfolio_url($url));
                   6102: }
                   6103: 
1.798     raeburn  6104: sub is_portfolio_file {
                   6105:     my ($file) = @_;
1.820     raeburn  6106:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  6107:         return 1;
                   6108:     }
                   6109:     return;
                   6110: }
                   6111: 
1.976     raeburn  6112: sub usertools_access {
1.1084    raeburn  6113:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  6114:     my ($access,%tools);
                   6115:     if ($context eq '') {
                   6116:         $context = 'tools';
                   6117:     }
                   6118:     if ($context eq 'requestcourses') {
                   6119:         %tools = (
                   6120:                       official   => 1,
                   6121:                       unofficial => 1,
1.1006    raeburn  6122:                       community  => 1,
1.985     raeburn  6123:                  );
1.1172.2.9  raeburn  6124:     } elsif ($context eq 'requestauthor') {
                   6125:         %tools = (
                   6126:                       requestauthor => 1,
                   6127:                  );
1.985     raeburn  6128:     } else {
                   6129:         %tools = (
                   6130:                       aboutme   => 1,
                   6131:                       blog      => 1,
1.1172.2.6  raeburn  6132:                       webdav    => 1,
1.985     raeburn  6133:                       portfolio => 1,
                   6134:                  );
                   6135:     }
1.976     raeburn  6136:     return if (!defined($tools{$tool}));
                   6137: 
                   6138:     if ((!defined($udom)) || (!defined($uname))) {
                   6139:         $udom = $env{'user.domain'};
                   6140:         $uname = $env{'user.name'};
                   6141:     }
                   6142: 
1.978     raeburn  6143:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6144:         if ($action ne 'reload') {
1.985     raeburn  6145:             if ($context eq 'requestcourses') {
                   6146:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  6147:             } elsif ($context eq 'requestauthor') {
                   6148:                 return $env{'environment.canrequest.author'};
1.985     raeburn  6149:             } else {
                   6150:                 return $env{'environment.availabletools.'.$tool};
                   6151:             }
                   6152:         }
1.976     raeburn  6153:     }
                   6154: 
1.1172.2.9  raeburn  6155:     my ($toolstatus,$inststatus,$envkey);
                   6156:     if ($context eq 'requestauthor') {
                   6157:         $envkey = $context;
                   6158:     } else {
                   6159:         $envkey = $context.'.'.$tool;
                   6160:     }
1.976     raeburn  6161: 
1.985     raeburn  6162:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   6163:          ($action ne 'reload')) {
1.1172.2.9  raeburn  6164:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  6165:         $inststatus = $env{'environment.inststatus'};
                   6166:     } else {
1.1084    raeburn  6167:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  6168:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  6169:             $inststatus = $userenvref->{'inststatus'};
                   6170:         } else {
1.1172.2.9  raeburn  6171:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   6172:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  6173:             $inststatus = $userenv{'inststatus'};
                   6174:         }
1.976     raeburn  6175:     }
                   6176: 
                   6177:     if ($toolstatus ne '') {
                   6178:         if ($toolstatus) {
                   6179:             $access = 1;
                   6180:         } else {
                   6181:             $access = 0;
                   6182:         }
                   6183:         return $access;
                   6184:     }
                   6185: 
1.1084    raeburn  6186:     my ($is_adv,%domdef);
                   6187:     if (ref($is_advref) eq 'HASH') {
                   6188:         $is_adv = $is_advref->{'is_adv'};
                   6189:     } else {
                   6190:         $is_adv = &is_advanced_user($udom,$uname);
                   6191:     }
                   6192:     if (ref($domdefref) eq 'HASH') {
                   6193:         %domdef = %{$domdefref};
                   6194:     } else {
                   6195:         %domdef = &get_domain_defaults($udom);
                   6196:     }
1.976     raeburn  6197:     if (ref($domdef{$tool}) eq 'HASH') {
                   6198:         if ($is_adv) {
                   6199:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   6200:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   6201:                     $access = 1;
                   6202:                 } else {
                   6203:                     $access = 0;
                   6204:                 }
                   6205:                 return $access;
                   6206:             }
                   6207:         }
                   6208:         if ($inststatus ne '') {
                   6209:             my ($hasaccess,$hasnoaccess);
                   6210:             foreach my $affiliation (split(/:/,$inststatus)) {
                   6211:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   6212:                     if ($domdef{$tool}{$affiliation}) {
                   6213:                         $hasaccess = 1;
                   6214:                     } else {
                   6215:                         $hasnoaccess = 1;
                   6216:                     }
                   6217:                 }
                   6218:             }
                   6219:             if ($hasaccess || $hasnoaccess) {
                   6220:                 if ($hasaccess) {
                   6221:                     $access = 1;
                   6222:                 } elsif ($hasnoaccess) {
                   6223:                     $access = 0; 
                   6224:                 }
                   6225:                 return $access;
                   6226:             }
                   6227:         } else {
                   6228:             if ($domdef{$tool}{'default'} ne '') {
                   6229:                 if ($domdef{$tool}{'default'}) {
                   6230:                     $access = 1;
                   6231:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   6232:                     $access = 0;
                   6233:                 }
                   6234:                 return $access;
                   6235:             }
                   6236:         }
                   6237:     } else {
1.1172.2.6  raeburn  6238:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  6239:             $access = 1;
                   6240:         } else {
                   6241:             $access = 0;
                   6242:         }
1.976     raeburn  6243:         return $access;
                   6244:     }
                   6245: }
                   6246: 
1.1050    raeburn  6247: sub is_course_owner {
                   6248:     my ($cdom,$cnum,$udom,$uname) = @_;
                   6249:     if (($udom eq '') || ($uname eq '')) {
                   6250:         $udom = $env{'user.domain'};
                   6251:         $uname = $env{'user.name'};
                   6252:     }
                   6253:     unless (($udom eq '') || ($uname eq '')) {
                   6254:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   6255:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   6256:                 return 1;
                   6257:             } else {
                   6258:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   6259:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   6260:                     return 1;
                   6261:                 }
                   6262:             }
                   6263:         }
                   6264:     }
                   6265:     return;
                   6266: }
                   6267: 
1.976     raeburn  6268: sub is_advanced_user {
                   6269:     my ($udom,$uname) = @_;
1.1085    raeburn  6270:     if ($udom ne '' && $uname ne '') {
                   6271:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  6272:             if (wantarray) {
                   6273:                 return ($env{'user.adv'},$env{'user.author'});
                   6274:             } else {
                   6275:                 return $env{'user.adv'};
                   6276:             }
1.1085    raeburn  6277:         }
                   6278:     }
1.976     raeburn  6279:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   6280:     my %allroles;
1.1128    raeburn  6281:     my ($is_adv,$is_author);
1.976     raeburn  6282:     foreach my $role (keys(%roleshash)) {
                   6283:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   6284:         my $area = '/'.$tdomain.'/'.$trest;
                   6285:         if ($sec ne '') {
                   6286:             $area .= '/'.$sec;
                   6287:         }
                   6288:         if (($area ne '') && ($trole ne '')) {
                   6289:             my $spec=$trole.'.'.$area;
                   6290:             if ($trole =~ /^cr\//) {
                   6291:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6292:             } elsif ($trole ne 'gr') {
                   6293:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6294:             }
1.1128    raeburn  6295:             if ($trole eq 'au') {
                   6296:                 $is_author = 1;
                   6297:             }
1.976     raeburn  6298:         }
                   6299:     }
                   6300:     foreach my $role (keys(%allroles)) {
                   6301:         last if ($is_adv);
                   6302:         foreach my $item (split(/:/,$allroles{$role})) {
                   6303:             if ($item ne '') {
                   6304:                 my ($privilege,$restrictions)=split(/&/,$item);
                   6305:                 if ($privilege eq 'adv') {
                   6306:                     $is_adv = 1;
                   6307:                     last;
                   6308:                 }
                   6309:             }
                   6310:         }
                   6311:     }
1.1128    raeburn  6312:     if (wantarray) {
                   6313:         return ($is_adv,$is_author);
                   6314:     }
1.976     raeburn  6315:     return $is_adv;
                   6316: }
1.798     raeburn  6317: 
1.1035    raeburn  6318: sub check_can_request {
1.1036    raeburn  6319:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  6320:     my $canreq = 0;
                   6321:     my ($types,$typename) = &Apache::loncommon::course_types();
                   6322:     my @options = ('approval','validate','autolimit');
                   6323:     my $optregex = join('|',@options);
                   6324:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   6325:         foreach my $type (@{$types}) {
                   6326:             if (&usertools_access($env{'user.name'},
                   6327:                                   $env{'user.domain'},
                   6328:                                   $type,undef,'requestcourses')) {
                   6329:                 $canreq ++;
1.1036    raeburn  6330:                 if (ref($request_domains) eq 'HASH') {
                   6331:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   6332:                 }
1.1035    raeburn  6333:                 if ($dom eq $env{'user.domain'}) {
                   6334:                     $can_request->{$type} = 1;
                   6335:                 }
                   6336:             }
                   6337:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   6338:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   6339:                 if (@curr > 0) {
1.1036    raeburn  6340:                     foreach my $item (@curr) {
                   6341:                         if (ref($request_domains) eq 'HASH') {
                   6342:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   6343:                             if ($otherdom ne '') {
                   6344:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   6345:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   6346:                                         push(@{$request_domains->{$type}},$otherdom);
                   6347:                                     }
                   6348:                                 } else {
                   6349:                                     push(@{$request_domains->{$type}},$otherdom);
                   6350:                                 }
                   6351:                             }
                   6352:                         }
                   6353:                     }
                   6354:                     unless($dom eq $env{'user.domain'}) {
                   6355:                         $canreq ++;
1.1035    raeburn  6356:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   6357:                             $can_request->{$type} = 1;
                   6358:                         }
                   6359:                     }
                   6360:                 }
                   6361:             }
                   6362:         }
                   6363:     }
                   6364:     return $canreq;
                   6365: }
                   6366: 
1.341     www      6367: # ---------------------------------------------- Custom access rule evaluation
                   6368: 
                   6369: sub customaccess {
                   6370:     my ($priv,$uri)=@_;
1.807     albertel 6371:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      6372:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 6373:     $udom = &LONCAPA::clean_domain($udom);
                   6374:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      6375:     my $access=0;
1.800     albertel 6376:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 6377: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   6378: 	if ($type eq 'user') {
                   6379: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 6380: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 6381: 		if ($tdom) {
                   6382: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   6383: 		}
1.896     albertel 6384: 		if ($tuname) {
                   6385: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 6386: 		}
                   6387: 		$access=($effect eq 'allow');
                   6388: 		last;
                   6389: 	    }
                   6390: 	} else {
                   6391: 	    if ($role) {
                   6392: 		if ($role ne $urole) { next; }
                   6393: 	    }
                   6394: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   6395: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   6396: 		if ($tdom) {
                   6397: 		    if ($tdom ne $udom) { next; }
                   6398: 		}
                   6399: 		if ($tcrs) {
                   6400: 		    if ($tcrs ne $ucrs) { next; }
                   6401: 		}
                   6402: 		if ($tsec) {
                   6403: 		    if ($tsec ne $usec) { next; }
                   6404: 		}
                   6405: 		$access=($effect eq 'allow');
                   6406: 		last;
                   6407: 	    }
                   6408: 	    if ($realm eq '' && $role eq '') {
                   6409: 		$access=($effect eq 'allow');
                   6410: 	    }
1.402     bowersj2 6411: 	}
1.341     www      6412:     }
                   6413:     return $access;
                   6414: }
                   6415: 
1.103     harris41 6416: # ------------------------------------------------- Check for a user privilege
1.12      www      6417: 
                   6418: sub allowed {
1.810     raeburn  6419:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 6420:     my $ver_orguri=$uri;
1.439     www      6421:     $uri=&deversion($uri);
1.152     www      6422:     my $orguri=$uri;
1.52      www      6423:     $uri=&declutter($uri);
1.809     raeburn  6424: 
1.810     raeburn  6425:     if ($priv eq 'evb') {
                   6426: # Evade communication block restrictions for specified role in a course
                   6427:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   6428:             return $1;
                   6429:         } else {
                   6430:             return;
                   6431:         }
                   6432:     }
                   6433: 
1.620     albertel 6434:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      6435: # Free bre access to adm and meta resources
1.775     albertel 6436:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 6437: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   6438: 	&& ($priv eq 'bre')) {
1.14      www      6439: 	return 'F';
1.159     www      6440:     }
                   6441: 
1.545     banghart 6442: # Free bre access to user's own portfolio contents
1.714     raeburn  6443:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  6444:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  6445: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  6446:         my %setters;
                   6447:         my ($startblock,$endblock) = 
                   6448:             &Apache::loncommon::blockcheck(\%setters,'port');
                   6449:         if ($startblock && $endblock) {
                   6450:             return 'B';
                   6451:         } else {
                   6452:             return 'F';
                   6453:         }
1.545     banghart 6454:     }
                   6455: 
1.762     raeburn  6456: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  6457:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   6458:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   6459:         if (exists($env{'request.course.id'})) {
                   6460:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6461:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6462:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   6463:                 my $courseprivid=$env{'request.course.id'};
                   6464:                 $courseprivid=~s/\_/\//;
                   6465:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   6466:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   6467:                     return $1; 
1.762     raeburn  6468:                 } else {
                   6469:                     if ($env{'request.course.sec'}) {
                   6470:                         $courseprivid.='/'.$env{'request.course.sec'};
                   6471:                     }
                   6472:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   6473:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   6474:                         return $2;
                   6475:                     }
1.714     raeburn  6476:                 }
                   6477:             }
                   6478:         }
                   6479:     }
                   6480: 
1.159     www      6481: # Free bre to public access
                   6482: 
                   6483:     if ($priv eq 'bre') {
1.238     www      6484:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 6485: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      6486:            return 'F'; 
                   6487:         }
1.238     www      6488:         if ($copyright eq 'priv') {
                   6489:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6490: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      6491: 		return '';
                   6492:             }
                   6493:         }
                   6494:         if ($copyright eq 'domain') {
                   6495:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6496: 	    unless (($env{'user.domain'} eq $1) ||
                   6497:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      6498: 		return '';
                   6499:             }
1.262     matthew  6500:         }
1.620     albertel 6501:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  6502:             # Library role, so allow browsing of resources in this domain.
                   6503:             return 'F';
1.238     www      6504:         }
1.341     www      6505:         if ($copyright eq 'custom') {
                   6506: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   6507:         }
1.14      www      6508:     }
1.264     matthew  6509:     # Domain coordinator is trying to create a course
1.620     albertel 6510:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  6511:         # uri is the requested domain in this case.
                   6512:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  6513:         # a role of dc for the domain in question.
1.620     albertel 6514:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  6515:     }
1.29      www      6516: 
1.52      www      6517:     my $thisallowed='';
                   6518:     my $statecond=0;
                   6519:     my $courseprivid='';
                   6520: 
1.1039    raeburn  6521:     my $ownaccess;
1.1043    raeburn  6522:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  6523:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   6524:         if ($uri eq '') {
                   6525:             $ownaccess = 1;
                   6526:         } else {
                   6527:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   6528:                 my $udom = $env{'user.domain'};
                   6529:                 my $uname = $env{'user.name'};
                   6530:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   6531:                     $ownaccess = 1;
1.1040    raeburn  6532:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  6533:                     unless ($uri =~ m{\.\./}) {
                   6534:                         $ownaccess = 1;
                   6535:                     }
                   6536:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   6537:                     my $now = time;
                   6538:                     if ($uri =~ m{^([^/]+)/?$}) {
                   6539:                         my $adom = $1;
                   6540:                         foreach my $key (keys(%env)) {
1.1042    raeburn  6541:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  6542:                                 my ($start,$end) = split('.',$env{$key});
                   6543:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6544:                                     $ownaccess = 1;
                   6545:                                     last;
                   6546:                                 }
                   6547:                             }
                   6548:                         }
                   6549:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   6550:                         my $adom = $1;
                   6551:                         my $aname = $2;
1.1042    raeburn  6552:                         foreach my $role ('ca','aa') { 
                   6553:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   6554:                                 my ($start,$end) =
                   6555:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   6556:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6557:                                     $ownaccess = 1;
                   6558:                                     last;
                   6559:                                 }
1.1039    raeburn  6560:                             }
                   6561:                         }
                   6562:                     }
                   6563:                 }
                   6564:             }
                   6565:         }
                   6566:     }
                   6567: 
1.52      www      6568: # Course
                   6569: 
1.620     albertel 6570:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6571:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6572:             $thisallowed.=$1;
                   6573:         }
1.52      www      6574:     }
1.29      www      6575: 
1.52      www      6576: # Domain
                   6577: 
1.620     albertel 6578:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 6579:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6580:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6581:             $thisallowed.=$1;
                   6582:         }
1.12      www      6583:     }
1.52      www      6584: 
1.1141    raeburn  6585: # User who is not author or co-author might still be able to edit
                   6586: # resource of an author in the domain (e.g., if Domain Coordinator).
                   6587:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   6588:         (&allowed('mdc',$env{'request.course.id'}))) {
                   6589:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   6590:             $thisallowed.=$1;
                   6591:         }
                   6592:     }
                   6593: 
1.52      www      6594: # Course: uri itself is a course
1.66      www      6595:     my $courseuri=$uri;
                   6596:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      6597:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      6598: 
1.620     albertel 6599:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 6600:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6601:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6602:             $thisallowed.=$1;
                   6603:         }
1.12      www      6604:     }
1.29      www      6605: 
1.665     albertel 6606: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 6607: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 6608:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 6609: 	$thisallowed='';
1.671     raeburn  6610:         my ($match)=&is_on_map($uri);
                   6611:         if ($match) {
                   6612:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   6613:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6614:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6615:                 if (@blockers > 0) {
                   6616:                     $thisallowed = 'B';
                   6617:                 } else {
                   6618:                     $thisallowed.=$1;
                   6619:                 }
1.671     raeburn  6620:             }
                   6621:         } else {
1.705     albertel 6622:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  6623:             if ($refuri) {
                   6624:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  6625:                     $thisallowed='F';
1.671     raeburn  6626:                 } else {
                   6627:                     $refuri=&declutter($refuri);
                   6628:                     my ($match) = &is_on_map($refuri);
                   6629:                     if ($match) {
1.1162    raeburn  6630:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6631:                         if (@blockers > 0) {
                   6632:                             $thisallowed = 'B';
                   6633:                         } else {
                   6634:                             $thisallowed='F';
                   6635:                         }
1.671     raeburn  6636:                     }
1.669     raeburn  6637:                 }
1.671     raeburn  6638:             }
                   6639:         }
1.314     www      6640:     }
1.492     albertel 6641: 
1.766     albertel 6642:     if ($priv eq 'bre'
                   6643: 	&& $thisallowed ne 'F' 
                   6644: 	&& $thisallowed ne '2'
                   6645: 	&& &is_portfolio_url($uri)) {
                   6646: 	$thisallowed = &portfolio_access($uri);
                   6647:     }
                   6648:     
1.52      www      6649: # Full access at system, domain or course-wide level? Exit.
1.29      www      6650:     if ($thisallowed=~/F/) {
                   6651: 	return 'F';
                   6652:     }
                   6653: 
1.52      www      6654: # If this is generating or modifying users, exit with special codes
1.29      www      6655: 
1.643     www      6656:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   6657: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 6658: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      6659: # no author name given, so this just checks on the general right to make a co-author in this domain
                   6660: 	    unless ($auname) { return $thisallowed; }
                   6661: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 6662: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   6663: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   6664: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   6665: 	}
1.52      www      6666: 	return $thisallowed;
                   6667:     }
                   6668: #
1.103     harris41 6669: # Gathered so far: system, domain and course wide privileges
1.52      www      6670: #
                   6671: # Course: See if uri or referer is an individual resource that is part of 
                   6672: # the course
                   6673: 
1.620     albertel 6674:     if ($env{'request.course.id'}) {
1.232     www      6675: 
1.620     albertel 6676:        $courseprivid=$env{'request.course.id'};
                   6677:        if ($env{'request.course.sec'}) {
                   6678:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      6679:        }
                   6680:        $courseprivid=~s/\_/\//;
                   6681:        my $checkreferer=1;
1.232     www      6682:        my ($match,$cond)=&is_on_map($uri);
                   6683:        if ($match) {
                   6684:            $statecond=$cond;
1.620     albertel 6685:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6686:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6687:                my $value = $1;
                   6688:                if ($priv eq 'bre') {
                   6689:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6690:                    if (@blockers > 0) {
                   6691:                        $thisallowed = 'B';
                   6692:                    } else {
                   6693:                        $thisallowed.=$value;
                   6694:                    }
                   6695:                } else {
                   6696:                    $thisallowed.=$value;
                   6697:                }
1.52      www      6698:                $checkreferer=0;
                   6699:            }
1.29      www      6700:        }
1.83      www      6701:        
1.148     www      6702:        if ($checkreferer) {
1.620     albertel 6703: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      6704:             unless ($refuri) {
1.800     albertel 6705:                 foreach my $key (keys(%env)) {
                   6706: 		    if ($key=~/^httpref\..*\*/) {
                   6707: 			my $pattern=$key;
1.156     www      6708:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      6709:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   6710:                         $pattern=~s/\//\\\//g;
1.152     www      6711:                         if ($orguri=~/$pattern/) {
1.800     albertel 6712: 			    $refuri=$env{$key};
1.148     www      6713:                         }
                   6714:                     }
1.191     harris41 6715:                 }
1.148     www      6716:             }
1.232     www      6717: 
1.148     www      6718:          if ($refuri) { 
1.152     www      6719: 	  $refuri=&declutter($refuri);
1.232     www      6720:           my ($match,$cond)=&is_on_map($refuri);
                   6721:             if ($match) {
                   6722:               my $refstatecond=$cond;
1.620     albertel 6723:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6724:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6725:                   my $value = $1;
                   6726:                   if ($priv eq 'bre') {
                   6727:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6728:                       if (@blockers > 0) {
                   6729:                           $thisallowed = 'B';
                   6730:                       } else {
                   6731:                           $thisallowed.=$value;
                   6732:                       }
                   6733:                   } else {
                   6734:                       $thisallowed.=$value;
                   6735:                   }
1.53      www      6736:                   $uri=$refuri;
                   6737:                   $statecond=$refstatecond;
1.52      www      6738:               }
                   6739:           }
1.148     www      6740:         }
1.29      www      6741:        }
1.52      www      6742:    }
1.29      www      6743: 
1.52      www      6744: #
1.103     harris41 6745: # Gathered now: all privileges that could apply, and condition number
1.52      www      6746: # 
                   6747: #
                   6748: # Full or no access?
                   6749: #
1.29      www      6750: 
1.52      www      6751:     if ($thisallowed=~/F/) {
                   6752: 	return 'F';
                   6753:     }
1.29      www      6754: 
1.52      www      6755:     unless ($thisallowed) {
                   6756:         return '';
                   6757:     }
1.29      www      6758: 
1.52      www      6759: # Restrictions exist, deal with them
                   6760: #
                   6761: #   C:according to course preferences
                   6762: #   R:according to resource settings
                   6763: #   L:unless locked
                   6764: #   X:according to user session state
                   6765: #
                   6766: 
                   6767: # Possibly locked functionality, check all courses
1.54      www      6768: # Locks might take effect only after 10 minutes cache expiration for other
                   6769: # courses, and 2 minutes for current course
1.52      www      6770: 
                   6771:     my $envkey;
                   6772:     if ($thisallowed=~/L/) {
1.1000    raeburn  6773:         foreach $envkey (keys(%env)) {
1.54      www      6774:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   6775:                my $courseid=$2;
                   6776:                my $roleid=$1.'.'.$2;
1.92      www      6777:                $courseid=~s/^\///;
1.54      www      6778:                my $expiretime=600;
1.620     albertel 6779:                if ($env{'request.role'} eq $roleid) {
1.54      www      6780: 		  $expiretime=120;
                   6781:                }
                   6782: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   6783:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 6784:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 6785: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      6786:                }
1.620     albertel 6787:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6788:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   6789: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   6790:                        &log($env{'user.domain'},$env{'user.name'},
                   6791:                             $env{'user.home'},
1.57      www      6792:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      6793:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6794:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6795: 		       return '';
                   6796:                    }
                   6797:                }
1.620     albertel 6798:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6799:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   6800: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   6801:                        &log($env{'user.domain'},$env{'user.name'},
                   6802:                             $env{'user.home'},
1.57      www      6803:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      6804:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6805:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6806: 		       return '';
                   6807:                    }
                   6808:                }
                   6809: 	   }
1.29      www      6810:        }
1.52      www      6811:     }
                   6812:    
                   6813: #
                   6814: # Rest of the restrictions depend on selected course
                   6815: #
                   6816: 
1.620     albertel 6817:     unless ($env{'request.course.id'}) {
1.766     albertel 6818: 	if ($thisallowed eq 'A') {
                   6819: 	    return 'A';
1.814     raeburn  6820:         } elsif ($thisallowed eq 'B') {
                   6821:             return 'B';
1.766     albertel 6822: 	} else {
                   6823: 	    return '1';
                   6824: 	}
1.52      www      6825:     }
1.29      www      6826: 
1.52      www      6827: #
                   6828: # Now user is definitely in a course
                   6829: #
1.53      www      6830: 
                   6831: 
                   6832: # Course preferences
                   6833: 
                   6834:    if ($thisallowed=~/C/) {
1.620     albertel 6835:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   6836:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   6837:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 6838: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  6839: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6840: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6841: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   6842: 			$env{'request.course.id'});
                   6843: 	   }
1.237     www      6844:            return '';
                   6845:        }
                   6846: 
1.620     albertel 6847:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 6848: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  6849: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6850: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   6851: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   6852: 			$env{'request.course.id'});
                   6853: 	   }
1.54      www      6854:            return '';
                   6855:        }
1.53      www      6856:    }
                   6857: 
                   6858: # Resource preferences
                   6859: 
                   6860:    if ($thisallowed=~/R/) {
1.620     albertel 6861:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 6862:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  6863: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6864: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6865: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   6866: 	   }
                   6867: 	   return '';
1.54      www      6868:        }
1.53      www      6869:    }
1.30      www      6870: 
1.246     www      6871: # Restricted by state or randomout?
1.30      www      6872: 
1.52      www      6873:    if ($thisallowed=~/X/) {
1.620     albertel 6874:       if ($env{'acc.randomout'}) {
1.579     albertel 6875: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 6876:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      6877:             return ''; 
                   6878:          }
1.247     www      6879:       }
                   6880:       if (&condval($statecond)) {
1.52      www      6881: 	 return '2';
                   6882:       } else {
                   6883:          return '';
                   6884:       }
                   6885:    }
1.30      www      6886: 
1.766     albertel 6887:     if ($thisallowed eq 'A') {
                   6888: 	return 'A';
1.814     raeburn  6889:     } elsif ($thisallowed eq 'B') {
                   6890:         return 'B';
1.766     albertel 6891:     }
1.52      www      6892:    return 'F';
1.232     www      6893: }
1.1162    raeburn  6894: 
1.1172.2.13  raeburn  6895: # ------------------------------------------- Check construction space access
                   6896: 
                   6897: sub constructaccess {
                   6898:     my ($url,$setpriv)=@_;
                   6899: 
                   6900: # We do not allow editing of previous versions of files
                   6901:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   6902: 
                   6903: # Get username and domain from URL
                   6904:     my ($ownername,$ownerdomain,$ownerhome);
                   6905: 
                   6906:     ($ownerdomain,$ownername) =
                   6907:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
                   6908: 
                   6909: # The URL does not really point to any authorspace, forget it
                   6910:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   6911: 
                   6912: # Now we need to see if the user has access to the authorspace of
                   6913: # $ownername at $ownerdomain
                   6914: 
                   6915:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   6916: # Real author for this?
                   6917:        $ownerhome = $env{'user.home'};
                   6918:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   6919:           return ($ownername,$ownerdomain,$ownerhome);
                   6920:        }
                   6921:     } else {
                   6922: # Co-author for this?
                   6923:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   6924:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   6925:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   6926:             return ($ownername,$ownerdomain,$ownerhome);
                   6927:         }
                   6928:     }
                   6929: 
                   6930: # We don't have any access right now. If we are not possibly going to do anything about this,
                   6931: # we might as well leave
                   6932:    unless ($setpriv) { return ''; }
                   6933: 
                   6934: # Backdoor access?
                   6935:     my $allowed=&allowed('eco',$ownerdomain);
                   6936: # Nope
                   6937:     unless ($allowed) { return ''; }
                   6938: # Looks like we may have access, but could be locked by the owner of the construction space
                   6939:     if ($allowed eq 'U') {
                   6940:         my %blocked=&get('environment',['domcoord.author'],
                   6941:                          $ownerdomain,$ownername);
                   6942: # Is blocked by owner
                   6943:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   6944:     }
                   6945:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   6946: # Grant temporary access
                   6947:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  6948:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  6949:         if (!$update) { $update = $then; }
                   6950:         my $refresh=$env{'user.refresh.time'};
                   6951:         if (!$refresh) { $refresh = $update; }
                   6952:         my $now = time;
                   6953:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   6954:                            $now,'ca','constructaccess');
                   6955:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   6956:         return($ownername,$ownerdomain,$ownerhome);
                   6957:     }
                   6958: # No business here
                   6959:     return '';
                   6960: }
                   6961: 
1.1162    raeburn  6962: sub get_comm_blocks {
                   6963:     my ($cdom,$cnum) = @_;
                   6964:     if ($cdom eq '' || $cnum eq '') {
                   6965:         return unless ($env{'request.course.id'});
                   6966:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6967:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6968:     }
                   6969:     my %commblocks;
                   6970:     my $hashid=$cdom.'_'.$cnum;
                   6971:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   6972:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   6973:         %commblocks = %{$blocksref};
                   6974:     } else {
                   6975:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   6976:         my $cachetime = 600;
                   6977:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   6978:     }
                   6979:     return %commblocks;
                   6980: }
                   6981: 
                   6982: sub has_comm_blocking {
                   6983:     my ($priv,$symb,$uri,$blocks) = @_;
                   6984:     return unless ($env{'request.course.id'});
                   6985:     return unless ($priv eq 'bre');
                   6986:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   6987:     my %commblocks;
                   6988:     if (ref($blocks) eq 'HASH') {
                   6989:         %commblocks = %{$blocks};
                   6990:     } else {
                   6991:         %commblocks = &get_comm_blocks();
                   6992:     }
                   6993:     return unless (keys(%commblocks) > 0);
                   6994:     if (!$symb) { $symb=&symbread($uri,1); }
                   6995:     my ($map,$resid,undef)=&decode_symb($symb);
                   6996:     my %tocheck = (
                   6997:                     maps      => $map,
                   6998:                     resources => $symb,
                   6999:                   );
                   7000:     my @blockers;
                   7001:     my $now = time;
1.1163    raeburn  7002:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1162    raeburn  7003:     foreach my $block (keys(%commblocks)) {
                   7004:         if ($block =~ /^(\d+)____(\d+)$/) {
                   7005:             my ($start,$end) = ($1,$2);
                   7006:             if ($start <= $now && $end >= $now) {
                   7007:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7008:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7009:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   7010:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
                   7011:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   7012:                                     push(@blockers,$block);
                   7013:                                 }
                   7014:                             }
                   7015:                         }
                   7016:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   7017:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
                   7018:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
                   7019:                                     push(@blockers,$block);
                   7020:                                 }
                   7021:                             }
                   7022:                         }
                   7023:                     }
                   7024:                 }
                   7025:             }
                   7026:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   7027:             my $item = $1;
1.1163    raeburn  7028:             my @to_test;
1.1162    raeburn  7029:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7030:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7031:                     my $check_interval;
                   7032:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
                   7033:                         my @interval;
                   7034:                         my $type = 'map';
                   7035:                         if ($item eq 'course') {
                   7036:                             $type = 'course';
                   7037:                             @interval=&EXT("resource.0.interval");
                   7038:                         } else {
                   7039:                             if ($item =~ /___\d+___/) {
                   7040:                                 $type = 'resource';
                   7041:                                 @interval=&EXT("resource.0.interval",$item);
1.1163    raeburn  7042:                                 if (ref($navmap)) {                        
                   7043:                                     my $res = $navmap->getBySymb($item); 
                   7044:                                     push(@to_test,$res);
                   7045:                                 }
1.1162    raeburn  7046:                             } else {
                   7047:                                 my $mapsymb = &symbread($item,1);
                   7048:                                 if ($mapsymb) {
                   7049:                                     if (ref($navmap)) {
                   7050:                                         my $mapres = $navmap->getBySymb($mapsymb);
1.1163    raeburn  7051:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
                   7052:                                         foreach my $res (@to_test) {
1.1162    raeburn  7053:                                             my $symb = $res->symb();
                   7054:                                             next if ($symb eq $mapsymb);
                   7055:                                             if ($symb ne '') {
                   7056:                                                 @interval=&EXT("resource.0.interval",$symb);
                   7057:                                                 last;
                   7058:                                             }
                   7059:                                         }
                   7060:                                     }
                   7061:                                 }
                   7062:                             }
                   7063:                         }
                   7064:                         if ($interval[0] =~ /\d+/) {
                   7065:                             my $first_access;
                   7066:                             if ($type eq 'resource') {
                   7067:                                 $first_access=&get_first_access($interval[1],$item);
                   7068:                             } elsif ($type eq 'map') {
                   7069:                                 $first_access=&get_first_access($interval[1],undef,$item);
                   7070:                             } else {
                   7071:                                 $first_access=&get_first_access($interval[1]);
                   7072:                             }
                   7073:                             if ($first_access) {
                   7074:                                 my $timesup = $first_access+$interval[0];
                   7075:                                 if ($timesup > $now) {
1.1163    raeburn  7076:                                     foreach my $res (@to_test) {
                   7077:                                         if ($res->is_problem()) {
                   7078:                                             if ($res->completable()) {
                   7079:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   7080:                                                     push(@blockers,$block);
                   7081:                                                 }
                   7082:                                                 last;
                   7083:                                             }
                   7084:                                         }
1.1162    raeburn  7085:                                     }
                   7086:                                 }
                   7087:                             }
                   7088:                         }
                   7089:                     }
                   7090:                 }
                   7091:             }
                   7092:         }
                   7093:     }
                   7094:     return @blockers;
                   7095: }
                   7096: 
                   7097: sub check_docs_block {
                   7098:     my ($docsblock,$tocheck) =@_;
                   7099:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
                   7100:         return;
                   7101:     }
                   7102:     if (ref($docsblock->{'maps'}) eq 'HASH') {
                   7103:         if ($tocheck->{'maps'}) {
                   7104:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
                   7105:                 return 1;
                   7106:             }
                   7107:         }
                   7108:     }
                   7109:     if (ref($docsblock->{'resources'}) eq 'HASH') {
                   7110:         if ($tocheck->{'resources'}) {
                   7111:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
                   7112:                 return 1;
                   7113:             }
                   7114:         }
                   7115:     }
                   7116:     return;
                   7117: }
                   7118: 
1.1133    foxr     7119: #
                   7120: #   Removes the versino from a URI and
                   7121: #   splits it in to its filename and path to the filename.
                   7122: #   Seems like File::Basename could have done this more clearly.
                   7123: #   Parameters:
                   7124: #      $uri   - input URI
                   7125: #   Returns:
                   7126: #     Two element list consisting of 
                   7127: #     $pathname  - the URI up to and excluding the trailing /
                   7128: #     $filename  - The part of the URI following the last /
                   7129: #  NOTE:
                   7130: #    Another realization of this is simply:
                   7131: #    use File::Basename;
                   7132: #    ...
                   7133: #    $uri = shift;
                   7134: #    $filename = basename($uri);
                   7135: #    $path     = dirname($uri);
                   7136: #    return ($filename, $path);
                   7137: #
                   7138: #     The implementation below is probably faster however.
                   7139: #
1.710     albertel 7140: sub split_uri_for_cond {
                   7141:     my $uri=&deversion(&declutter(shift));
                   7142:     my @uriparts=split(/\//,$uri);
                   7143:     my $filename=pop(@uriparts);
                   7144:     my $pathname=join('/',@uriparts);
                   7145:     return ($pathname,$filename);
                   7146: }
1.232     www      7147: # --------------------------------------------------- Is a resource on the map?
                   7148: 
                   7149: sub is_on_map {
1.710     albertel 7150:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 7151:     #Trying to find the conditional for the file
1.620     albertel 7152:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 7153: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      7154:     if ($match) {
1.289     bowersj2 7155: 	return (1,$1);
                   7156:     } else {
1.434     www      7157: 	return (0,0);
1.289     bowersj2 7158:     }
1.12      www      7159: }
                   7160: 
1.427     www      7161: # --------------------------------------------------------- Get symb from alias
                   7162: 
                   7163: sub get_symb_from_alias {
                   7164:     my $symb=shift;
                   7165:     my ($map,$resid,$url)=&decode_symb($symb);
                   7166: # Already is a symb
                   7167:     if ($url) { return $symb; }
                   7168: # Must be an alias
                   7169:     my $aliassymb='';
                   7170:     my %bighash;
1.620     albertel 7171:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      7172:                             &GDBM_READER(),0640)) {
                   7173:         my $rid=$bighash{'mapalias_'.$symb};
                   7174: 	if ($rid) {
                   7175: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 7176: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   7177: 				    $resid,$bighash{'src_'.$rid});
1.427     www      7178: 	}
                   7179:         untie %bighash;
                   7180:     }
                   7181:     return $aliassymb;
                   7182: }
                   7183: 
1.12      www      7184: # ----------------------------------------------------------------- Define Role
                   7185: 
                   7186: sub definerole {
                   7187:   if (allowed('mcr','/')) {
                   7188:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 7189:     foreach my $role (split(':',$sysrole)) {
                   7190: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7191:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   7192:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   7193: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7194:                return "refused:s:$crole&$cqual"; 
                   7195:             }
                   7196:         }
1.191     harris41 7197:     }
1.800     albertel 7198:     foreach my $role (split(':',$domrole)) {
                   7199: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7200:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   7201:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   7202: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      7203:                return "refused:d:$crole&$cqual"; 
                   7204:             }
                   7205:         }
1.191     harris41 7206:     }
1.800     albertel 7207:     foreach my $role (split(':',$courole)) {
                   7208: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7209:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   7210:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   7211: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7212:                return "refused:c:$crole&$cqual"; 
                   7213:             }
                   7214:         }
1.191     harris41 7215:     }
1.620     albertel 7216:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   7217:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7218: 	        "rolesdef_$rolename=".
                   7219:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 7220:     return reply($command,$env{'user.home'});
1.12      www      7221:   } else {
                   7222:     return 'refused';
                   7223:   }
1.105     harris41 7224: }
                   7225: 
                   7226: # ---------------- Make a metadata query against the network of library servers
                   7227: 
                   7228: sub metadata_query {
1.244     matthew  7229:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 7230:     my %rhash;
1.845     albertel 7231:     my %libserv = &all_library();
1.244     matthew  7232:     my @server_list = (defined($server_array) ? @$server_array
                   7233:                                               : keys(%libserv) );
                   7234:     for my $server (@server_list) {
1.118     harris41 7235: 	unless ($custom or $customshow) {
                   7236: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   7237: 	    $rhash{$server}=$reply;
                   7238: 	}
                   7239: 	else {
                   7240: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   7241: 			     &escape($custom).':'.&escape($customshow),
                   7242: 			     $server);
                   7243: 	    $rhash{$server}=$reply;
                   7244: 	}
1.112     harris41 7245:     }
1.118     harris41 7246:     return \%rhash;
1.240     www      7247: }
                   7248: 
                   7249: # ----------------------------------------- Send log queries and wait for reply
                   7250: 
                   7251: sub log_query {
                   7252:     my ($uname,$udom,$query,%filters)=@_;
                   7253:     my $uhome=&homeserver($uname,$udom);
                   7254:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 7255:     my $uhost=&hostname($uhome);
1.800     albertel 7256:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      7257:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   7258:                        $uhome);
1.479     albertel 7259:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      7260:     return get_query_reply($queryid);
                   7261: }
                   7262: 
1.818     raeburn  7263: # -------------------------- Update MySQL table for portfolio file
                   7264: 
                   7265: sub update_portfolio_table {
1.821     raeburn  7266:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  7267:     if ($group ne '') {
                   7268:         $file_name =~s /^\Q$group\E//;
                   7269:     }
1.818     raeburn  7270:     my $homeserver = &homeserver($uname,$udom);
                   7271:     my $queryid=
1.821     raeburn  7272:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   7273:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  7274:     my $reply = &get_query_reply($queryid);
                   7275:     return $reply;
                   7276: }
                   7277: 
1.899     raeburn  7278: # -------------------------- Update MySQL allusers table
                   7279: 
                   7280: sub update_allusers_table {
                   7281:     my ($uname,$udom,$names) = @_;
                   7282:     my $homeserver = &homeserver($uname,$udom);
                   7283:     my $queryid=
                   7284:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   7285:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   7286:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   7287:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   7288:                'generation='.&escape($names->{'generation'}).'%%'.
                   7289:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   7290:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  7291:     return;
1.899     raeburn  7292: }
                   7293: 
1.508     raeburn  7294: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  7295: 
                   7296: sub fetch_enrollment_query {
1.511     raeburn  7297:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  7298:     my $homeserver;
1.547     raeburn  7299:     my $maxtries = 1;
1.508     raeburn  7300:     if ($context eq 'automated') {
                   7301:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  7302:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  7303:     } else {
                   7304:         $homeserver = &homeserver($cnum,$dom);
                   7305:     }
1.838     albertel 7306:     my $host=&hostname($homeserver);
1.506     raeburn  7307:     my $cmd = '';
1.1000    raeburn  7308:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 7309:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  7310:     }
                   7311:     $cmd =~ s/%%$//;
                   7312:     $cmd = &escape($cmd);
                   7313:     my $query = 'fetchenrollment';
1.620     albertel 7314:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  7315:     unless ($queryid=~/^\Q$host\E\_/) { 
                   7316:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   7317:         return 'error: '.$queryid;
                   7318:     }
1.506     raeburn  7319:     my $reply = &get_query_reply($queryid);
1.547     raeburn  7320:     my $tries = 1;
                   7321:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7322:         $reply = &get_query_reply($queryid);
                   7323:         $tries ++;
                   7324:     }
1.526     raeburn  7325:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 7326:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  7327:     } else {
1.901     albertel 7328:         my @responses = split(/:/,$reply);
1.515     raeburn  7329:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 7330:             foreach my $line (@responses) {
                   7331:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  7332:                 $$replyref{$key} = $value;
                   7333:             }
                   7334:         } else {
1.1117    foxr     7335:             my $pathname = LONCAPA::tempdir();
1.800     albertel 7336:             foreach my $line (@responses) {
                   7337:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  7338:                 $$replyref{$key} = $value;
                   7339:                 if ($value > 0) {
1.800     albertel 7340:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   7341:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  7342:                         my $destname = $pathname.'/'.$filename;
                   7343:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  7344:                         if ($xml_classlist =~ /^error/) {
                   7345:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   7346:                         } else {
1.506     raeburn  7347:                             if ( open(FILE,">$destname") ) {
                   7348:                                 print FILE &unescape($xml_classlist);
                   7349:                                 close(FILE);
1.526     raeburn  7350:                             } else {
                   7351:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  7352:                             }
                   7353:                         }
                   7354:                     }
                   7355:                 }
                   7356:             }
                   7357:         }
                   7358:         return 'ok';
                   7359:     }
                   7360:     return 'error';
                   7361: }
                   7362: 
1.242     www      7363: sub get_query_reply {
                   7364:     my $queryid=shift;
1.1117    foxr     7365:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      7366:     my $reply='';
                   7367:     for (1..100) {
                   7368: 	sleep 2;
                   7369:         if (-e $replyfile.'.end') {
1.448     albertel 7370: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 7371: 		$reply = join('',<$fh>);
                   7372: 		close($fh);
1.240     www      7373: 	   } else { return 'error: reply_file_error'; }
1.242     www      7374:            return &unescape($reply);
                   7375: 	}
1.240     www      7376:     }
1.242     www      7377:     return 'timeout:'.$queryid;
1.240     www      7378: }
                   7379: 
                   7380: sub courselog_query {
1.241     www      7381: #
                   7382: # possible filters:
                   7383: # url: url or symb
                   7384: # username
                   7385: # domain
                   7386: # action: view, submit, grade
                   7387: # start: timestamp
                   7388: # end: timestamp
                   7389: #
1.240     www      7390:     my (%filters)=@_;
1.620     albertel 7391:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      7392:     if ($filters{'url'}) {
                   7393: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   7394:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   7395:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   7396:     }
1.620     albertel 7397:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7398:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      7399:     return &log_query($cname,$cdom,'courselog',%filters);
                   7400: }
                   7401: 
                   7402: sub userlog_query {
1.858     raeburn  7403: #
                   7404: # possible filters:
                   7405: # action: log check role
                   7406: # start: timestamp
                   7407: # end: timestamp
                   7408: #
1.240     www      7409:     my ($uname,$udom,%filters)=@_;
                   7410:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      7411: }
                   7412: 
1.506     raeburn  7413: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   7414: 
                   7415: sub auto_run {
1.508     raeburn  7416:     my ($cnum,$cdom) = @_;
1.876     raeburn  7417:     my $response = 0;
                   7418:     my $settings;
                   7419:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   7420:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   7421:         $settings = $domconfig{'autoenroll'};
                   7422:         if ($settings->{'run'} eq '1') {
                   7423:             $response = 1;
                   7424:         }
                   7425:     } else {
1.934     raeburn  7426:         my $homeserver;
                   7427:         if (&is_course($cdom,$cnum)) {
                   7428:             $homeserver = &homeserver($cnum,$cdom);
                   7429:         } else {
                   7430:             $homeserver = &domain($cdom,'primary');
                   7431:         }
                   7432:         if ($homeserver ne 'no_host') {
                   7433:             $response = &reply('autorun:'.$cdom,$homeserver);
                   7434:         }
1.876     raeburn  7435:     }
1.506     raeburn  7436:     return $response;
                   7437: }
1.776     albertel 7438: 
1.506     raeburn  7439: sub auto_get_sections {
1.508     raeburn  7440:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  7441:     my $homeserver;
                   7442:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   7443:         $homeserver = &homeserver($cnum,$cdom);
                   7444:     }
                   7445:     if (!defined($homeserver)) { 
                   7446:         if ($cdom =~ /^$match_domain$/) {
                   7447:             $homeserver = &domain($cdom,'primary');
                   7448:         }
                   7449:     }
                   7450:     my @secs;
                   7451:     if (defined($homeserver)) {
                   7452:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   7453:         unless ($response eq 'refused') {
                   7454:             @secs = split(/:/,$response);
                   7455:         }
1.506     raeburn  7456:     }
                   7457:     return @secs;
                   7458: }
1.776     albertel 7459: 
1.506     raeburn  7460: sub auto_new_course {
1.1099    raeburn  7461:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  7462:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  7463:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  7464:     return $response;
                   7465: }
1.776     albertel 7466: 
1.506     raeburn  7467: sub auto_validate_courseID {
1.508     raeburn  7468:     my ($cnum,$cdom,$inst_course_id) = @_;
                   7469:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  7470:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  7471:     return $response;
                   7472: }
1.776     albertel 7473: 
1.1007    raeburn  7474: sub auto_validate_instcode {
1.1020    raeburn  7475:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  7476:     my ($homeserver,$response);
                   7477:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7478:         $homeserver = &homeserver($cnum,$cdom);
                   7479:     }
                   7480:     if (!defined($homeserver)) {
                   7481:         if ($cdom =~ /^$match_domain$/) {
                   7482:             $homeserver = &domain($cdom,'primary');
                   7483:         }
                   7484:     }
1.1065    raeburn  7485:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   7486:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  7487:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   7488:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  7489: }
                   7490: 
1.506     raeburn  7491: sub auto_create_password {
1.873     raeburn  7492:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   7493:     my ($homeserver,$response);
1.506     raeburn  7494:     my $create_passwd = 0;
                   7495:     my $authchk = '';
1.873     raeburn  7496:     if ($udom =~ /^$match_domain$/) {
                   7497:         $homeserver = &domain($udom,'primary');
                   7498:     }
                   7499:     if ($homeserver eq '') {
                   7500:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7501:             $homeserver = &homeserver($cnum,$cdom);
                   7502:         }
                   7503:     }
                   7504:     if ($homeserver eq '') {
                   7505:         $authchk = 'nodomain';
1.506     raeburn  7506:     } else {
1.873     raeburn  7507:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   7508:         if ($response eq 'refused') {
                   7509:             $authchk = 'refused';
                   7510:         } else {
1.901     albertel 7511:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  7512:         }
1.506     raeburn  7513:     }
                   7514:     return ($authparam,$create_passwd,$authchk);
                   7515: }
                   7516: 
1.706     raeburn  7517: sub auto_photo_permission {
                   7518:     my ($cnum,$cdom,$students) = @_;
                   7519:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 7520:     my ($outcome,$perm_reqd,$conditions) = 
                   7521: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 7522:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7523: 	return (undef,undef);
                   7524:     }
1.706     raeburn  7525:     return ($outcome,$perm_reqd,$conditions);
                   7526: }
                   7527: 
                   7528: sub auto_checkphotos {
                   7529:     my ($uname,$udom,$pid) = @_;
                   7530:     my $homeserver = &homeserver($uname,$udom);
                   7531:     my ($result,$resulttype);
                   7532:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 7533: 				   &escape($uname).':'.&escape($pid),
                   7534: 				   $homeserver));
1.709     albertel 7535:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7536: 	return (undef,undef);
                   7537:     }
1.706     raeburn  7538:     if ($outcome) {
                   7539:         ($result,$resulttype) = split(/:/,$outcome);
                   7540:     } 
                   7541:     return ($result,$resulttype);
                   7542: }
                   7543: 
                   7544: sub auto_photochoice {
                   7545:     my ($cnum,$cdom) = @_;
                   7546:     my $homeserver = &homeserver($cnum,$cdom);
                   7547:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 7548: 						       &escape($cdom),
                   7549: 						       $homeserver)));
1.709     albertel 7550:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7551: 	return (undef,undef);
                   7552:     }
1.706     raeburn  7553:     return ($update,$comment);
                   7554: }
                   7555: 
                   7556: sub auto_photoupdate {
                   7557:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   7558:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 7559:     my $host=&hostname($homeserver);
1.706     raeburn  7560:     my $cmd = '';
                   7561:     my $maxtries = 1;
1.800     albertel 7562:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   7563:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  7564:     }
                   7565:     $cmd =~ s/%%$//;
                   7566:     $cmd = &escape($cmd);
                   7567:     my $query = 'institutionalphotos';
                   7568:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   7569:     unless ($queryid=~/^\Q$host\E\_/) {
                   7570:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   7571:         return 'error: '.$queryid;
                   7572:     }
                   7573:     my $reply = &get_query_reply($queryid);
                   7574:     my $tries = 1;
                   7575:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7576:         $reply = &get_query_reply($queryid);
                   7577:         $tries ++;
                   7578:     }
                   7579:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   7580:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   7581:     } else {
                   7582:         my @responses = split(/:/,$reply);
                   7583:         my $outcome = shift(@responses); 
                   7584:         foreach my $item (@responses) {
                   7585:             my ($key,$value) = split(/=/,$item);
                   7586:             $$photo{$key} = $value;
                   7587:         }
                   7588:         return $outcome;
                   7589:     }
                   7590:     return 'error';
                   7591: }
                   7592: 
1.521     raeburn  7593: sub auto_instcode_format {
1.793     albertel 7594:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   7595: 	$cat_order) = @_;
1.521     raeburn  7596:     my $courses = '';
1.772     raeburn  7597:     my @homeservers;
1.521     raeburn  7598:     if ($caller eq 'global') {
1.841     albertel 7599: 	my %servers = &get_servers($codedom,'library');
                   7600: 	foreach my $tryserver (keys(%servers)) {
                   7601: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7602: 		push(@homeservers,$tryserver);
                   7603: 	    }
1.584     raeburn  7604:         }
1.1022    raeburn  7605:     } elsif ($caller eq 'requests') {
                   7606:         if ($codedom =~ /^$match_domain$/) {
                   7607:             my $chome = &domain($codedom,'primary');
                   7608:             unless ($chome eq 'no_host') {
                   7609:                 push(@homeservers,$chome);
                   7610:             }
                   7611:         }
1.521     raeburn  7612:     } else {
1.772     raeburn  7613:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  7614:     }
1.793     albertel 7615:     foreach my $code (keys(%{$instcodes})) {
                   7616:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  7617:     }
                   7618:     chop($courses);
1.772     raeburn  7619:     my $ok_response = 0;
                   7620:     my $response;
                   7621:     while (@homeservers > 0 && $ok_response == 0) {
                   7622:         my $server = shift(@homeservers); 
                   7623:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   7624:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   7625:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 7626: 		split(/:/,$response);
1.772     raeburn  7627:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   7628:             push(@{$codetitles},&str2array($codetitles_str));
                   7629:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   7630:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   7631:             $ok_response = 1;
                   7632:         }
                   7633:     }
                   7634:     if ($ok_response) {
1.521     raeburn  7635:         return 'ok';
1.772     raeburn  7636:     } else {
                   7637:         return $response;
1.521     raeburn  7638:     }
                   7639: }
                   7640: 
1.792     raeburn  7641: sub auto_instcode_defaults {
                   7642:     my ($domain,$returnhash,$code_order) = @_;
                   7643:     my @homeservers;
1.841     albertel 7644: 
                   7645:     my %servers = &get_servers($domain,'library');
                   7646:     foreach my $tryserver (keys(%servers)) {
                   7647: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7648: 	    push(@homeservers,$tryserver);
                   7649: 	}
1.792     raeburn  7650:     }
1.841     albertel 7651: 
1.792     raeburn  7652:     my $response;
1.841     albertel 7653:     foreach my $server (@homeservers) {
1.792     raeburn  7654:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 7655:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   7656: 	
                   7657: 	foreach my $pair (split(/\&/,$response)) {
                   7658: 	    my ($name,$value)=split(/\=/,$pair);
                   7659: 	    if ($name eq 'code_order') {
                   7660: 		@{$code_order} = split(/\&/,&unescape($value));
                   7661: 	    } else {
                   7662: 		$returnhash->{&unescape($name)}=&unescape($value);
                   7663: 	    }
                   7664: 	}
                   7665: 	return 'ok';
1.792     raeburn  7666:     }
1.841     albertel 7667: 
                   7668:     return $response;
1.1003    raeburn  7669: }
                   7670: 
                   7671: sub auto_possible_instcodes {
1.1007    raeburn  7672:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   7673:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   7674:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   7675:         return;
                   7676:     }
1.1003    raeburn  7677:     my (@homeservers,$uhome);
                   7678:     if (defined(&domain($domain,'primary'))) {
                   7679:         $uhome=&domain($domain,'primary');
                   7680:         push(@homeservers,&domain($domain,'primary'));
                   7681:     } else {
                   7682:         my %servers = &get_servers($domain,'library');
                   7683:         foreach my $tryserver (keys(%servers)) {
                   7684:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7685:                 push(@homeservers,$tryserver);
                   7686:             }
                   7687:         }
                   7688:     }
                   7689:     my $response;
                   7690:     foreach my $server (@homeservers) {
                   7691:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   7692:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  7693:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   7694:             split(':',$response);
                   7695:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   7696:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  7697:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  7698:             my ($name,$value)=split('=',$item);
                   7699:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7700:         }
                   7701:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  7702:             my ($name,$value)=split('=',$item);
                   7703:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7704:         }
                   7705:         return 'ok';
                   7706:     }
                   7707:     return $response;
                   7708: }
1.792     raeburn  7709: 
1.1010    raeburn  7710: sub auto_courserequest_checks {
                   7711:     my ($dom) = @_;
1.1020    raeburn  7712:     my ($homeserver,%validations);
                   7713:     if ($dom =~ /^$match_domain$/) {
                   7714:         $homeserver = &domain($dom,'primary');
                   7715:     }
                   7716:     unless ($homeserver eq 'no_host') {
                   7717:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   7718:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   7719:             my @items = split(/&/,$response);
                   7720:             foreach my $item (@items) {
                   7721:                 my ($key,$value) = split('=',$item);
                   7722:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   7723:             }
                   7724:         }
                   7725:     }
1.1010    raeburn  7726:     return %validations; 
                   7727: }
                   7728: 
1.1020    raeburn  7729: sub auto_courserequest_validation {
                   7730:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   7731:     my ($homeserver,$response);
                   7732:     if ($dom =~ /^$match_domain$/) {
                   7733:         $homeserver = &domain($dom,'primary');
                   7734:     }
                   7735:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  7736:           
1.1020    raeburn  7737:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  7738:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  7739:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   7740:                                     $homeserver));
                   7741:     }
                   7742:     return $response;
                   7743: }
                   7744: 
1.777     albertel 7745: sub auto_validate_class_sec {
1.918     raeburn  7746:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  7747:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  7748:     my $ownerlist;
                   7749:     if (ref($owners) eq 'ARRAY') {
                   7750:         $ownerlist = join(',',@{$owners});
                   7751:     } else {
                   7752:         $ownerlist = $owners;
                   7753:     }
1.773     raeburn  7754:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  7755:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  7756:     return $response;
                   7757: }
                   7758: 
1.679     raeburn  7759: # ------------------------------------------------------- Course Group routines
                   7760: 
                   7761: sub get_coursegroups {
1.809     raeburn  7762:     my ($cdom,$cnum,$group,$namespace) = @_;
                   7763:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  7764: }
                   7765: 
1.679     raeburn  7766: sub modify_coursegroup {
                   7767:     my ($cdom,$cnum,$groupsettings) = @_;
                   7768:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   7769: }
                   7770: 
1.809     raeburn  7771: sub toggle_coursegroup_status {
                   7772:     my ($cdom,$cnum,$group,$action) = @_;
                   7773:     my ($from_namespace,$to_namespace);
                   7774:     if ($action eq 'delete') {
                   7775:         $from_namespace = 'coursegroups';
                   7776:         $to_namespace = 'deleted_groups';
                   7777:     } else {
                   7778:         $from_namespace = 'deleted_groups';
                   7779:         $to_namespace = 'coursegroups';
                   7780:     }
                   7781:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  7782:     if (my $tmp = &error(%curr_group)) {
                   7783:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   7784:         return ('read error',$tmp);
                   7785:     } else {
                   7786:         my %savedsettings = %curr_group; 
1.809     raeburn  7787:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  7788:         my $deloutcome;
                   7789:         if ($result eq 'ok') {
1.809     raeburn  7790:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  7791:         } else {
                   7792:             return ('write error',$result);
                   7793:         }
                   7794:         if ($deloutcome eq 'ok') {
                   7795:             return 'ok';
                   7796:         } else {
                   7797:             return ('delete error',$deloutcome);
                   7798:         }
                   7799:     }
                   7800: }
                   7801: 
1.679     raeburn  7802: sub modify_group_roles {
1.957     raeburn  7803:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  7804:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   7805:     my $role = 'gr/'.&escape($userprivs);
                   7806:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  7807:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  7808:     if ($result eq 'ok') {
                   7809:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   7810:     }
1.679     raeburn  7811:     return $result;
                   7812: }
                   7813: 
                   7814: sub modify_coursegroup_membership {
                   7815:     my ($cdom,$cnum,$membership) = @_;
                   7816:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   7817:     return $result;
                   7818: }
                   7819: 
1.682     raeburn  7820: sub get_active_groups {
                   7821:     my ($udom,$uname,$cdom,$cnum) = @_;
                   7822:     my $now = time;
                   7823:     my %groups = ();
                   7824:     foreach my $key (keys(%env)) {
1.811     albertel 7825:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  7826:             my ($start,$end) = split(/\./,$env{$key});
                   7827:             if (($end!=0) && ($end<$now)) { next; }
                   7828:             if (($start!=0) && ($start>$now)) { next; }
                   7829:             if ($1 eq $cdom && $2 eq $cnum) {
                   7830:                 $groups{$3} = $env{$key} ;
                   7831:             }
                   7832:         }
                   7833:     }
                   7834:     return %groups;
                   7835: }
                   7836: 
1.683     raeburn  7837: sub get_group_membership {
                   7838:     my ($cdom,$cnum,$group) = @_;
                   7839:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   7840: }
                   7841: 
                   7842: sub get_users_groups {
                   7843:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  7844:     my @usersgroups;
1.683     raeburn  7845:     my $cachetime=1800;
                   7846: 
                   7847:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  7848:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   7849:     if (defined($cached)) {
1.734     albertel 7850:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  7851:     } else {  
                   7852:         $grouplist = '';
1.816     raeburn  7853:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  7854:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  7855:         my $access_end = $env{'course.'.$courseid.
                   7856:                               '.default_enrollment_end_date'};
                   7857:         my $now = time;
                   7858:         foreach my $key (keys(%roleshash)) {
                   7859:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   7860:                 my $group = $1;
                   7861:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   7862:                     my $start = $2;
                   7863:                     my $end = $1;
                   7864:                     if ($start == -1) { next; } # deleted from group
                   7865:                     if (($start!=0) && ($start>$now)) { next; }
                   7866:                     if (($end!=0) && ($end<$now)) {
                   7867:                         if ($access_end && $access_end < $now) {
                   7868:                             if ($access_end - $end < 86400) {
                   7869:                                 push(@usersgroups,$group);
1.733     raeburn  7870:                             }
                   7871:                         }
1.817     raeburn  7872:                         next;
1.733     raeburn  7873:                     }
1.817     raeburn  7874:                     push(@usersgroups,$group);
1.683     raeburn  7875:                 }
                   7876:             }
                   7877:         }
1.817     raeburn  7878:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   7879:         $grouplist = join(':',@usersgroups);
                   7880:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  7881:     }
1.733     raeburn  7882:     return @usersgroups;
1.683     raeburn  7883: }
                   7884: 
                   7885: sub devalidate_getgroups_cache {
                   7886:     my ($udom,$uname,$cdom,$cnum)=@_;
                   7887:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 7888: 
1.683     raeburn  7889:     my $hashid="$udom:$uname:$courseid";
                   7890:     &devalidate_cache_new('getgroups',$hashid);
                   7891: }
                   7892: 
1.12      www      7893: # ------------------------------------------------------------------ Plain Text
                   7894: 
                   7895: sub plaintext {
1.988     raeburn  7896:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  7897:     if ($short =~ m{^cr/}) {
1.758     albertel 7898: 	return (split('/',$short))[-1];
                   7899:     }
1.742     raeburn  7900:     if (!defined($cid)) {
                   7901:         $cid = $env{'request.course.id'};
                   7902:     }
                   7903:     my %rolenames = (
1.1008    raeburn  7904:                       Course    => 'std',
                   7905:                       Community => 'alt1',
1.742     raeburn  7906:                     );
1.1037    raeburn  7907:     if ($cid ne '') {
                   7908:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   7909:             unless ($forcedefault) {
                   7910:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   7911:                 &Apache::lonlocal::mt_escape(\$roletext);
                   7912:                 return &Apache::lonlocal::mt($roletext);
                   7913:             }
                   7914:         }
                   7915:     }
                   7916:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   7917:         (defined($rolenames{$type})) && 
                   7918:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  7919:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  7920:     } elsif ($cid ne '') {
                   7921:         my $crstype = $env{'course.'.$cid.'.type'};
                   7922:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   7923:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   7924:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   7925:         }
1.742     raeburn  7926:     }
1.1037    raeburn  7927:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      7928: }
                   7929: 
                   7930: # ----------------------------------------------------------------- Assign Role
                   7931: 
                   7932: sub assignrole {
1.957     raeburn  7933:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   7934:         $context)=@_;
1.21      www      7935:     my $mrole;
                   7936:     if ($role =~ /^cr\//) {
1.393     www      7937:         my $cwosec=$url;
1.811     albertel 7938:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      7939: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  7940:            my $refused = 1;
                   7941:            if ($context eq 'requestcourses') {
                   7942:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   7943:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   7944:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   7945:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   7946:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7947:                            if ($crsenv{'internal.courseowner'} eq
                   7948:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   7949:                                $refused = '';
                   7950:                            }
                   7951:                        }
                   7952:                    }
                   7953:                }
                   7954:            }
                   7955:            if ($refused) {
                   7956:                &logthis('Refused custom assignrole: '.
                   7957:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   7958:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   7959:                return 'refused';
                   7960:            }
1.104     www      7961:         }
1.21      www      7962:         $mrole='cr';
1.678     raeburn  7963:     } elsif ($role =~ /^gr\//) {
                   7964:         my $cwogrp=$url;
1.811     albertel 7965:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  7966:         unless (&allowed('mdg',$cwogrp)) {
                   7967:             &logthis('Refused group assignrole: '.
                   7968:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   7969:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   7970:             return 'refused';
                   7971:         }
                   7972:         $mrole='gr';
1.21      www      7973:     } else {
1.82      www      7974:         my $cwosec=$url;
1.811     albertel 7975:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  7976:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   7977:             my $refused;
                   7978:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   7979:                 if (!(&allowed('c'.$role,$url))) {
                   7980:                     $refused = 1;
                   7981:                 }
                   7982:             } else {
                   7983:                 $refused = 1;
                   7984:             }
1.947     raeburn  7985:             if ($refused) {
1.1045    raeburn  7986:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   7987:                 if (!$selfenroll && $context eq 'course') {
                   7988:                     my %crsenv;
                   7989:                     if ($role eq 'cc' || $role eq 'co') {
                   7990:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7991:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   7992:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   7993:                                 if ($crsenv{'internal.courseowner'} eq 
                   7994:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   7995:                                     $refused = '';
                   7996:                                 }
                   7997:                             }
                   7998:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   7999:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   8000:                                 if ($crsenv{'internal.courseowner'} eq 
                   8001:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8002:                                     $refused = '';
                   8003:                                 }
                   8004:                             }
                   8005:                         }
                   8006:                     }
                   8007:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  8008:                     $refused = '';
1.1017    raeburn  8009:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  8010:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  8011:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  8012:                         my $wrongcc;
                   8013:                         if ($cnum =~ /^$match_community$/) {
                   8014:                             $wrongcc = 1 if ($role eq 'cc');
                   8015:                         } else {
                   8016:                             $wrongcc = 1 if ($role eq 'co');
                   8017:                         }
                   8018:                         unless ($wrongcc) {
                   8019:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8020:                             if ($crsenv{'internal.courseowner'} eq 
                   8021:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   8022:                                 $refused = '';
                   8023:                             }
1.1017    raeburn  8024:                         }
                   8025:                     }
1.1172.2.9  raeburn  8026:                 } elsif ($context eq 'requestauthor') {
                   8027:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   8028:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   8029:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   8030:                             $refused = '';
                   8031:                         } else {
                   8032:                             my %domdefaults = &get_domain_defaults($udom);
                   8033:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   8034:                                 my $checkbystatus;
                   8035:                                 if ($env{'user.adv'}) {
                   8036:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   8037:                                     if ($disposition eq 'automatic') {
                   8038:                                         $refused = '';
                   8039:                                     } elsif ($disposition eq '') {
                   8040:                                         $checkbystatus = 1;
                   8041:                                     }
                   8042:                                 } else {
                   8043:                                     $checkbystatus = 1;
                   8044:                                 }
                   8045:                                 if ($checkbystatus) {
                   8046:                                     if ($env{'environment.inststatus'}) {
                   8047:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   8048:                                         foreach my $type (@inststatuses) {
                   8049:                                             if (($type ne '') &&
                   8050:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   8051:                                                 $refused = '';
                   8052:                                             }
                   8053:                                         }
                   8054:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   8055:                                         $refused = '';
                   8056:                                     }
                   8057:                                 }
                   8058:                             }
                   8059:                         }
                   8060:                     }
1.1017    raeburn  8061:                 }
                   8062:                 if ($refused) {
1.947     raeburn  8063:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   8064:                              ' '.$role.' '.$end.' '.$start.' by '.
                   8065: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   8066:                     return 'refused';
                   8067:                 }
1.932     raeburn  8068:             }
1.1131    raeburn  8069:         } elsif ($role eq 'au') {
                   8070:             if ($url ne '/'.$udom.'/') {
                   8071:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   8072:                          ' to assign author role for '.$uname.':'.$udom.
                   8073:                          ' in domain: '.$url.' refused (wrong domain).');
                   8074:                 return 'refused';
                   8075:             }
1.104     www      8076:         }
1.21      www      8077:         $mrole=$role;
                   8078:     }
1.620     albertel 8079:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      8080:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      8081:     if ($end) { $command.='_'.$end; }
1.21      www      8082:     if ($start) {
                   8083: 	if ($end) { 
1.81      www      8084:            $command.='_'.$start; 
1.21      www      8085:         } else {
1.81      www      8086:            $command.='_0_'.$start;
1.21      www      8087:         }
                   8088:     }
1.739     raeburn  8089:     my $origstart = $start;
                   8090:     my $origend = $end;
1.957     raeburn  8091:     my $delflag;
1.357     www      8092: # actually delete
                   8093:     if ($deleteflag) {
1.373     www      8094: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      8095: # modify command to delete the role
1.620     albertel 8096:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      8097:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 8098: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      8099: # set start and finish to negative values for userrolelog
                   8100:            $start=-1;
                   8101:            $end=-1;
1.957     raeburn  8102:            $delflag = 1;
1.357     www      8103:         }
                   8104:     }
                   8105: # send command
1.349     www      8106:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      8107: # log new user role if status is ok
1.349     www      8108:     if ($answer eq 'ok') {
1.663     raeburn  8109: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  8110:         if (($role eq 'cc') || ($role eq 'in') ||
                   8111:             ($role eq 'ep') || ($role eq 'ad') ||
                   8112:             ($role eq 'ta') || ($role eq 'st') ||
                   8113:             ($role=~/^cr/) || ($role eq 'gr') ||
                   8114:             ($role eq 'co')) {
1.1172.2.13  raeburn  8115: # for course roles, perform group memberships changes triggered by role change.
                   8116:             unless ($role =~ /^gr/) {
                   8117:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   8118:                                                  $origstart,$selfenroll,$context);
                   8119:             }
1.1172.2.9  raeburn  8120:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8121:                            $selfenroll,$context);
                   8122:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
                   8123:                  ($role eq 'au') || ($role eq 'dc')) {
                   8124:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8125:                            $context);
                   8126:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   8127:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8128:                              $context);
                   8129:         }
1.1053    raeburn  8130:         if ($role eq 'cc') {
                   8131:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   8132:         }
1.349     www      8133:     }
                   8134:     return $answer;
1.169     harris41 8135: }
                   8136: 
1.1053    raeburn  8137: sub autoupdate_coowners {
                   8138:     my ($url,$end,$start,$uname,$udom) = @_;
                   8139:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   8140:     if (($cdom ne '') && ($cnum ne '')) {
                   8141:         my $now = time;
                   8142:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   8143:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   8144:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   8145:             my $instcode = $coursehash{'internal.coursecode'};
                   8146:             if ($instcode ne '') {
1.1056    raeburn  8147:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   8148:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  8149:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  8150:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   8151:                         if ($result eq 'valid') {
                   8152:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  8153:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8154:                                     push(@newcoowners,$coowner);
                   8155:                                 }
                   8156:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   8157:                                     push(@newcoowners,$uname.':'.$udom);
                   8158:                                 }
                   8159:                                 @newcoowners = sort(@newcoowners);
                   8160:                             } else {
                   8161:                                 push(@newcoowners,$uname.':'.$udom);
                   8162:                             }
                   8163:                         } else {
                   8164:                             if ($coursehash{'internal.co-owners'}) {
                   8165:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8166:                                     unless ($coowner eq $uname.':'.$udom) {
                   8167:                                         push(@newcoowners,$coowner);
                   8168:                                     }
                   8169:                                 }
                   8170:                                 unless (@newcoowners > 0) {
                   8171:                                     $delcoowners = 1;
                   8172:                                     $coowners = '';
                   8173:                                 }
                   8174:                             }
                   8175:                         }
                   8176:                         if (@newcoowners || $delcoowners) {
                   8177:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   8178:                                             $delcoowners,@newcoowners);
                   8179:                         }
                   8180:                     }
                   8181:                 }
                   8182:             }
                   8183:         }
                   8184:     }
                   8185: }
                   8186: 
                   8187: sub store_coowners {
                   8188:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   8189:     my $cid = $cdom.'_'.$cnum;
                   8190:     my ($coowners,$delresult,$putresult);
                   8191:     if (@newcoowners) {
                   8192:         $coowners = join(',',@newcoowners);
                   8193:         my %coownershash = (
                   8194:                             'internal.co-owners' => $coowners,
                   8195:                            );
                   8196:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   8197:         if ($putresult eq 'ok') {
                   8198:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   8199:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   8200:             }
                   8201:         }
                   8202:     }
                   8203:     if ($delcoowners) {
                   8204:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   8205:         if ($delresult eq 'ok') {
                   8206:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   8207:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   8208:             }
                   8209:         }
                   8210:     }
                   8211:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   8212:         my %crsinfo =
                   8213:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   8214:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   8215:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   8216:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   8217:         }
                   8218:     }
                   8219: }
                   8220: 
1.169     harris41 8221: # -------------------------------------------------- Modify user authentication
1.197     www      8222: # Overrides without validation
                   8223: 
1.169     harris41 8224: sub modifyuserauth {
                   8225:     my ($udom,$uname,$umode,$upass)=@_;
                   8226:     my $uhome=&homeserver($uname,$udom);
1.197     www      8227:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   8228:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 8229:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8230:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 8231:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   8232: 		     &escape($upass),$uhome);
1.620     albertel 8233:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      8234:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   8235:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   8236:     &log($udom,,$uname,$uhome,
1.620     albertel 8237:         'Authentication changed by '.$env{'user.domain'}.', '.
                   8238:                                      $env{'user.name'}.', '.$umode.
1.197     www      8239:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 8240:     unless ($reply eq 'ok') {
1.197     www      8241:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 8242: 	return 'error: '.$reply;
                   8243:     }   
1.170     harris41 8244:     return 'ok';
1.80      www      8245: }
                   8246: 
1.81      www      8247: # --------------------------------------------------------------- Modify a user
1.80      www      8248: 
1.81      www      8249: sub modifyuser {
1.206     matthew  8250:     my ($udom,    $uname, $uid,
                   8251:         $umode,   $upass, $first,
                   8252:         $middle,  $last,  $gene,
1.1058    raeburn  8253:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 8254:     $udom= &LONCAPA::clean_domain($udom);
                   8255:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  8256:     my $showcandelete = 'none';
                   8257:     if (ref($candelete) eq 'ARRAY') {
                   8258:         if (@{$candelete} > 0) {
                   8259:             $showcandelete = join(', ',@{$candelete});
                   8260:         }
                   8261:     }
1.81      www      8262:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      8263:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  8264: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  8265:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   8266:                                      ' desiredhome not specified'). 
1.620     albertel 8267:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8268:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 8269:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  8270:     my $newuser;
                   8271:     if ($uhome eq 'no_host') {
                   8272:         $newuser = 1;
                   8273:     }
1.80      www      8274: # ----------------------------------------------------------------- Create User
1.406     albertel 8275:     if (($uhome eq 'no_host') && 
                   8276: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      8277:         my $unhome='';
1.844     albertel 8278:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  8279:             $unhome = $desiredhome;
1.620     albertel 8280: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   8281: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  8282:         } else { # load balancing routine for determining $unhome
1.81      www      8283:             my $loadm=10000000;
1.841     albertel 8284: 	    my %servers = &get_servers($udom,'library');
                   8285: 	    foreach my $tryserver (keys(%servers)) {
                   8286: 		my $answer=reply('load',$tryserver);
                   8287: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   8288: 		    $loadm=$answer;
                   8289: 		    $unhome=$tryserver;
                   8290: 		}
1.80      www      8291: 	    }
                   8292:         }
                   8293:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  8294: 	    return 'error: unable to find a home server for '.$uname.
                   8295:                    ' in domain '.$udom;
1.80      www      8296:         }
                   8297:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   8298:                          &escape($upass),$unhome);
                   8299: 	unless ($reply eq 'ok') {
                   8300:             return 'error: '.$reply;
                   8301:         }   
1.230     stredwic 8302:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      8303:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  8304: 	    return 'error: unable verify users home machine.';
1.80      www      8305:         }
1.209     matthew  8306:     }   # End of creation of new user
1.80      www      8307: # ---------------------------------------------------------------------- Add ID
                   8308:     if ($uid) {
                   8309:        $uid=~tr/A-Z/a-z/;
                   8310:        my %uidhash=&idrget($udom,$uname);
1.196     www      8311:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   8312:          && (!$forceid)) {
1.80      www      8313: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  8314: 	      return 'error: user id "'.$uid.'" does not match '.
                   8315:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      8316:           }
                   8317:        } else {
                   8318: 	  &idput($udom,($uname => $uid));
                   8319:        }
                   8320:     }
                   8321: # -------------------------------------------------------------- Add names, etc
1.313     matthew  8322:     my @tmp=&get('environment',
1.899     raeburn  8323: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  8324:                     'permanentemail','inststatus'],
1.134     albertel 8325: 		   $udom,$uname);
1.1075    raeburn  8326:     my (%names,%oldnames);
1.313     matthew  8327:     if ($tmp[0] =~ m/^error:.*/) { 
                   8328:         %names=(); 
                   8329:     } else {
                   8330:         %names = @tmp;
1.1075    raeburn  8331:         %oldnames = %names;
1.313     matthew  8332:     }
1.388     www      8333: #
1.1058    raeburn  8334: # If name, email and/or uid are blank (e.g., because an uploaded file
                   8335: # of users did not contain them), do not overwrite existing values
                   8336: # unless field is in $candelete array ref.  
                   8337: #
                   8338: 
                   8339:     my @fields = ('firstname','middlename','lastname','generation',
                   8340:                   'permanentemail','id');
                   8341:     my %newvalues;
                   8342:     if (ref($candelete) eq 'ARRAY') {
                   8343:         foreach my $field (@fields) {
                   8344:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   8345:                 if ($field eq 'firstname') {
                   8346:                     $names{$field} = $first;
                   8347:                 } elsif ($field eq 'middlename') {
                   8348:                     $names{$field} = $middle;
                   8349:                 } elsif ($field eq 'lastname') {
                   8350:                     $names{$field} = $last;
                   8351:                 } elsif ($field eq 'generation') { 
                   8352:                     $names{$field} = $gene;
                   8353:                 } elsif ($field eq 'permanentemail') {
                   8354:                     $names{$field} = $email;
                   8355:                 } elsif ($field eq 'id') {
                   8356:                     $names{$field}  = $uid;
                   8357:                 }
                   8358:             }
                   8359:         }
                   8360:     }
1.388     www      8361:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  8362:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      8363:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  8364:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      8365:     if ($email) {
                   8366:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  8367:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      8368:     }
1.899     raeburn  8369:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  8370:     if (defined($inststatus)) {
                   8371:         $names{'inststatus'} = '';
                   8372:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   8373:         if (ref($usertypes) eq 'HASH') {
                   8374:             my @okstatuses; 
                   8375:             foreach my $item (split(/:/,$inststatus)) {
                   8376:                 if (defined($usertypes->{$item})) {
                   8377:                     push(@okstatuses,$item);  
                   8378:                 }
                   8379:             }
                   8380:             if (@okstatuses) {
                   8381:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   8382:             }
                   8383:         }
                   8384:     }
1.1075    raeburn  8385:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  8386:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  8387:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  8388:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   8389:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   8390:     } else {
                   8391:         $logmsg .= ' during self creation';
                   8392:     }
1.1075    raeburn  8393:     my $changed;
                   8394:     if ($newuser) {
                   8395:         $changed = 1;
                   8396:     } else {
                   8397:         foreach my $field (@fields) {
                   8398:             if ($names{$field} ne $oldnames{$field}) {
                   8399:                 $changed = 1;
                   8400:                 last;
                   8401:             }
                   8402:         }
                   8403:     }
                   8404:     unless ($changed) {
                   8405:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   8406:         &logthis($logmsg);
                   8407:         return 'ok';
                   8408:     }
                   8409:     my $reply = &put('environment', \%names, $udom,$uname);
                   8410:     if ($reply ne 'ok') { 
                   8411:         return 'error: '.$reply;
                   8412:     }
1.1087    raeburn  8413:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   8414:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   8415:     }
1.1075    raeburn  8416:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   8417:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   8418:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  8419:     &logthis($logmsg);
1.134     albertel 8420:     return 'ok';
1.80      www      8421: }
                   8422: 
1.81      www      8423: # -------------------------------------------------------------- Modify student
1.80      www      8424: 
1.81      www      8425: sub modifystudent {
                   8426:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  8427:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.19  raeburn  8428:         $selfenroll,$context,$inststatus,$credits)=@_;
1.455     albertel 8429:     if (!$cid) {
1.620     albertel 8430: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8431: 	    return 'not_in_class';
                   8432: 	}
1.80      www      8433:     }
                   8434: # --------------------------------------------------------------- Make the user
1.81      www      8435:     my $reply=&modifyuser
1.209     matthew  8436: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  8437:          $desiredhome,$email,$inststatus);
1.80      www      8438:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  8439:     # This will cause &modify_student_enrollment to get the uid from the
                   8440:     # students environment
                   8441:     $uid = undef if (!$forceid);
1.455     albertel 8442:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  8443: 					$gene,$usec,$end,$start,$type,$locktype,
                   8444:                                         $cid,$selfenroll,$context,$credits);
1.297     matthew  8445:     return $reply;
                   8446: }
                   8447: 
                   8448: sub modify_student_enrollment {
1.1172.2.23  raeburn  8449:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
                   8450:         $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455     albertel 8451:     my ($cdom,$cnum,$chome);
                   8452:     if (!$cid) {
1.620     albertel 8453: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8454: 	    return 'not_in_class';
                   8455: 	}
1.620     albertel 8456: 	$cdom=$env{'course.'.$cid.'.domain'};
                   8457: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 8458:     } else {
                   8459: 	($cdom,$cnum)=split(/_/,$cid);
                   8460:     }
1.620     albertel 8461:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 8462:     if (!$chome) {
1.457     raeburn  8463: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  8464:     }
1.455     albertel 8465:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  8466:     # Make sure the user exists
1.81      www      8467:     my $uhome=&homeserver($uname,$udom);
                   8468:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8469: 	return 'error: no such user';
                   8470:     }
1.297     matthew  8471:     # Get student data if we were not given enough information
                   8472:     if (!defined($first)  || $first  eq '' || 
                   8473:         !defined($last)   || $last   eq '' || 
                   8474:         !defined($uid)    || $uid    eq '' || 
                   8475:         !defined($middle) || $middle eq '' || 
                   8476:         !defined($gene)   || $gene   eq '') {
1.294     matthew  8477:         # They did not supply us with enough data to enroll the student, so
                   8478:         # we need to pick up more information.
1.297     matthew  8479:         my %tmp = &get('environment',
1.294     matthew  8480:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  8481:                        ,$udom,$uname);
                   8482: 
1.800     albertel 8483:         #foreach my $key (keys(%tmp)) {
                   8484:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 8485:         #}
1.294     matthew  8486:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   8487:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   8488:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  8489:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  8490:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   8491:     }
1.556     albertel 8492:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  8493:     my $user = "$uname:$udom";
                   8494:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 8495:     my $reply=cput('classlist',
1.1148    raeburn  8496: 		   {$user => 
1.1172.2.19  raeburn  8497: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487     albertel 8498: 		   $cdom,$cnum);
1.1148    raeburn  8499:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   8500:         &devalidate_getsection_cache($udom,$uname,$cid);
                   8501:     } else { 
1.81      www      8502: 	return 'error: '.$reply;
                   8503:     }
1.297     matthew  8504:     # Add student role to user
1.83      www      8505:     my $uurl='/'.$cid;
1.81      www      8506:     $uurl=~s/\_/\//g;
                   8507:     if ($usec) {
                   8508: 	$uurl.='/'.$usec;
                   8509:     }
1.1148    raeburn  8510:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   8511:                              $selfenroll,$context);
                   8512:     if ($result ne 'ok') {
                   8513:         if ($old_entry{$user} ne '') {
                   8514:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   8515:         } else {
                   8516:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   8517:         }
                   8518:     }
                   8519:     return $result; 
1.21      www      8520: }
                   8521: 
1.556     albertel 8522: sub format_name {
                   8523:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   8524:     my $name;
                   8525:     if ($first ne 'lastname') {
                   8526: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   8527:     } else {
                   8528: 	if ($lastname=~/\S/) {
                   8529: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   8530: 	    $name=~s/\s+,/,/;
                   8531: 	} else {
                   8532: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   8533: 	}
                   8534:     }
                   8535:     $name=~s/^\s+//;
                   8536:     $name=~s/\s+$//;
                   8537:     $name=~s/\s+/ /g;
                   8538:     return $name;
                   8539: }
                   8540: 
1.84      www      8541: # ------------------------------------------------- Write to course preferences
                   8542: 
                   8543: sub writecoursepref {
                   8544:     my ($courseid,%prefs)=@_;
                   8545:     $courseid=~s/^\///;
                   8546:     $courseid=~s/\_/\//g;
                   8547:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   8548:     my $chome=homeserver($cnum,$cdomain);
                   8549:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   8550: 	return 'error: no such course';
                   8551:     }
                   8552:     my $cstring='';
1.800     albertel 8553:     foreach my $pref (keys(%prefs)) {
                   8554: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 8555:     }
1.84      www      8556:     $cstring=~s/\&$//;
                   8557:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   8558: }
                   8559: 
                   8560: # ---------------------------------------------------------- Make/modify course
                   8561: 
                   8562: sub createcourse {
1.741     raeburn  8563:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  8564:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      8565:     $url=&declutter($url);
                   8566:     my $cid='';
1.1028    raeburn  8567:     if ($context eq 'requestcourses') {
                   8568:         my $can_create = 0;
                   8569:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   8570:         if ($udom eq $ownerdom) {
                   8571:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   8572:                                   $context)) {
                   8573:                 $can_create = 1;
                   8574:             }
                   8575:         } else {
                   8576:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   8577:                                            $category);
                   8578:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   8579:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   8580:                 if (@curr > 0) {
                   8581:                     my @options = qw(approval validate autolimit);
                   8582:                     my $optregex = join('|',@options);
                   8583:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   8584:                         $can_create = 1;
                   8585:                     }
                   8586:                 }
                   8587:             }
                   8588:         }
                   8589:         if ($can_create) {
                   8590:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   8591:                 unless (&allowed('ccc',$udom)) {
                   8592:                     return 'refused'; 
                   8593:                 }
1.1017    raeburn  8594:             }
                   8595:         } else {
                   8596:             return 'refused';
                   8597:         }
1.1028    raeburn  8598:     } elsif (!&allowed('ccc',$udom)) {
                   8599:         return 'refused';
1.84      www      8600:     }
1.1011    raeburn  8601: # --------------------------------------------------------------- Get Unique ID
                   8602:     my $uname;
                   8603:     if ($cnum =~ /^$match_courseid$/) {
                   8604:         my $chome=&homeserver($cnum,$udom,'true');
                   8605:         if (($chome eq '') || ($chome eq 'no_host')) {
                   8606:             $uname = $cnum;
                   8607:         } else {
1.1038    raeburn  8608:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8609:         }
                   8610:     } else {
1.1038    raeburn  8611:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8612:     }
                   8613:     return $uname if ($uname =~ /^error/);
                   8614: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  8615:     if (!defined($course_server)) {
                   8616:         if (defined(&domain($udom,'primary'))) {
                   8617:             $course_server = &domain($udom,'primary');
                   8618:         } else {
                   8619:             $course_server = $env{'user.home'}; 
                   8620:         }
                   8621:     }
                   8622:     my %host_servers =
                   8623:         &Apache::lonnet::get_servers($udom,'library');
                   8624:     unless ($host_servers{$course_server}) {
                   8625:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  8626:     }
1.84      www      8627: # ------------------------------------------------------------- Make the course
                   8628:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  8629:                       $course_server);
1.84      www      8630:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  8631:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      8632:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8633: 	return 'error: no such course';
                   8634:     }
1.271     www      8635: # ----------------------------------------------------------------- Course made
1.516     raeburn  8636: # log existence
1.1029    raeburn  8637:     my $now = time;
1.918     raeburn  8638:     my $newcourse = {
                   8639:                     $udom.'_'.$uname => {
1.921     raeburn  8640:                                      description => $description,
                   8641:                                      inst_code   => $inst_code,
                   8642:                                      owner       => $course_owner,
                   8643:                                      type        => $crstype,
1.1029    raeburn  8644:                                      creator     => $env{'user.name'}.':'.
                   8645:                                                     $env{'user.domain'},
                   8646:                                      created     => $now,
                   8647:                                      context     => $context,
1.918     raeburn  8648:                                                 },
                   8649:                     };
1.921     raeburn  8650:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      8651: # set toplevel url
1.271     www      8652:     my $topurl=$url;
                   8653:     unless ($nonstandard) {
                   8654: # ------------------------------------------ For standard courses, make top url
                   8655:         my $mapurl=&clutter($url);
1.278     www      8656:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 8657:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      8658: <map>
                   8659: <resource id="1" type="start"></resource>
                   8660: <resource id="2" src="$mapurl"></resource>
                   8661: <resource id="3" type="finish"></resource>
                   8662: <link index="1" from="1" to="2"></link>
                   8663: <link index="2" from="2" to="3"></link>
                   8664: </map>
                   8665: ENDINITMAP
                   8666:         $topurl=&declutter(
1.638     albertel 8667:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      8668:                           );
                   8669:     }
                   8670: # ----------------------------------------------------------- Write preferences
1.84      www      8671:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  8672:                      ('description'              => $description,
                   8673:                       'url'                      => $topurl,
                   8674:                       'internal.creator'         => $env{'user.name'}.':'.
                   8675:                                                     $env{'user.domain'},
                   8676:                       'internal.created'         => $now,
                   8677:                       'internal.creationcontext' => $context)
                   8678:                     );
1.84      www      8679:     return '/'.$udom.'/'.$uname;
                   8680: }
                   8681: 
1.1011    raeburn  8682: # ------------------------------------------------------------------- Create ID
                   8683: sub generate_coursenum {
1.1038    raeburn  8684:     my ($udom,$crstype) = @_;
1.1011    raeburn  8685:     my $domdesc = &domain($udom);
                   8686:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  8687:     my $first;
                   8688:     if ($crstype eq 'Community') {
                   8689:         $first = '0';
                   8690:     } else {
                   8691:         $first = int(1+rand(9)); 
                   8692:     } 
                   8693:     my $uname=$first.
1.1011    raeburn  8694:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8695:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8696:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8697: # ----------------------------------------------- Make sure that does not exist
                   8698:     my $uhome=&homeserver($uname,$udom,'true');
                   8699:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  8700:         if ($crstype eq 'Community') {
                   8701:             $first = '0';
                   8702:         } else {
                   8703:             $first = int(1+rand(9));
                   8704:         }
                   8705:         $uname=$first.
1.1011    raeburn  8706:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8707:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8708:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8709:         $uhome=&homeserver($uname,$udom,'true');
                   8710:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   8711:             return 'error: unable to generate unique course-ID';
                   8712:         }
                   8713:     }
                   8714:     return $uname;
                   8715: }
                   8716: 
1.813     albertel 8717: sub is_course {
1.1167    droeschl 8718:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   8719:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   8720: 
                   8721:     return unless $cdom and $cnum;
                   8722: 
                   8723:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   8724:         '.');
                   8725: 
1.1172.2.23  raeburn  8726:     return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167    droeschl 8727:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 8728: }
                   8729: 
1.1015    raeburn  8730: sub store_userdata {
                   8731:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  8732:     my $result;
1.1016    raeburn  8733:     if ($datakey ne '') {
1.1013    raeburn  8734:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  8735:             if ($udom eq '' || $uname eq '') {
                   8736:                 $udom = $env{'user.domain'};
                   8737:                 $uname = $env{'user.name'};
                   8738:             }
                   8739:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  8740:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   8741:                 $result = 'error: no_host';
                   8742:             } else {
                   8743:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   8744:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   8745: 
                   8746:                 my $namevalue='';
                   8747:                 foreach my $key (keys(%{$storehash})) {
                   8748:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   8749:                 }
                   8750:                 $namevalue=~s/\&$//;
1.1105    raeburn  8751:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   8752:                                   $namevalue,$uhome);
1.1013    raeburn  8753:             }
                   8754:         } else {
                   8755:             $result = 'error: data to store was not a hash reference'; 
                   8756:         }
                   8757:     } else {
                   8758:         $result= 'error: invalid requestkey'; 
                   8759:     }
                   8760:     return $result;
                   8761: }
                   8762: 
1.21      www      8763: # ---------------------------------------------------------- Assign Custom Role
                   8764: 
                   8765: sub assigncustomrole {
1.957     raeburn  8766:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8767:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  8768:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      8769: }
                   8770: 
                   8771: # ----------------------------------------------------------------- Revoke Role
                   8772: 
                   8773: sub revokerole {
1.957     raeburn  8774:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8775:     my $now=time;
1.965     raeburn  8776:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      8777: }
                   8778: 
                   8779: # ---------------------------------------------------------- Revoke Custom Role
                   8780: 
                   8781: sub revokecustomrole {
1.957     raeburn  8782:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8783:     my $now=time;
1.357     www      8784:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  8785:            $deleteflag,$selfenroll,$context);
1.17      www      8786: }
                   8787: 
1.533     banghart 8788: # ------------------------------------------------------------ Disk usage
1.535     albertel 8789: sub diskusage {
1.955     raeburn  8790:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   8791:     $directorypath =~ s/\/$//;
                   8792:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   8793:                        .&escape($getpropath).':'.&escape($uname).':'
                   8794:                        .&escape($udom),homeserver($uname,$udom));
                   8795:     if ($listing eq 'unknown_cmd') {
                   8796:         if ($getpropath) {
                   8797:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   8798:         }
                   8799:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   8800:     }
1.514     albertel 8801:     return $listing;
1.512     banghart 8802: }
                   8803: 
1.566     banghart 8804: sub is_locked {
1.1096    raeburn  8805:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 8806:     my @check;
                   8807:     my $is_locked;
1.1093    raeburn  8808:     push (@check,$file_name);
1.613     albertel 8809:     my %locked = &get('file_permissions',\@check,
1.620     albertel 8810: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 8811:     my ($tmp)=keys(%locked);
                   8812:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  8813:     
1.566     banghart 8814:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  8815:         $is_locked = 'false';
                   8816:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  8817:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  8818:                $is_locked = 'true';
1.1096    raeburn  8819:                if (ref($which) eq 'ARRAY') {
                   8820:                    push(@{$which},$entry);
                   8821:                } else {
                   8822:                    last;
                   8823:                }
1.745     raeburn  8824:            }
                   8825:        }
1.566     banghart 8826:     } else {
                   8827:         $is_locked = 'false';
                   8828:     }
1.1093    raeburn  8829:     return $is_locked;
1.566     banghart 8830: }
                   8831: 
1.759     albertel 8832: sub declutter_portfile {
                   8833:     my ($file) = @_;
1.833     albertel 8834:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 8835:     return $file;
                   8836: }
                   8837: 
1.559     banghart 8838: # ------------------------------------------------------------- Mark as Read Only
                   8839: 
                   8840: sub mark_as_readonly {
                   8841:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 8842:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 8843:     my ($tmp)=keys(%current_permissions);
                   8844:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 8845:     foreach my $file (@{$files}) {
1.759     albertel 8846: 	$file = &declutter_portfile($file);
1.561     banghart 8847:         push(@{$current_permissions{$file}},$what);
1.559     banghart 8848:     }
1.613     albertel 8849:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 8850:     return;
                   8851: }
                   8852: 
1.572     banghart 8853: # ------------------------------------------------------------Save Selected Files
                   8854: 
                   8855: sub save_selected_files {
                   8856:     my ($user, $path, @files) = @_;
                   8857:     my $filename = $user."savedfiles";
1.573     banghart 8858:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 8859:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 8860:     foreach my $file (@files) {
1.620     albertel 8861:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 8862:     }
                   8863:     foreach my $file (@other_files) {
1.574     banghart 8864:         print (OUT $file."\n");
1.572     banghart 8865:     }
1.574     banghart 8866:     close (OUT);
1.572     banghart 8867:     return 'ok';
                   8868: }
                   8869: 
1.574     banghart 8870: sub clear_selected_files {
                   8871:     my ($user) = @_;
                   8872:     my $filename = $user."savedfiles";
1.1117    foxr     8873:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 8874:     print (OUT undef);
                   8875:     close (OUT);
                   8876:     return ("ok");    
                   8877: }
                   8878: 
1.572     banghart 8879: sub files_in_path {
                   8880:     my ($user, $path) = @_;
                   8881:     my $filename = $user."savedfiles";
                   8882:     my %return_files;
1.1117    foxr     8883:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 8884:     while (my $line_in = <IN>) {
1.574     banghart 8885:         chomp ($line_in);
                   8886:         my @paths_and_file = split (m!/!, $line_in);
                   8887:         my $file_part = pop (@paths_and_file);
                   8888:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 8889:         $path_part.='/';
                   8890:         my $path_and_file = $path_part.$file_part;
                   8891:         if ($path_part eq $path) {
                   8892:             $return_files{$file_part}= 'selected';
                   8893:         }
                   8894:     }
1.574     banghart 8895:     close (IN);
                   8896:     return (\%return_files);
1.572     banghart 8897: }
                   8898: 
                   8899: # called in portfolio select mode, to show files selected NOT in current directory
                   8900: sub files_not_in_path {
                   8901:     my ($user, $path) = @_;
                   8902:     my $filename = $user."savedfiles";
                   8903:     my @return_files;
                   8904:     my $path_part;
1.1117    foxr     8905:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 8906:     while (my $line = <IN>) {
1.572     banghart 8907:         #ok, I know it's clunky, but I want it to work
1.800     albertel 8908:         my @paths_and_file = split(m|/|, $line);
                   8909:         my $file_part = pop(@paths_and_file);
                   8910:         chomp($file_part);
                   8911:         my $path_part = join('/', @paths_and_file);
1.572     banghart 8912:         $path_part .= '/';
                   8913:         my $path_and_file = $path_part.$file_part;
                   8914:         if ($path_part ne $path) {
1.800     albertel 8915:             push(@return_files, ($path_and_file));
1.572     banghart 8916:         }
                   8917:     }
1.800     albertel 8918:     close(OUT);
1.574     banghart 8919:     return (@return_files);
1.572     banghart 8920: }
                   8921: 
1.745     raeburn  8922: #----------------------------------------------Get portfolio file permissions
1.629     banghart 8923: 
1.745     raeburn  8924: sub get_portfile_permissions {
                   8925:     my ($domain,$user) = @_;
1.613     albertel 8926:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 8927:     my ($tmp)=keys(%current_permissions);
                   8928:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  8929:     return \%current_permissions;
                   8930: }
                   8931: 
                   8932: #---------------------------------------------Get portfolio file access controls
                   8933: 
1.749     raeburn  8934: sub get_access_controls {
1.745     raeburn  8935:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 8936:     my %access;
                   8937:     my $real_file = $file;
                   8938:     $file =~ s/\.meta$//;
1.745     raeburn  8939:     if (defined($file)) {
1.749     raeburn  8940:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   8941:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 8942:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  8943:             }
                   8944:         }
1.745     raeburn  8945:     } else {
1.749     raeburn  8946:         foreach my $key (keys(%{$current_permissions})) {
                   8947:             if ($key =~ /\0accesscontrol$/) {
                   8948:                 if (defined($group)) {
                   8949:                     if ($key !~ m-^\Q$group\E/-) {
                   8950:                         next;
                   8951:                     }
                   8952:                 }
                   8953:                 my ($fullpath) = split(/\0/,$key);
                   8954:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   8955:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   8956:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   8957:                     }
                   8958:                 }
                   8959:             }
                   8960:         }
                   8961:     }
                   8962:     return %access;
                   8963: }
                   8964: 
                   8965: sub modify_access_controls {
                   8966:     my ($file_name,$changes,$domain,$user)=@_;
                   8967:     my ($outcome,$deloutcome);
                   8968:     my %store_permissions;
                   8969:     my %new_values;
                   8970:     my %new_control;
                   8971:     my %translation;
                   8972:     my @deletions = ();
                   8973:     my $now = time;
                   8974:     if (exists($$changes{'activate'})) {
                   8975:         if (ref($$changes{'activate'}) eq 'HASH') {
                   8976:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   8977:             my $numnew = scalar(@newitems);
                   8978:             for (my $i=0; $i<$numnew; $i++) {
                   8979:                 my $newkey = $newitems[$i];
                   8980:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  8981:                 if ($newkey =~ /^\d+:/) { 
                   8982:                     $newkey =~ s/^(\d+)/$newid/;
                   8983:                     $translation{$1} = $newid;
                   8984:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   8985:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   8986:                     $translation{$1} = $newid;
                   8987:                 }
1.749     raeburn  8988:                 $new_values{$file_name."\0".$newkey} = 
                   8989:                                           $$changes{'activate'}{$newitems[$i]};
                   8990:                 $new_control{$newkey} = $now;
                   8991:             }
                   8992:         }
                   8993:     }
                   8994:     my %todelete;
                   8995:     my %changed_items;
                   8996:     foreach my $action ('delete','update') {
                   8997:         if (exists($$changes{$action})) {
                   8998:             if (ref($$changes{$action}) eq 'HASH') {
                   8999:                 foreach my $key (keys(%{$$changes{$action}})) {
                   9000:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   9001:                     if ($action eq 'delete') { 
                   9002:                         $todelete{$itemnum} = 1;
                   9003:                     } else {
                   9004:                         $changed_items{$itemnum} = $key;
                   9005:                     }
                   9006:                 }
1.745     raeburn  9007:             }
                   9008:         }
1.749     raeburn  9009:     }
                   9010:     # get lock on access controls for file.
                   9011:     my $lockhash = {
                   9012:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   9013:                                                        ':'.$env{'user.domain'},
                   9014:                    }; 
                   9015:     my $tries = 0;
                   9016:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9017:    
                   9018:     while (($gotlock ne 'ok') && $tries <3) {
                   9019:         $tries ++;
                   9020:         sleep 1;
                   9021:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9022:     }
                   9023:     if ($gotlock eq 'ok') {
                   9024:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   9025:         my ($tmp)=keys(%curr_permissions);
                   9026:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   9027:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   9028:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   9029:             if (ref($curr_controls) eq 'HASH') {
                   9030:                 foreach my $control_item (keys(%{$curr_controls})) {
                   9031:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   9032:                     if (defined($todelete{$itemnum})) {
                   9033:                         push(@deletions,$file_name."\0".$control_item);
                   9034:                     } else {
                   9035:                         if (defined($changed_items{$itemnum})) {
                   9036:                             $new_control{$changed_items{$itemnum}} = $now;
                   9037:                             push(@deletions,$file_name."\0".$control_item);
                   9038:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   9039:                         } else {
                   9040:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   9041:                         }
                   9042:                     }
1.745     raeburn  9043:                 }
                   9044:             }
                   9045:         }
1.970     raeburn  9046:         my ($group);
                   9047:         if (&is_course($domain,$user)) {
                   9048:             ($group,my $file) = split(/\//,$file_name,2);
                   9049:         }
1.749     raeburn  9050:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   9051:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   9052:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   9053:         #  remove lock
                   9054:         my @del_lock = ($file_name."\0".'locked_access_records');
                   9055:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  9056:         my $sqlresult =
1.970     raeburn  9057:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  9058:                                     $group);
1.749     raeburn  9059:     } else {
                   9060:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  9061:     }
1.749     raeburn  9062:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  9063: }
                   9064: 
1.827     raeburn  9065: sub make_public_indefinitely {
                   9066:     my ($requrl) = @_;
                   9067:     my $now = time;
                   9068:     my $action = 'activate';
                   9069:     my $aclnum = 0;
                   9070:     if (&is_portfolio_url($requrl)) {
                   9071:         my (undef,$udom,$unum,$file_name,$group) =
                   9072:             &parse_portfolio_url($requrl);
                   9073:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   9074:         my %access_controls = &get_access_controls($current_perms,
                   9075:                                                    $group,$file_name);
                   9076:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   9077:             my ($num,$scope,$end,$start) = 
                   9078:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   9079:             if ($scope eq 'public') {
                   9080:                 if ($start <= $now && $end == 0) {
                   9081:                     $action = 'none';
                   9082:                 } else {
                   9083:                     $action = 'update';
                   9084:                     $aclnum = $num;
                   9085:                 }
                   9086:                 last;
                   9087:             }
                   9088:         }
                   9089:         if ($action eq 'none') {
                   9090:              return 'ok';
                   9091:         } else {
                   9092:             my %changes;
                   9093:             my $newend = 0;
                   9094:             my $newstart = $now;
                   9095:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   9096:             $changes{$action}{$newkey} = {
                   9097:                 type => 'public',
                   9098:                 time => {
                   9099:                     start => $newstart,
                   9100:                     end   => $newend,
                   9101:                 },
                   9102:             };
                   9103:             my ($outcome,$deloutcome,$new_values,$translation) =
                   9104:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   9105:             return $outcome;
                   9106:         }
                   9107:     } else {
                   9108:         return 'invalid';
                   9109:     }
                   9110: }
                   9111: 
1.745     raeburn  9112: #------------------------------------------------------Get Marked as Read Only
                   9113: 
                   9114: sub get_marked_as_readonly {
                   9115:     my ($domain,$user,$what,$group) = @_;
                   9116:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 9117:     my @readonly_files;
1.629     banghart 9118:     my $cmp1=$what;
                   9119:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  9120:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9121:         if (defined($group)) {
                   9122:             if ($file_name !~ m-^\Q$group\E/-) {
                   9123:                 next;
                   9124:             }
                   9125:         }
1.561     banghart 9126:         if (ref($value) eq "ARRAY"){
                   9127:             foreach my $stored_what (@{$value}) {
1.629     banghart 9128:                 my $cmp2=$stored_what;
1.759     albertel 9129:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  9130:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  9131:                 }
1.629     banghart 9132:                 if ($cmp1 eq $cmp2) {
1.561     banghart 9133:                     push(@readonly_files, $file_name);
1.745     raeburn  9134:                     last;
1.563     banghart 9135:                 } elsif (!defined($what)) {
                   9136:                     push(@readonly_files, $file_name);
1.745     raeburn  9137:                     last;
1.561     banghart 9138:                 }
                   9139:             }
1.745     raeburn  9140:         }
1.561     banghart 9141:     }
                   9142:     return @readonly_files;
                   9143: }
1.577     banghart 9144: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 9145: 
1.577     banghart 9146: sub get_marked_as_readonly_hash {
1.745     raeburn  9147:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 9148:     my %readonly_files;
1.745     raeburn  9149:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9150:         if (defined($group)) {
                   9151:             if ($file_name !~ m-^\Q$group\E/-) {
                   9152:                 next;
                   9153:             }
                   9154:         }
1.577     banghart 9155:         if (ref($value) eq "ARRAY"){
                   9156:             foreach my $stored_what (@{$value}) {
1.745     raeburn  9157:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 9158:                     foreach my $lock_descriptor(@{$stored_what}) {
                   9159:                         if ($lock_descriptor eq 'graded') {
                   9160:                             $readonly_files{$file_name} = 'graded';
                   9161:                         } elsif ($lock_descriptor eq 'handback') {
                   9162:                             $readonly_files{$file_name} = 'handback';
                   9163:                         } else {
                   9164:                             if (!exists($readonly_files{$file_name})) {
                   9165:                                 $readonly_files{$file_name} = 'locked';
                   9166:                             }
                   9167:                         }
1.745     raeburn  9168:                     }
1.750     banghart 9169:                 } 
1.577     banghart 9170:             }
                   9171:         } 
                   9172:     }
                   9173:     return %readonly_files;
                   9174: }
1.559     banghart 9175: # ------------------------------------------------------------ Unmark as Read Only
                   9176: 
                   9177: sub unmark_as_readonly {
1.629     banghart 9178:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   9179:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  9180:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 9181:     $file_name = &declutter_portfile($file_name);
1.634     albertel 9182:     my $symb_crs = $what;
                   9183:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  9184:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 9185:     my ($tmp)=keys(%current_permissions);
                   9186:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9187:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 9188:     foreach my $file (@readonly_files) {
1.759     albertel 9189: 	my $clean_file = &declutter_portfile($file);
                   9190: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 9191: 	my $current_locks = $current_permissions{$file};
1.563     banghart 9192:         my @new_locks;
                   9193:         my @del_keys;
                   9194:         if (ref($current_locks) eq "ARRAY"){
                   9195:             foreach my $locker (@{$current_locks}) {
1.632     albertel 9196:                 my $compare=$locker;
1.749     raeburn  9197:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  9198:                     $compare=join('',@{$locker});
1.746     raeburn  9199:                     if ($compare ne $symb_crs) {
                   9200:                         push(@new_locks, $locker);
                   9201:                     }
1.563     banghart 9202:                 }
                   9203:             }
1.650     albertel 9204:             if (scalar(@new_locks) > 0) {
1.563     banghart 9205:                 $current_permissions{$file} = \@new_locks;
                   9206:             } else {
                   9207:                 push(@del_keys, $file);
1.613     albertel 9208:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 9209:                 delete($current_permissions{$file});
1.563     banghart 9210:             }
                   9211:         }
1.561     banghart 9212:     }
1.613     albertel 9213:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9214:     return;
                   9215: }
1.512     banghart 9216: 
1.17      www      9217: # ------------------------------------------------------------ Directory lister
                   9218: 
                   9219: sub dirlist {
1.955     raeburn  9220:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      9221:     $uri=~s/^\///;
                   9222:     $uri=~s/\/$//;
1.253     stredwic 9223:     my ($udom, $uname);
1.955     raeburn  9224:     if ($getuserdir) {
1.253     stredwic 9225:         $udom = $userdomain;
                   9226:         $uname = $username;
1.955     raeburn  9227:     } else {
                   9228:         (undef,$udom,$uname)=split(/\//,$uri);
                   9229:         if(defined($userdomain)) {
                   9230:             $udom = $userdomain;
                   9231:         }
                   9232:         if(defined($username)) {
                   9233:             $uname = $username;
                   9234:         }
1.253     stredwic 9235:     }
1.955     raeburn  9236:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 9237: 
1.955     raeburn  9238:     $dirRoot = $perlvar{'lonDocRoot'};
                   9239:     if (defined($getpropath)) {
                   9240:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 9241:         $dirRoot =~ s/\/$//;
1.955     raeburn  9242:     } elsif (defined($getuserdir)) {
                   9243:         my $subdir=$uname.'__';
                   9244:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   9245:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   9246:                    ."/$udom/$subdir/$uname";
                   9247:     } elsif (defined($alternateRoot)) {
                   9248:         $dirRoot = $alternateRoot;
1.751     banghart 9249:     }
1.253     stredwic 9250: 
                   9251:     if($udom) {
                   9252:         if($uname) {
1.1135    raeburn  9253:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  9254:             if ($uhome eq 'no_host') {
                   9255:                 return ([],'no_host');
                   9256:             }
1.955     raeburn  9257:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  9258:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  9259:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  9260:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9261:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  9262:             } else {
                   9263:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9264:             }
1.605     matthew  9265:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9266:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  9267:                 @listing_results = split(/:/,$listing);
                   9268:             } else {
                   9269:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9270:             }
1.1135    raeburn  9271:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  9272:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9273:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9274:                 return ([],$listing);
                   9275:             } else {
                   9276:                 return (\@listing_results);
1.1135    raeburn  9277:             }
1.955     raeburn  9278:         } elsif(!$alternateRoot) {
1.1136    raeburn  9279:             my (%allusers,%listerror);
1.841     albertel 9280: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  9281:  	    foreach my $tryserver (keys(%servers)) {
                   9282:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   9283:                                   &escape($udom),$tryserver);
                   9284:                 if ($listing eq 'unknown_cmd') {
                   9285: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9286: 				      $udom, $tryserver);
                   9287:                 } else {
                   9288:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9289:                 }
1.841     albertel 9290: 		if ($listing eq 'unknown_cmd') {
                   9291: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9292: 				      $udom, $tryserver);
                   9293: 		    @listing_results = split(/:/,$listing);
                   9294: 		} else {
                   9295: 		    @listing_results =
                   9296: 			map { &unescape($_); } split(/:/,$listing);
                   9297: 		}
1.1136    raeburn  9298:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   9299:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9300:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9301:                     $listerror{$tryserver} = $listing;
                   9302:                 } else {
1.841     albertel 9303: 		    foreach my $line (@listing_results) {
                   9304: 			my ($entry) = split(/&/,$line,2);
                   9305: 			$allusers{$entry} = 1;
                   9306: 		    }
                   9307: 		}
1.253     stredwic 9308:             }
1.1136    raeburn  9309:             my @alluserslist=();
1.800     albertel 9310:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  9311:                 push(@alluserslist,$user.'&user');
1.253     stredwic 9312:             }
1.1136    raeburn  9313:             return (\@alluserslist);
1.253     stredwic 9314:         } else {
1.1136    raeburn  9315:             return ([],'missing username');
1.253     stredwic 9316:         }
1.955     raeburn  9317:     } elsif(!defined($getpropath)) {
1.1136    raeburn  9318:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   9319:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   9320:         return (\@all_domains);
1.955     raeburn  9321:     } else {
1.1136    raeburn  9322:         return ([],'missing domain');
1.275     stredwic 9323:     }
                   9324: }
                   9325: 
                   9326: # --------------------------------------------- GetFileTimestamp
                   9327: # This function utilizes dirlist and returns the date stamp for
                   9328: # when it was last modified.  It will also return an error of -1
                   9329: # if an error occurs
                   9330: 
                   9331: sub GetFileTimestamp {
1.955     raeburn  9332:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 9333:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   9334:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  9335:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   9336:                                     undef,$getuserdir);
                   9337:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9338:         return -1;
                   9339:     }
                   9340:     if (ref($fileref) eq 'ARRAY') {
                   9341:         my @stats = split('&',$fileref->[0]);
1.375     matthew  9342:         # @stats contains first the filename, then the stat output
                   9343:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 9344:     } else {
                   9345:         return -1;
1.253     stredwic 9346:     }
1.26      www      9347: }
                   9348: 
1.712     albertel 9349: sub stat_file {
                   9350:     my ($uri) = @_;
1.787     albertel 9351:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 9352: 
1.955     raeburn  9353:     my ($udom,$uname,$file);
1.712     albertel 9354:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   9355: 	($udom,$uname,$file) =
1.811     albertel 9356: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 9357: 	$file = 'userfiles/'.$file;
                   9358:     }
                   9359:     if ($uri =~ m-^/res/-) {
                   9360: 	($udom,$uname) = 
1.807     albertel 9361: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 9362: 	$file = $uri;
                   9363:     }
                   9364: 
                   9365:     if (!$udom || !$uname || !$file) {
                   9366: 	# unable to handle the uri
                   9367: 	return ();
                   9368:     }
1.956     raeburn  9369:     my $getpropath;
                   9370:     if ($file =~ /^userfiles\//) {
                   9371:         $getpropath = 1;
                   9372:     }
1.1136    raeburn  9373:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   9374:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9375:         return ();
                   9376:     } else {
                   9377:         if (ref($listref) eq 'ARRAY') {
                   9378:             my @stats = split('&',$listref->[0]);
                   9379: 	    shift(@stats); #filename is first
                   9380: 	    return @stats;
                   9381:         }
1.712     albertel 9382:     }
                   9383:     return ();
                   9384: }
                   9385: 
1.26      www      9386: # -------------------------------------------------------- Value of a Condition
                   9387: 
1.713     albertel 9388: # gets the value of a specific preevaluated condition
                   9389: #    stored in the string  $env{user.state.<cid>}
                   9390: # or looks up a condition reference in the bighash and if if hasn't
                   9391: # already been evaluated recurses into docondval to get the value of
                   9392: # the condition, then memoizing it to 
                   9393: #   $env{user.state.<cid>.<condition>}
1.40      www      9394: sub directcondval {
                   9395:     my $number=shift;
1.620     albertel 9396:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 9397: 	&Apache::lonuserstate::evalstate();
                   9398:     }
1.713     albertel 9399:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   9400: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   9401:     } elsif ($number =~ /^_/) {
                   9402: 	my $sub_condition;
                   9403: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   9404: 		&GDBM_READER(),0640)) {
                   9405: 	    $sub_condition=$bighash{'conditions'.$number};
                   9406: 	    untie(%bighash);
                   9407: 	}
                   9408: 	my $value = &docondval($sub_condition);
1.949     raeburn  9409: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 9410: 	return $value;
                   9411:     }
1.620     albertel 9412:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   9413:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      9414:     } else {
                   9415:        return 2;
                   9416:     }
                   9417: }
                   9418: 
1.713     albertel 9419: # get the collection of conditions for this resource
1.26      www      9420: sub condval {
                   9421:     my $condidx=shift;
1.54      www      9422:     my $allpathcond='';
1.713     albertel 9423:     foreach my $cond (split(/\|/,$condidx)) {
                   9424: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   9425: 	    $allpathcond.=
                   9426: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   9427: 	}
1.191     harris41 9428:     }
1.54      www      9429:     $allpathcond=~s/\|$//;
1.713     albertel 9430:     return &docondval($allpathcond);
                   9431: }
                   9432: 
                   9433: #evaluates an expression of conditions
                   9434: sub docondval {
                   9435:     my ($allpathcond) = @_;
                   9436:     my $result=0;
                   9437:     if ($env{'request.course.id'}
                   9438: 	&& defined($allpathcond)) {
                   9439: 	my $operand='|';
                   9440: 	my @stack;
                   9441: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   9442: 	    if ($chunk eq '(') {
                   9443: 		push @stack,($operand,$result);
                   9444: 	    } elsif ($chunk eq ')') {
                   9445: 		my $before=pop @stack;
                   9446: 		if (pop @stack eq '&') {
                   9447: 		    $result=$result>$before?$before:$result;
                   9448: 		} else {
                   9449: 		    $result=$result>$before?$result:$before;
                   9450: 		}
                   9451: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   9452: 		$operand=$chunk;
                   9453: 	    } else {
                   9454: 		my $new=directcondval($chunk);
                   9455: 		if ($operand eq '&') {
                   9456: 		    $result=$result>$new?$new:$result;
                   9457: 		} else {
                   9458: 		    $result=$result>$new?$result:$new;
                   9459: 		}
                   9460: 	    }
                   9461: 	}
1.26      www      9462:     }
                   9463:     return $result;
1.421     albertel 9464: }
                   9465: 
                   9466: # ---------------------------------------------------- Devalidate courseresdata
                   9467: 
                   9468: sub devalidatecourseresdata {
                   9469:     my ($coursenum,$coursedomain)=@_;
                   9470:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9471:     &devalidate_cache_new('courseres',$hashid);
1.28      www      9472: }
                   9473: 
1.763     www      9474: 
1.200     www      9475: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     9476: #
                   9477: #  Parameters:
                   9478: #      $coursenum    - Number of the course.
                   9479: #      $coursedomain - Domain at which the course was created.
                   9480: #  Returns:
                   9481: #     A hash of the course parameters along (I think) with timestamps
                   9482: #     and version info.
1.877     foxr     9483: 
1.624     albertel 9484: sub get_courseresdata {
                   9485:     my ($coursenum,$coursedomain)=@_;
1.200     www      9486:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   9487:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9488:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 9489:     my %dumpreply;
1.417     albertel 9490:     unless (defined($cached)) {
1.624     albertel 9491: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 9492: 	$result=\%dumpreply;
1.251     albertel 9493: 	my ($tmp) = keys(%dumpreply);
                   9494: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 9495: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 9496: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   9497: 	    return $tmp;
1.416     albertel 9498: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 9499: 	    $result=undef;
1.599     albertel 9500: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 9501: 	}
                   9502:     }
1.624     albertel 9503:     return $result;
                   9504: }
                   9505: 
1.633     albertel 9506: sub devalidateuserresdata {
                   9507:     my ($uname,$udom)=@_;
                   9508:     my $hashid="$udom:$uname";
                   9509:     &devalidate_cache_new('userres',$hashid);
                   9510: }
                   9511: 
1.624     albertel 9512: sub get_userresdata {
                   9513:     my ($uname,$udom)=@_;
                   9514:     #most student don\'t have any data set, check if there is some data
                   9515:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   9516: 
                   9517:     my $hashid="$udom:$uname";
                   9518:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   9519:     if (!defined($cached)) {
                   9520: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   9521: 	$result=\%resourcedata;
                   9522: 	&do_cache_new('userres',$hashid,$result,600);
                   9523:     }
                   9524:     my ($tmp)=keys(%$result);
                   9525:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   9526: 	return $result;
                   9527:     }
                   9528:     #error 2 occurs when the .db doesn't exist
                   9529:     if ($tmp!~/error: 2 /) {
1.672     albertel 9530: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 9531: 		 " Trying to get resource data for ".
                   9532: 		 $uname." at ".$udom.": ".
                   9533: 		 $tmp."</font>");
                   9534:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 9535: 	#&EXT_cache_set($udom,$uname);
                   9536: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 9537: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 9538:     }
                   9539:     return $tmp;
                   9540: }
1.879     foxr     9541: #----------------------------------------------- resdata - return resource data
                   9542: #  Purpose:
                   9543: #    Return resource data for either users or for a course.
                   9544: #  Parameters:
                   9545: #     $name      - Course/user name.
                   9546: #     $domain    - Name of the domain the user/course is registered on.
                   9547: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   9548: #     @which     - Array of names of resources desired.
                   9549: #  Returns:
                   9550: #     The value of the first reasource in @which that is found in the
                   9551: #     resource hash.
                   9552: #  Exceptional Conditions:
                   9553: #     If the $type passed in is not valid (not the string 'course' or 
                   9554: #     'user', an undefined  reference is returned.
                   9555: #     If none of the resources are found, an undef is returned
1.624     albertel 9556: sub resdata {
                   9557:     my ($name,$domain,$type,@which)=@_;
                   9558:     my $result;
                   9559:     if ($type eq 'course') {
                   9560: 	$result=&get_courseresdata($name,$domain);
                   9561:     } elsif ($type eq 'user') {
                   9562: 	$result=&get_userresdata($name,$domain);
                   9563:     }
                   9564:     if (!ref($result)) { return $result; }    
1.251     albertel 9565:     foreach my $item (@which) {
1.927     albertel 9566: 	if (defined($result->{$item->[0]})) {
                   9567: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 9568: 	}
1.250     albertel 9569:     }
1.291     albertel 9570:     return undef;
1.200     www      9571: }
                   9572: 
1.379     matthew  9573: #
                   9574: # EXT resource caching routines
                   9575: #
                   9576: 
                   9577: sub clear_EXT_cache_status {
1.383     albertel 9578:     &delenv('cache.EXT.');
1.379     matthew  9579: }
                   9580: 
                   9581: sub EXT_cache_status {
                   9582:     my ($target_domain,$target_user) = @_;
1.383     albertel 9583:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 9584:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  9585:         # We know already the user has no data
                   9586:         return 1;
                   9587:     } else {
                   9588:         return 0;
                   9589:     }
                   9590: }
                   9591: 
                   9592: sub EXT_cache_set {
                   9593:     my ($target_domain,$target_user) = @_;
1.383     albertel 9594:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  9595:     #&appenv({$cachename => time});
1.379     matthew  9596: }
                   9597: 
1.28      www      9598: # --------------------------------------------------------- Value of a Variable
1.58      www      9599: sub EXT {
1.715     albertel 9600: 
1.395     albertel 9601:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      9602:     unless ($varname) { return ''; }
1.218     albertel 9603:     #get real user name/domain, courseid and symb
                   9604:     my $courseid;
1.359     albertel 9605:     my $publicuser;
1.427     www      9606:     if ($symbparm) {
                   9607: 	$symbparm=&get_symb_from_alias($symbparm);
                   9608:     }
1.218     albertel 9609:     if (!($uname && $udom)) {
1.790     albertel 9610:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 9611:       if (!$symbparm) {	$symbparm=$cursymb; }
                   9612:     } else {
1.620     albertel 9613: 	$courseid=$env{'request.course.id'};
1.218     albertel 9614:     }
1.48      www      9615:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   9616:     my $rest;
1.320     albertel 9617:     if (defined($therest[0])) {
1.48      www      9618:        $rest=join('.',@therest);
                   9619:     } else {
                   9620:        $rest='';
                   9621:     }
1.320     albertel 9622: 
1.57      www      9623:     my $qualifierrest=$qualifier;
                   9624:     if ($rest) { $qualifierrest.='.'.$rest; }
                   9625:     my $spacequalifierrest=$space;
                   9626:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      9627:     if ($realm eq 'user') {
1.48      www      9628: # --------------------------------------------------------------- user.resource
                   9629: 	if ($space eq 'resource') {
1.651     albertel 9630: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   9631: 		  || defined($Apache::lonhomework::parsing_a_task))
                   9632: 		 &&
1.744     albertel 9633: 		 ($symbparm eq &symbread()) ) {	
                   9634: 		# if we are in the middle of processing the resource the
                   9635: 		# get the value we are planning on committing
                   9636:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   9637:                     return $Apache::lonhomework::results{$qualifierrest};
                   9638:                 } else {
                   9639:                     return $Apache::lonhomework::history{$qualifierrest};
                   9640:                 }
1.335     albertel 9641: 	    } else {
1.359     albertel 9642: 		my %restored;
1.620     albertel 9643: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 9644: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   9645: 		} else {
                   9646: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   9647: 		}
1.335     albertel 9648: 		return $restored{$qualifierrest};
                   9649: 	    }
1.48      www      9650: # ----------------------------------------------------------------- user.access
                   9651:         } elsif ($space eq 'access') {
1.218     albertel 9652: 	    # FIXME - not supporting calls for a specific user
1.48      www      9653:             return &allowed($qualifier,$rest);
                   9654: # ------------------------------------------ user.preferences, user.environment
                   9655:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 9656: 	    if (($uname eq $env{'user.name'}) &&
                   9657: 		($udom eq $env{'user.domain'})) {
                   9658: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 9659: 	    } else {
1.359     albertel 9660: 		my %returnhash;
                   9661: 		if (!$publicuser) {
                   9662: 		    %returnhash=&userenvironment($udom,$uname,
                   9663: 						 $qualifierrest);
                   9664: 		}
1.218     albertel 9665: 		return $returnhash{$qualifierrest};
                   9666: 	    }
1.48      www      9667: # ----------------------------------------------------------------- user.course
                   9668:         } elsif ($space eq 'course') {
1.218     albertel 9669: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9670:             return $env{join('.',('request.course',$qualifier))};
1.48      www      9671: # ------------------------------------------------------------------- user.role
                   9672:         } elsif ($space eq 'role') {
1.218     albertel 9673: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9674:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      9675:             if ($qualifier eq 'value') {
                   9676: 		return $role;
                   9677:             } elsif ($qualifier eq 'extent') {
                   9678:                 return $where;
                   9679:             }
                   9680: # ----------------------------------------------------------------- user.domain
                   9681:         } elsif ($space eq 'domain') {
1.218     albertel 9682:             return $udom;
1.48      www      9683: # ------------------------------------------------------------------- user.name
                   9684:         } elsif ($space eq 'name') {
1.218     albertel 9685:             return $uname;
1.48      www      9686: # ---------------------------------------------------- Any other user namespace
1.29      www      9687:         } else {
1.359     albertel 9688: 	    my %reply;
                   9689: 	    if (!$publicuser) {
                   9690: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   9691: 	    }
                   9692: 	    return $reply{$qualifierrest};
1.48      www      9693:         }
1.236     www      9694:     } elsif ($realm eq 'query') {
                   9695: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 9696:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   9697: 						[$spacequalifierrest]);
1.620     albertel 9698: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      9699:    } elsif ($realm eq 'request') {
1.48      www      9700: # ------------------------------------------------------------- request.browser
                   9701:         if ($space eq 'browser') {
1.1145    bisitz   9702:             return $env{'browser.'.$qualifier};
1.57      www      9703: # ------------------------------------------------------------ request.filename
                   9704:         } else {
1.620     albertel 9705:             return $env{'request.'.$spacequalifierrest};
1.29      www      9706:         }
1.28      www      9707:     } elsif ($realm eq 'course') {
1.48      www      9708: # ---------------------------------------------------------- course.description
1.620     albertel 9709:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      9710:     } elsif ($realm eq 'resource') {
1.165     www      9711: 
1.620     albertel 9712: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 9713: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   9714: 	}
1.693     albertel 9715: 
                   9716: 	if ($space eq 'title') {
                   9717: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   9718: 	    return &gettitle($symbparm);
                   9719: 	}
                   9720: 	
                   9721: 	if ($space eq 'map') {
                   9722: 	    my ($map) = &decode_symb($symbparm);
                   9723: 	    return &symbread($map);
                   9724: 	}
1.905     albertel 9725: 	if ($space eq 'filename') {
                   9726: 	    if ($symbparm) {
                   9727: 		return &clutter((&decode_symb($symbparm))[2]);
                   9728: 	    }
                   9729: 	    return &hreflocation('',$env{'request.filename'});
                   9730: 	}
1.693     albertel 9731: 
                   9732: 	my ($section, $group, @groups);
1.593     albertel 9733: 	my ($courselevelm,$courselevel);
1.539     albertel 9734: 	if ($symbparm && defined($courseid) && 
1.620     albertel 9735: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      9736: 
1.218     albertel 9737: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      9738: 
1.60      www      9739: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 9740: 	    my $symbp=$symbparm;
1.735     albertel 9741: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 9742: 
                   9743: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   9744: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   9745: 
1.620     albertel 9746: 	    if (($env{'user.name'} eq $uname) &&
                   9747: 		($env{'user.domain'} eq $udom)) {
                   9748: 		$section=$env{'request.course.sec'};
1.733     raeburn  9749:                 @groups = split(/:/,$env{'request.course.groups'});  
                   9750:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 9751: 	    } else {
1.539     albertel 9752: 		if (! defined($usection)) {
1.551     albertel 9753: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 9754: 		} else {
                   9755: 		    $section = $usection;
                   9756: 		}
1.733     raeburn  9757:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 9758: 	    }
                   9759: 
                   9760: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   9761: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   9762: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   9763: 
1.593     albertel 9764: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 9765: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 9766: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      9767: 
1.60      www      9768: # ----------------------------------------------------------- first, check user
1.624     albertel 9769: 
                   9770: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 9771: 				       ([$courselevelr,'resource'],
                   9772: 					[$courselevelm,'map'     ],
                   9773: 					[$courselevel, 'course'  ]));
1.931     albertel 9774: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      9775: 
1.594     albertel 9776: # ------------------------------------------------ second, check some of course
1.684     raeburn  9777:             my $coursereply;
1.691     raeburn  9778:             if (@groups > 0) {
                   9779:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   9780:                                        $mapparm,$spacequalifierrest);
1.927     albertel 9781:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  9782:             }
1.96      www      9783: 
1.684     raeburn  9784: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 9785: 				  $env{'course.'.$courseid.'.domain'},
                   9786: 				  'course',
                   9787: 				  ([$seclevelr,   'resource'],
                   9788: 				   [$seclevelm,   'map'     ],
                   9789: 				   [$seclevel,    'course'  ],
                   9790: 				   [$courselevelr,'resource']));
                   9791: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      9792: 
1.60      www      9793: # ------------------------------------------------------ third, check map parms
1.218     albertel 9794: 	    my %parmhash=();
                   9795: 	    my $thisparm='';
                   9796: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 9797: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 9798: 		    &GDBM_READER(),0640)) {
1.218     albertel 9799: 		$thisparm=$parmhash{$symbparm};
                   9800: 		untie(%parmhash);
                   9801: 	    }
1.927     albertel 9802: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 9803: 	}
1.594     albertel 9804: # ------------------------------------------ fourth, look in resource metadata
1.71      www      9805: 
1.218     albertel 9806: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 9807: 	my $filename;
                   9808: 	if (!$symbparm) { $symbparm=&symbread(); }
                   9809: 	if ($symbparm) {
1.409     www      9810: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 9811: 	} else {
1.620     albertel 9812: 	    $filename=$env{'request.filename'};
1.282     albertel 9813: 	}
                   9814: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 9815: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 9816: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 9817: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      9818: 
1.927     albertel 9819: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 9820: 	if ($symbparm && defined($courseid) && 
1.620     albertel 9821: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 9822: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   9823: 				     $env{'course.'.$courseid.'.domain'},
                   9824: 				     'course',
1.927     albertel 9825: 				     ([$courselevelm,'map'   ],
                   9826: 				      [$courselevel, 'course']));
                   9827: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 9828: 	}
1.145     www      9829: # ------------------------------------------------------------------ Cascade up
1.218     albertel 9830: 	unless ($space eq '0') {
1.336     albertel 9831: 	    my @parts=split(/_/,$space);
                   9832: 	    my $id=pop(@parts);
                   9833: 	    my $part=join('_',@parts);
                   9834: 	    if ($part eq '') { $part='0'; }
1.927     albertel 9835: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 9836: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  9837: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 9838: 	}
1.395     albertel 9839: 	if ($recurse) { return undef; }
                   9840: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 9841: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      9842: # ---------------------------------------------------- Any other user namespace
                   9843:     } elsif ($realm eq 'environment') {
                   9844: # ----------------------------------------------------------------- environment
1.620     albertel 9845: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   9846: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 9847: 	} else {
1.770     albertel 9848: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   9849: 		return '';
                   9850: 	    }
1.219     albertel 9851: 	    my %returnhash=&userenvironment($udom,$uname,
                   9852: 					    $spacequalifierrest);
                   9853: 	    return $returnhash{$spacequalifierrest};
                   9854: 	}
1.28      www      9855:     } elsif ($realm eq 'system') {
1.48      www      9856: # ----------------------------------------------------------------- system.time
                   9857: 	if ($space eq 'time') {
                   9858: 	    return time;
                   9859:         }
1.696     albertel 9860:     } elsif ($realm eq 'server') {
                   9861: # ----------------------------------------------------------------- system.time
                   9862: 	if ($space eq 'name') {
                   9863: 	    return $ENV{'SERVER_NAME'};
                   9864:         }
1.28      www      9865:     }
1.48      www      9866:     return '';
1.61      www      9867: }
                   9868: 
1.927     albertel 9869: sub get_reply {
                   9870:     my ($reply_value) = @_;
1.940     raeburn  9871:     if (ref($reply_value) eq 'ARRAY') {
                   9872:         if (wantarray) {
                   9873: 	    return @$reply_value;
                   9874:         }
                   9875:         return $reply_value->[0];
                   9876:     } else {
                   9877:         return $reply_value;
1.927     albertel 9878:     }
                   9879: }
                   9880: 
1.691     raeburn  9881: sub check_group_parms {
                   9882:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   9883:     my @groupitems = ();
                   9884:     my $resultitem;
1.927     albertel 9885:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  9886:     foreach my $group (@{$groups}) {
                   9887:         foreach my $level (@levels) {
1.927     albertel 9888:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   9889:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  9890:         }
                   9891:     }
                   9892:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   9893:                             $env{'course.'.$courseid.'.domain'},
                   9894:                                      'course',@groupitems);
                   9895:     return $coursereply;
                   9896: }
                   9897: 
                   9898: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  9899:     my ($courseid,@groups) = @_;
                   9900:     @groups = sort(@groups);
1.691     raeburn  9901:     return @groups;
                   9902: }
                   9903: 
1.395     albertel 9904: sub packages_tab_default {
                   9905:     my ($uri,$varname)=@_;
                   9906:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 9907: 
                   9908:     my (@extension,@specifics,$do_default);
                   9909:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 9910: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 9911: 	if ($pack_type eq 'default') {
                   9912: 	    $do_default=1;
                   9913: 	} elsif ($pack_type eq 'extension') {
                   9914: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 9915: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 9916: 	    # only look at packages defaults for packages that this id is
1.738     albertel 9917: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   9918: 	}
                   9919:     }
                   9920:     # first look for a package that matches the requested part id
                   9921:     foreach my $package (@specifics) {
                   9922: 	my (undef,$pack_type,$pack_part)=@{$package};
                   9923: 	next if ($pack_part ne $part);
                   9924: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9925: 	    return $packagetab{"$pack_type&$name&default"};
                   9926: 	}
                   9927:     }
                   9928:     # look for any possible matching non extension_ package
                   9929:     foreach my $package (@specifics) {
                   9930: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 9931: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9932: 	    return $packagetab{"$pack_type&$name&default"};
                   9933: 	}
1.585     albertel 9934: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 9935: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   9936: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 9937: 	}
                   9938:     }
1.738     albertel 9939:     # look for any posible extension_ match
                   9940:     foreach my $package (@extension) {
                   9941: 	my ($package,$pack_type)=@{$package};
                   9942: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9943: 	    return $packagetab{"$pack_type&$name&default"};
                   9944: 	}
                   9945: 	if (defined($packagetab{$package."&$name&default"})) {
                   9946: 	    return $packagetab{$package."&$name&default"};
                   9947: 	}
                   9948:     }
                   9949:     # look for a global default setting
                   9950:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   9951: 	return $packagetab{"default&$name&default"};
                   9952:     }
1.395     albertel 9953:     return undef;
                   9954: }
                   9955: 
1.334     albertel 9956: sub add_prefix_and_part {
                   9957:     my ($prefix,$part)=@_;
                   9958:     my $keyroot;
                   9959:     if (defined($prefix) && $prefix !~ /^__/) {
                   9960: 	# prefix that has a part already
                   9961: 	$keyroot=$prefix;
                   9962:     } elsif (defined($prefix)) {
                   9963: 	# prefix that is missing a part
                   9964: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   9965:     } else {
                   9966: 	# no prefix at all
                   9967: 	if (defined($part)) { $keyroot='_'.$part; }
                   9968:     }
                   9969:     return $keyroot;
                   9970: }
                   9971: 
1.71      www      9972: # ---------------------------------------------------------------- Get metadata
                   9973: 
1.599     albertel 9974: my %metaentry;
1.1070    www      9975: my %importedpartids;
1.71      www      9976: sub metadata {
1.176     www      9977:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      9978:     $uri=&declutter($uri);
1.288     albertel 9979:     # if it is a non metadata possible uri return quickly
1.529     albertel 9980:     if (($uri eq '') || 
                   9981: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.20  raeburn  9982: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108    raeburn  9983:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 9984: 	return undef;
                   9985:     }
1.1140    www      9986:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
1.924     albertel 9987: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 9988: 	return undef;
1.288     albertel 9989:     }
1.73      www      9990:     my $filename=$uri;
                   9991:     $uri=~s/\.meta$//;
1.172     www      9992: #
                   9993: # Is the metadata already cached?
1.177     www      9994: # Look at timestamp of caching
1.172     www      9995: # Everything is cached by the main uri, libraries are never directly cached
                   9996: #
1.428     albertel 9997:     if (!defined($liburi)) {
1.599     albertel 9998: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 9999: 	if (defined($cached)) { return $result->{':'.$what}; }
                   10000:     }
                   10001:     {
1.1069    www      10002: # Imported parts would go here
1.1070    www      10003:         my %importedids=();
                   10004:         my @origfileimportpartids=();
1.1069    www      10005:         my $importedparts=0;
1.172     www      10006: #
                   10007: # Is this a recursive call for a library?
                   10008: #
1.599     albertel 10009: #	if (! exists($metacache{$uri})) {
                   10010: #	    $metacache{$uri}={};
                   10011: #	}
1.924     albertel 10012: 	my $cachetime = 60*60;
1.171     www      10013:         if ($liburi) {
                   10014: 	    $liburi=&declutter($liburi);
                   10015:             $filename=$liburi;
1.401     bowersj2 10016:         } else {
1.599     albertel 10017: 	    &devalidate_cache_new('meta',$uri);
                   10018: 	    undef(%metaentry);
1.401     bowersj2 10019: 	}
1.140     www      10020:         my %metathesekeys=();
1.73      www      10021:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 10022: 	my $metastring;
1.1140    www      10023: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 10024: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 10025: 	    $metastring = 
1.929     albertel 10026: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 10027: 					  ('grade_target' => 'meta'));
                   10028: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  10029: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   10030:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 10031: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 10032: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 10033: 	    $metastring=&getfile($file);
1.489     albertel 10034: 	}
1.208     albertel 10035:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      10036:         my $token;
1.140     www      10037:         undef %metathesekeys;
1.71      www      10038:         while ($token=$parser->get_token) {
1.339     albertel 10039: 	    if ($token->[0] eq 'S') {
                   10040: 		if (defined($token->[2]->{'package'})) {
1.172     www      10041: #
                   10042: # This is a package - get package info
                   10043: #
1.339     albertel 10044: 		    my $package=$token->[2]->{'package'};
                   10045: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10046: 		    if (defined($token->[2]->{'id'})) { 
                   10047: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   10048: 		    }
1.599     albertel 10049: 		    if ($metaentry{':packages'}) {
                   10050: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 10051: 		    } else {
1.599     albertel 10052: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 10053: 		    }
1.736     albertel 10054: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 10055: 			my $part=$keyroot;
                   10056: 			$part=~s/^\_//;
1.736     albertel 10057: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   10058: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   10059: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 10060: 			    # ignore package.tab specified default values
                   10061:                             # here &package_tab_default() will fetch those
                   10062: 			    if ($subp eq 'default') { next; }
1.736     albertel 10063: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 10064: 			    my $unikey;
                   10065: 			    if ($pack =~ /_0$/) {
                   10066: 				$unikey='parameter_0_'.$name;
                   10067: 				$part=0;
                   10068: 			    } else {
                   10069: 				$unikey='parameter'.$keyroot.'_'.$name;
                   10070: 			    }
1.339     albertel 10071: 			    if ($subp eq 'display') {
                   10072: 				$value.=' [Part: '.$part.']';
                   10073: 			    }
1.599     albertel 10074: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 10075: 			    $metathesekeys{$unikey}=1;
1.599     albertel 10076: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10077: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 10078: 			    }
1.599     albertel 10079: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   10080: 				$metaentry{':'.$unikey}=
                   10081: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 10082: 			    }
1.339     albertel 10083: 			}
                   10084: 		    }
                   10085: 		} else {
1.172     www      10086: #
                   10087: # This is not a package - some other kind of start tag
1.339     albertel 10088: #
                   10089: 		    my $entry=$token->[1];
1.1068    www      10090: 		    my $unikey='';
1.175     www      10091: 
1.339     albertel 10092: 		    if ($entry eq 'import') {
1.175     www      10093: #
                   10094: # Importing a library here
1.339     albertel 10095: #
1.1067    www      10096:                         my $location=$parser->get_text('/import');
                   10097:                         my $dir=$filename;
                   10098:                         $dir=~s|[^/]*$||;
                   10099:                         $location=&filelocation($dir,$location);
1.1069    www      10100:                        
1.1068    www      10101:                         my $importmode=$token->[2]->{'importmode'};
                   10102:                         if ($importmode eq 'problem') {
1.1069    www      10103: # Import as problem/response
1.1068    www      10104:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10105:                         } elsif ($importmode eq 'part') {
                   10106: # Import as part(s)
1.1069    www      10107:                            $importedparts=1;
                   10108: # We need to get the original file and the imported file to get the part order correct
                   10109: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   10110: # Load and inspect original file
1.1070    www      10111:                            if ($#origfileimportpartids<0) {
                   10112:                               undef(%importedpartids);
                   10113:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   10114:                               my $origfile=&getfile($origfilelocation);
                   10115:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10116:                            }
                   10117: 
1.1069    www      10118: # Load and inspect imported file
                   10119:                            my $impfile=&getfile($location);
                   10120:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10121:                            if ($#impfilepartids>=0) {
                   10122: # This problem had parts
1.1070    www      10123:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      10124:                            } else {
                   10125: # Importing by turning a single problem into a problem part
                   10126: # It gets the import-tags ID as part-ID
                   10127:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      10128:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      10129:                            }
1.1068    www      10130:                         } else {
                   10131: # Normal import
                   10132:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10133:                            if (defined($token->[2]->{'id'})) {
                   10134:                               $unikey.='_'.$token->[2]->{'id'};
                   10135:                            }
1.1067    www      10136:                         }
                   10137: 
1.339     albertel 10138: 			if ($depthcount<20) {
1.736     albertel 10139: 			    my $metadata = 
                   10140: 				&metadata($uri,'keys', $location,$unikey,
                   10141: 					  $depthcount+1);
                   10142: 			    foreach my $meta (split(',',$metadata)) {
                   10143: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   10144: 				$metathesekeys{$meta}=1;
1.339     albertel 10145: 			    }
1.1068    www      10146: 			
                   10147:                         }
1.1067    www      10148: 		    } else {
                   10149: #
                   10150: # Not importing, some other kind of non-package, non-library start tag
                   10151: # 
                   10152:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10153:                         if (defined($token->[2]->{'id'})) {
                   10154:                             $unikey.='_'.$token->[2]->{'id'};
                   10155:                         }
1.339     albertel 10156: 			if (defined($token->[2]->{'name'})) { 
                   10157: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   10158: 			}
                   10159: 			$metathesekeys{$unikey}=1;
1.736     albertel 10160: 			foreach my $param (@{$token->[3]}) {
                   10161: 			    $metaentry{':'.$unikey.'.'.$param} =
                   10162: 				$token->[2]->{$param};
1.339     albertel 10163: 			}
                   10164: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 10165: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 10166: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   10167: 		 # only ws inside the tag, and not in default, so use default
                   10168: 		 # as value
1.599     albertel 10169: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 10170: 			} elsif ( $internaltext =~ /\S/ ) {
                   10171: 		  # something interesting inside the tag
                   10172: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 10173: 			} else {
1.908     albertel 10174: 		  # no interesting values, don't set a default
1.339     albertel 10175: 			}
1.172     www      10176: # end of not-a-package not-a-library import
1.339     albertel 10177: 		    }
1.172     www      10178: # end of not-a-package start tag
1.339     albertel 10179: 		}
1.172     www      10180: # the next is the end of "start tag"
1.339     albertel 10181: 	    }
                   10182: 	}
1.483     albertel 10183: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 10184: 	$extension = lc($extension);
                   10185: 	if ($extension eq 'htm') { $extension='html'; }
                   10186: 
1.737     albertel 10187: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 10188: 	    #no specific packages #how's our extension
                   10189: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 10190: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 10191: 					 \%metathesekeys);
                   10192: 	}
1.883     albertel 10193: 
                   10194: 	if (!exists($metaentry{':packages'})
                   10195: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 10196: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 10197: 		#no specific packages well let's get default then
                   10198: 		if ($key!~/^default&/) { next; }
1.488     albertel 10199: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 10200: 					     \%metathesekeys);
                   10201: 	    }
                   10202: 	}
1.338     www      10203: # are there custom rights to evaluate
1.599     albertel 10204: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 10205: 
1.338     www      10206:     #
                   10207:     # Importing a rights file here
1.339     albertel 10208:     #
                   10209: 	    unless ($depthcount) {
1.599     albertel 10210: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 10211: 		my $dir=$filename;
                   10212: 		$dir=~s|[^/]*$||;
                   10213: 		$location=&filelocation($dir,$location);
1.736     albertel 10214: 		my $rights_metadata =
                   10215: 		    &metadata($uri,'keys',$location,'_rights',
                   10216: 			      $depthcount+1);
                   10217: 		foreach my $rights (split(',',$rights_metadata)) {
                   10218: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   10219: 		    $metathesekeys{$rights}=1;
1.339     albertel 10220: 		}
                   10221: 	    }
                   10222: 	}
1.737     albertel 10223: 	# uniqifiy package listing
                   10224: 	my %seen;
                   10225: 	my @uniq_packages =
                   10226: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   10227: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   10228: 
1.1070    www      10229:         if ($importedparts) {
                   10230: # We had imported parts and need to rebuild partorder
                   10231:            $metaentry{':partorder'}='';
                   10232:            $metathesekeys{'partorder'}=1;
                   10233:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   10234:                if ($origfileimportpartids[$index] eq 'part') {
                   10235: # original part, part of the problem
                   10236:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   10237:                } else {
                   10238: # we have imported parts at this position
                   10239:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   10240:                }
                   10241:            }
                   10242:            $metaentry{':partorder'}=~s/^\,//;
                   10243:         }
                   10244: 
1.737     albertel 10245: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 10246: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   10247: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 10248: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      10249: # this is the end of "was not already recently cached
1.71      www      10250:     }
1.599     albertel 10251:     return $metaentry{':'.$what};
1.261     albertel 10252: }
                   10253: 
1.488     albertel 10254: sub metadata_create_package_def {
1.483     albertel 10255:     my ($uri,$key,$package,$metathesekeys)=@_;
                   10256:     my ($pack,$name,$subp)=split(/\&/,$key);
                   10257:     if ($subp eq 'default') { next; }
                   10258:     
1.599     albertel 10259:     if (defined($metaentry{':packages'})) {
                   10260: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 10261:     } else {
1.599     albertel 10262: 	$metaentry{':packages'}=$package;
1.483     albertel 10263:     }
                   10264:     my $value=$packagetab{$key};
                   10265:     my $unikey;
                   10266:     $unikey='parameter_0_'.$name;
1.599     albertel 10267:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 10268:     $$metathesekeys{$unikey}=1;
1.599     albertel 10269:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10270: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 10271:     }
1.599     albertel 10272:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   10273: 	$metaentry{':'.$unikey}=
                   10274: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 10275:     }
                   10276: }
                   10277: 
1.261     albertel 10278: sub metadata_generate_part0 {
                   10279:     my ($metadata,$metacache,$uri) = @_;
                   10280:     my %allnames;
1.737     albertel 10281:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 10282: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 10283: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   10284: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 10285: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 10286: 	    $allnames{$name}=$part;
                   10287: 	  }
                   10288: 	}
                   10289:     }
                   10290:     foreach my $name (keys(%allnames)) {
                   10291:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 10292:       my $key=":parameter_0_$name";
1.261     albertel 10293:       $$metacache{"$key.part"}='0';
                   10294:       $$metacache{"$key.name"}=$name;
1.428     albertel 10295:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 10296: 					   $allnames{$name}.'_'.$name.
                   10297: 					   '.type'};
1.428     albertel 10298:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 10299: 			     '.display'};
1.644     www      10300:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 10301:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 10302:       $$metacache{"$key.display"}=$olddis;
                   10303:     }
1.71      www      10304: }
                   10305: 
1.764     albertel 10306: # ------------------------------------------------------ Devalidate title cache
                   10307: 
                   10308: sub devalidate_title_cache {
                   10309:     my ($url)=@_;
                   10310:     if (!$env{'request.course.id'}) { return; }
                   10311:     my $symb=&symbread($url);
                   10312:     if (!$symb) { return; }
                   10313:     my $key=$env{'request.course.id'}."\0".$symb;
                   10314:     &devalidate_cache_new('title',$key);
                   10315: }
                   10316: 
1.1014    droeschl 10317: # ------------------------------------------------- Get the title of a course
                   10318: 
                   10319: sub current_course_title {
                   10320:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   10321: }
1.301     www      10322: # ------------------------------------------------- Get the title of a resource
                   10323: 
                   10324: sub gettitle {
                   10325:     my $urlsymb=shift;
                   10326:     my $symb=&symbread($urlsymb);
1.534     albertel 10327:     if ($symb) {
1.620     albertel 10328: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 10329: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 10330: 	if (defined($cached)) { 
                   10331: 	    return $result;
                   10332: 	}
1.534     albertel 10333: 	my ($map,$resid,$url)=&decode_symb($symb);
                   10334: 	my $title='';
1.907     albertel 10335: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   10336: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   10337: 	} else {
                   10338: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10339: 		    &GDBM_READER(),0640)) {
                   10340: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   10341: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   10342: 		untie(%bighash);
                   10343: 	    }
1.534     albertel 10344: 	}
                   10345: 	$title=~s/\&colon\;/\:/gs;
                   10346: 	if ($title) {
1.1159    www      10347: # Remember both $symb and $title for dynamic metadata
                   10348:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      10349:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      10350: # Cache this title and then return it
1.599     albertel 10351: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 10352: 	}
                   10353: 	$urlsymb=$url;
                   10354:     }
                   10355:     my $title=&metadata($urlsymb,'title');
                   10356:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   10357:     return $title;
1.301     www      10358: }
1.613     albertel 10359: 
1.1172.2.13  raeburn  10360: sub getdocspath {
                   10361:     my ($symb) = @_;
                   10362:     my $path;
                   10363:     if ($symb) {
                   10364:         my ($mapurl,$id,$resurl) = &decode_symb($symb);
                   10365:         if ($resurl=~/\.(sequence|page)$/) {
                   10366:             $mapurl=$resurl;
                   10367:         } elsif ($resurl eq 'adm/navmaps') {
                   10368:             $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   10369:         }
                   10370:         my $mapresobj;
                   10371:         my $navmap = Apache::lonnavmaps::navmap->new();
                   10372:         if (ref($navmap)) {
                   10373:             $mapresobj = $navmap->getResourceByUrl($mapurl);
                   10374:         }
                   10375:         $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   10376:         my $type=$2;
                   10377:         if (ref($mapresobj)) {
                   10378:             my $pcslist = $mapresobj->map_hierarchy();
                   10379:             if ($pcslist ne '') {
                   10380:                 foreach my $pc (split(/,/,$pcslist)) {
                   10381:                     next if ($pc <= 1);
                   10382:                     my $res = $navmap->getByMapPc($pc);
                   10383:                     if (ref($res)) {
                   10384:                         my $thisurl = $res->src();
                   10385:                         $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   10386:                         my $thistitle = $res->title();
                   10387:                         $path .= '&'.
                   10388:                                  &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
                   10389:                                  &Apache::lonhtmlcommon::entity_encode($thistitle).
                   10390:                                  ':'.$res->randompick().
                   10391:                                  ':'.$res->randomout().
                   10392:                                  ':'.$res->encrypted().
                   10393:                                  ':'.$res->randomorder().
                   10394:                                  ':'.$res->is_page();
                   10395:                     }
                   10396:                 }
                   10397:             }
                   10398:             $path =~ s/^\&//;
                   10399:             my $maptitle = $mapresobj->title();
                   10400:             if ($mapurl eq 'default') {
                   10401:                 $maptitle = 'Main Course Documents';
                   10402:             }
                   10403:             $path .= ($path ne '')? '&' : ''.
                   10404:                     &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
                   10405:                     &Apache::lonhtmlcommon::entity_encode($maptitle).
                   10406:                     ':'.$mapresobj->randompick().
                   10407:                     ':'.$mapresobj->randomout().
                   10408:                     ':'.$mapresobj->encrypted().
                   10409:                     ':'.$mapresobj->randomorder().
                   10410:                     ':'.$mapresobj->is_page();
                   10411:         } else {
                   10412:             my $maptitle = &gettitle($mapurl);
                   10413:             my $ispage;
                   10414:             if ($mapurl =~ /\.page$/) {
                   10415:                 $ispage = 1;
                   10416:             }
                   10417:             if ($mapurl eq 'default') {
                   10418:                 $maptitle = 'Main Course Documents';
                   10419:             }
                   10420:             $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
                   10421:                     &Apache::lonhtmlcommon::entity_encode($maptitle).':::::'.$ispage;
                   10422:         }
                   10423:         unless ($mapurl eq 'default') {
                   10424:             $path = 'default&'.
                   10425:                     &Apache::lonhtmlcommon::entity_encode('Main Course Documents').
                   10426:                     ':::::&'.$path;
                   10427:         }
                   10428:     }
                   10429:     return $path;
                   10430: }
                   10431: 
1.614     albertel 10432: sub get_slot {
                   10433:     my ($which,$cnum,$cdom)=@_;
                   10434:     if (!$cnum || !$cdom) {
1.790     albertel 10435: 	(undef,my $courseid)=&whichuser();
1.620     albertel 10436: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   10437: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 10438:     }
1.703     albertel 10439:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   10440:     my %slotinfo;
                   10441:     if (exists($remembered{$key})) {
                   10442: 	$slotinfo{$which} = $remembered{$key};
                   10443:     } else {
                   10444: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   10445: 	&Apache::lonhomework::showhash(%slotinfo);
                   10446: 	my ($tmp)=keys(%slotinfo);
                   10447: 	if ($tmp=~/^error:/) { return (); }
                   10448: 	$remembered{$key} = $slotinfo{$which};
                   10449:     }
1.616     albertel 10450:     if (ref($slotinfo{$which}) eq 'HASH') {
                   10451: 	return %{$slotinfo{$which}};
                   10452:     }
                   10453:     return $slotinfo{$which};
1.614     albertel 10454: }
1.1150    raeburn  10455: 
                   10456: sub get_reservable_slots {
                   10457:     my ($cnum,$cdom,$uname,$udom) = @_;
                   10458:     my $now = time;
                   10459:     my $reservable_info;
                   10460:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   10461:     if (exists($remembered{$key})) {
                   10462:         $reservable_info = $remembered{$key};
                   10463:     } else {
                   10464:         my %resv;
                   10465:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   10466:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   10467:         $reservable_info = \%resv;
                   10468:         $remembered{$key} = $reservable_info;
                   10469:     }
                   10470:     return $reservable_info;
                   10471: }
                   10472: 
                   10473: sub get_course_slots {
                   10474:     my ($cnum,$cdom) = @_;
                   10475:     my $hashid=$cnum.':'.$cdom;
                   10476:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   10477:     if (defined($cached)) {
                   10478:         if (ref($result) eq 'HASH') {
                   10479:             return %{$result};
                   10480:         }
                   10481:     } else {
                   10482:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   10483:         my ($tmp) = keys(%slots);
                   10484:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  10485:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  10486:             return %slots;
                   10487:         }
                   10488:     }
                   10489:     return;
                   10490: }
                   10491: 
                   10492: sub devalidate_slots_cache {
                   10493:     my ($cnum,$cdom)=@_;
                   10494:     my $hashid=$cnum.':'.$cdom;
                   10495:     &devalidate_cache_new('allslots',$hashid);
                   10496: }
                   10497: 
1.1172.2.8  raeburn  10498: sub get_coursechange {
                   10499:     my ($cdom,$cnum) = @_;
                   10500:     if ($cdom eq '' || $cnum eq '') {
                   10501:         return unless ($env{'request.course.id'});
                   10502:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10503:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10504:     }
                   10505:     my $hashid=$cdom.'_'.$cnum;
                   10506:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   10507:     if ((defined($cached)) && ($change ne '')) {
                   10508:         return $change;
                   10509:     } else {
                   10510:         my %crshash;
                   10511:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   10512:         if ($crshash{'internal.contentchange'} eq '') {
                   10513:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   10514:             if ($change eq '') {
                   10515:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   10516:                 $change = $crshash{'internal.created'};
                   10517:             }
                   10518:         } else {
                   10519:             $change = $crshash{'internal.contentchange'};
                   10520:         }
                   10521:         my $cachetime = 600;
                   10522:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   10523:     }
                   10524:     return $change;
                   10525: }
                   10526: 
                   10527: sub devalidate_coursechange_cache {
                   10528:     my ($cnum,$cdom)=@_;
                   10529:     my $hashid=$cnum.':'.$cdom;
                   10530:     &devalidate_cache_new('crschange',$hashid);
                   10531: }
                   10532: 
1.31      www      10533: # ------------------------------------------------- Update symbolic store links
                   10534: 
                   10535: sub symblist {
                   10536:     my ($mapname,%newhash)=@_;
1.438     www      10537:     $mapname=&deversion(&declutter($mapname));
1.31      www      10538:     my %hash;
1.620     albertel 10539:     if (($env{'request.course.fn'}) && (%newhash)) {
                   10540:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10541:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  10542: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 10543: 		next if ($url eq 'last_known'
                   10544: 			 && $env{'form.no_update_last_known'});
                   10545: 		$hash{declutter($url)}=&encode_symb($mapname,
                   10546: 						    $newhash{$url}->[1],
                   10547: 						    $newhash{$url}->[0]);
1.191     harris41 10548:             }
1.31      www      10549:             if (untie(%hash)) {
                   10550: 		return 'ok';
                   10551:             }
                   10552:         }
                   10553:     }
                   10554:     return 'error';
1.212     www      10555: }
                   10556: 
                   10557: # --------------------------------------------------------------- Verify a symb
                   10558: 
                   10559: sub symbverify {
1.1172.2.11  raeburn  10560:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      10561:     my $thisfn=$thisurl;
1.439     www      10562:     $thisfn=&declutter($thisfn);
1.215     www      10563: # direct jump to resource in page or to a sequence - will construct own symbs
                   10564:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   10565: # check URL part
1.409     www      10566:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      10567: 
1.431     www      10568:     unless ($url eq $thisfn) { return 0; }
1.213     www      10569: 
1.216     www      10570:     $symb=&symbclean($symb);
1.510     www      10571:     $thisurl=&deversion($thisurl);
1.439     www      10572:     $thisfn=&deversion($thisfn);
1.213     www      10573: 
                   10574:     my %bighash;
                   10575:     my $okay=0;
1.431     www      10576: 
1.620     albertel 10577:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10578:                             &GDBM_READER(),0640)) {
1.1172.2.13  raeburn  10579:         my $noclutter;
1.1032    raeburn  10580:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   10581:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  10582:             if ($map =~ m{^uploaded/.+\.page$}) {
                   10583:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   10584:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   10585:                 $noclutter = 1;
                   10586:             }
                   10587:         }
                   10588:         my $ids;
                   10589:         if ($noclutter) {
                   10590:             $ids=$bighash{'ids_'.$thisurl};
                   10591:         } else {
                   10592:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  10593:         }
1.1102    raeburn  10594:         unless ($ids) {
1.1172.2.13  raeburn  10595:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  10596:             $ids=$bighash{$idkey};
1.216     www      10597:         }
                   10598:         if ($ids) {
                   10599: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  10600:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   10601:                 $symb =~ s/\?.+$//;
                   10602:             }
1.800     albertel 10603: 	    foreach my $id (split(/\,/,$ids)) {
                   10604: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      10605:                if (
                   10606:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  10607:    eq $symb) {
1.1172.2.11  raeburn  10608:                    if (ref($encstate)) {
                   10609:                        $$encstate = $bighash{'encrypted_'.$id};
                   10610:                    }
1.1172.2.13  raeburn  10611:                    if (($env{'request.role.adv'}) ||
                   10612:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  10613:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  10614:                        $okay=1;
                   10615:                        last;
                   10616:                    }
                   10617:                }
                   10618:            }
1.216     www      10619:         }
1.213     www      10620: 	untie(%bighash);
                   10621:     }
                   10622:     return $okay;
1.31      www      10623: }
                   10624: 
1.210     www      10625: # --------------------------------------------------------------- Clean-up symb
                   10626: 
                   10627: sub symbclean {
                   10628:     my $symb=shift;
1.568     albertel 10629:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      10630: # remove version from map
                   10631:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      10632: 
1.210     www      10633: # remove version from URL
                   10634:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      10635: 
1.507     www      10636: # remove wrapper
                   10637: 
1.510     www      10638:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 10639:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      10640:     return $symb;
1.409     www      10641: }
                   10642: 
                   10643: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 10644: 
                   10645: sub encode_symb {
                   10646:     my ($map,$resid,$url)=@_;
                   10647:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   10648: }
1.409     www      10649: 
                   10650: sub decode_symb {
1.568     albertel 10651:     my $symb=shift;
                   10652:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   10653:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      10654:     return (&fixversion($map),$resid,&fixversion($url));
                   10655: }
                   10656: 
                   10657: sub fixversion {
                   10658:     my $fn=shift;
1.609     banghart 10659:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      10660:     my %bighash;
                   10661:     my $uri=&clutter($fn);
1.620     albertel 10662:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      10663: # is this cached?
1.599     albertel 10664:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      10665:     if (defined($cached)) { return $result; }
                   10666: # unfortunately not cached, or expired
1.620     albertel 10667:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      10668: 	    &GDBM_READER(),0640)) {
                   10669:  	if ($bighash{'version_'.$uri}) {
                   10670:  	    my $version=$bighash{'version_'.$uri};
1.444     www      10671:  	    unless (($version eq 'mostrecent') || 
                   10672: 		    ($version==&getversion($uri))) {
1.440     www      10673:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   10674:  	    }
                   10675:  	}
                   10676:  	untie %bighash;
1.413     www      10677:     }
1.599     albertel 10678:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      10679: }
                   10680: 
                   10681: sub deversion {
                   10682:     my $url=shift;
                   10683:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   10684:     return $url;
1.210     www      10685: }
                   10686: 
1.31      www      10687: # ------------------------------------------------------ Return symb list entry
                   10688: 
                   10689: sub symbread {
1.249     www      10690:     my ($thisfn,$donotrecurse)=@_;
1.1172.2.13  raeburn  10691:     my $cache_str;
                   10692:     if ($thisfn ne '') {
                   10693:         $cache_str='request.symbread.cached.'.$thisfn;
                   10694:         if ($env{$cache_str} ne '') {
1.1172.2.8  raeburn  10695:             return $env{$cache_str};
                   10696:         }
1.1172.2.13  raeburn  10697:    } else {
1.242     www      10698: # no filename provided? try from environment
1.620     albertel 10699:         if ($env{'request.symb'}) {
1.1172.2.13  raeburn  10700:             return $env{$cache_str}=&symbclean($env{'request.symb'});
                   10701:         }
                   10702:         $thisfn=$env{'request.filename'};
1.44      www      10703:     }
1.569     albertel 10704:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      10705: # is that filename actually a symb? Verify, clean, and return
                   10706:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 10707: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 10708: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 10709: 	}
1.242     www      10710:     }
1.44      www      10711:     $thisfn=declutter($thisfn);
1.31      www      10712:     my %hash;
1.37      www      10713:     my %bighash;
                   10714:     my $syval='';
1.620     albertel 10715:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  10716:         my $targetfn = $thisfn;
1.609     banghart 10717:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  10718:             $targetfn = 'adm/wrapper/'.$thisfn;
                   10719:         }
1.687     albertel 10720: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   10721: 	    $targetfn=$1;
                   10722: 	}
1.620     albertel 10723:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10724:                       &GDBM_READER(),0640)) {
1.481     raeburn  10725: 	    $syval=$hash{$targetfn};
1.37      www      10726:             untie(%hash);
                   10727:         }
                   10728: # ---------------------------------------------------------- There was an entry
                   10729:         if ($syval) {
1.601     albertel 10730: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 10731: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  10732: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10733: 		    #return $env{$cache_str}='';
1.601     albertel 10734: 		#}    
                   10735: 		#$syval.=$1;
                   10736: 	    #}
1.37      www      10737:         } else {
                   10738: # ------------------------------------------------------- Was not in symb table
1.620     albertel 10739:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10740:                             &GDBM_READER(),0640)) {
1.37      www      10741: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      10742:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      10743:               unless ($ids) { 
                   10744:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      10745:               }
                   10746:               unless ($ids) {
                   10747: # alias?
                   10748: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      10749:               }
1.37      www      10750:               if ($ids) {
                   10751: # ------------------------------------------------------------------- Has ID(s)
                   10752:                  my @possibilities=split(/\,/,$ids);
1.39      www      10753:                  if ($#possibilities==0) {
                   10754: # ----------------------------------------------- There is only one possibility
1.37      www      10755: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 10756: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10757: 						    $resid,$thisfn);
1.249     www      10758:                  } elsif (!$donotrecurse) {
1.39      www      10759: # ------------------------------------------ There is more than one possibility
                   10760:                      my $realpossible=0;
1.800     albertel 10761:                      foreach my $id (@possibilities) {
                   10762: 			 my $file=$bighash{'src_'.$id};
1.39      www      10763:                          if (&allowed('bre',$file)) {
1.800     albertel 10764:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      10765:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   10766: 				$realpossible++;
1.626     albertel 10767:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10768: 						    $resid,$thisfn);
1.39      www      10769:                             }
                   10770: 			 }
1.191     harris41 10771:                      }
1.39      www      10772: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      10773:                  } else {
                   10774:                      $syval='';
1.37      www      10775:                  }
                   10776: 	      }
                   10777:               untie(%bighash)
1.481     raeburn  10778:            }
1.31      www      10779:         }
1.62      www      10780:         if ($syval) {
1.620     albertel 10781: 	    return $env{$cache_str}=$syval;
1.62      www      10782:         }
1.31      www      10783:     }
1.949     raeburn  10784:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10785:     return $env{$cache_str}='';
1.31      www      10786: }
                   10787: 
                   10788: # ---------------------------------------------------------- Return random seed
                   10789: 
1.32      www      10790: sub numval {
                   10791:     my $txt=shift;
                   10792:     $txt=~tr/A-J/0-9/;
                   10793:     $txt=~tr/a-j/0-9/;
                   10794:     $txt=~tr/K-T/0-9/;
                   10795:     $txt=~tr/k-t/0-9/;
                   10796:     $txt=~tr/U-Z/0-5/;
                   10797:     $txt=~tr/u-z/0-5/;
                   10798:     $txt=~s/\D//g;
1.564     albertel 10799:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      10800:     return int($txt);
1.368     albertel 10801: }
                   10802: 
1.484     albertel 10803: sub numval2 {
                   10804:     my $txt=shift;
                   10805:     $txt=~tr/A-J/0-9/;
                   10806:     $txt=~tr/a-j/0-9/;
                   10807:     $txt=~tr/K-T/0-9/;
                   10808:     $txt=~tr/k-t/0-9/;
                   10809:     $txt=~tr/U-Z/0-5/;
                   10810:     $txt=~tr/u-z/0-5/;
                   10811:     $txt=~s/\D//g;
                   10812:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10813:     my $total;
                   10814:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 10815:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 10816:     return int($total);
                   10817: }
                   10818: 
1.575     albertel 10819: sub numval3 {
                   10820:     use integer;
                   10821:     my $txt=shift;
                   10822:     $txt=~tr/A-J/0-9/;
                   10823:     $txt=~tr/a-j/0-9/;
                   10824:     $txt=~tr/K-T/0-9/;
                   10825:     $txt=~tr/k-t/0-9/;
                   10826:     $txt=~tr/U-Z/0-5/;
                   10827:     $txt=~tr/u-z/0-5/;
                   10828:     $txt=~s/\D//g;
                   10829:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10830:     my $total;
                   10831:     foreach my $val (@txts) { $total+=$val; }
                   10832:     if ($_64bit) { $total=(($total<<32)>>32); }
                   10833:     return $total;
                   10834: }
                   10835: 
1.675     albertel 10836: sub digest {
                   10837:     my ($data)=@_;
                   10838:     my $digest=&Digest::MD5::md5($data);
                   10839:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   10840:     my ($e,$f);
                   10841:     {
                   10842:         use integer;
                   10843:         $e=($a+$b);
                   10844:         $f=($c+$d);
                   10845:         if ($_64bit) {
                   10846:             $e=(($e<<32)>>32);
                   10847:             $f=(($f<<32)>>32);
                   10848:         }
                   10849:     }
                   10850:     if (wantarray) {
                   10851: 	return ($e,$f);
                   10852:     } else {
                   10853: 	my $g;
                   10854: 	{
                   10855: 	    use integer;
                   10856: 	    $g=($e+$f);
                   10857: 	    if ($_64bit) {
                   10858: 		$g=(($g<<32)>>32);
                   10859: 	    }
                   10860: 	}
                   10861: 	return $g;
                   10862:     }
                   10863: }
                   10864: 
1.368     albertel 10865: sub latest_rnd_algorithm_id {
1.675     albertel 10866:     return '64bit5';
1.366     albertel 10867: }
1.32      www      10868: 
1.503     albertel 10869: sub get_rand_alg {
                   10870:     my ($courseid)=@_;
1.790     albertel 10871:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 10872:     if ($courseid) {
1.620     albertel 10873: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 10874:     }
                   10875:     return &latest_rnd_algorithm_id();
                   10876: }
                   10877: 
1.562     albertel 10878: sub validCODE {
                   10879:     my ($CODE)=@_;
                   10880:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   10881:     return 0;
                   10882: }
                   10883: 
1.491     albertel 10884: sub getCODE {
1.620     albertel 10885:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 10886:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   10887: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   10888: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 10889: 	return $Apache::lonhomework::history{'resource.CODE'};
                   10890:     }
                   10891:     return undef;
                   10892: }
1.1133    foxr     10893: #
                   10894: #  Determines the random seed for a specific context:
                   10895: #
                   10896: # parameters:
                   10897: #   symb      - in course context the symb for the seed.
                   10898: #   course_id - The course id of the form domain_coursenum.
                   10899: #   domain    - Domain for the user.
                   10900: #   course    - Course for the user.
                   10901: #   cenv      - environment of the course.
                   10902: #
                   10903: # NOTE:
                   10904: #   All parameters are picked out of the environment if missing
                   10905: #   or not defined.
                   10906: #   If a symb cannot be determined the current time is used instead.
                   10907: #
                   10908: #  For a given well defined symb, courside, domain, username,
                   10909: #  and course environment, the seed is reproducible.
                   10910: #
1.31      www      10911: sub rndseed {
1.1133    foxr     10912:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 10913:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 10914:     if (!defined($symb)) {
1.366     albertel 10915: 	unless ($symb=$wsymb) { return time; }
                   10916:     }
1.1146    foxr     10917:     if (!defined $courseid) { 
                   10918: 	$courseid=$wcourseid; 
                   10919:     }
                   10920:     if (!defined $domain) { $domain=$wdomain; }
                   10921:     if (!defined $username) { $username=$wusername }
1.1133    foxr     10922: 
                   10923:     my $which;
                   10924:     if (defined($cenv->{'rndseed'})) {
                   10925: 	$which = $cenv->{'rndseed'};
                   10926:     } else {
                   10927: 	$which =&get_rand_alg($courseid);
                   10928:     }
1.491     albertel 10929:     if (defined(&getCODE())) {
1.675     albertel 10930: 	if ($which eq '64bit5') {
                   10931: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   10932: 	} elsif ($which eq '64bit4') {
1.575     albertel 10933: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   10934: 	} else {
                   10935: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   10936: 	}
1.675     albertel 10937:     } elsif ($which eq '64bit5') {
                   10938: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 10939:     } elsif ($which eq '64bit4') {
                   10940: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 10941:     } elsif ($which eq '64bit3') {
                   10942: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 10943:     } elsif ($which eq '64bit2') {
                   10944: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 10945:     } elsif ($which eq '64bit') {
                   10946: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   10947:     }
                   10948:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   10949: }
                   10950: 
                   10951: sub rndseed_32bit {
                   10952:     my ($symb,$courseid,$domain,$username)=@_;
                   10953:     {
                   10954: 	use integer;
                   10955: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   10956: 	my $symbseed=numval($symb) << 22;
                   10957: 	my $namechck=unpack("%32C*",$username) << 17;
                   10958: 	my $nameseed=numval($username) << 12;
                   10959: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   10960: 	my $courseseed=unpack("%32C*",$courseid);
                   10961: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 10962: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10963: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 10964: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 10965: 	return $num;
                   10966:     }
                   10967: }
                   10968: 
                   10969: sub rndseed_64bit {
                   10970:     my ($symb,$courseid,$domain,$username)=@_;
                   10971:     {
                   10972: 	use integer;
                   10973: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   10974: 	my $symbseed=numval($symb) << 10;
                   10975: 	my $namechck=unpack("%32S*",$username);
                   10976: 	
                   10977: 	my $nameseed=numval($username) << 21;
                   10978: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   10979: 	my $courseseed=unpack("%32S*",$courseid);
                   10980: 	
                   10981: 	my $num1=$symbchck+$symbseed+$namechck;
                   10982: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10983: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10984: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 10985: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 10986: 	return "$num1,$num2";
1.155     albertel 10987:     }
1.366     albertel 10988: }
                   10989: 
1.443     albertel 10990: sub rndseed_64bit2 {
                   10991:     my ($symb,$courseid,$domain,$username)=@_;
                   10992:     {
                   10993: 	use integer;
                   10994: 	# strings need to be an even # of cahracters long, it it is odd the
                   10995:         # last characters gets thrown away
                   10996: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10997: 	my $symbseed=numval($symb) << 10;
                   10998: 	my $namechck=unpack("%32S*",$username.' ');
                   10999: 	
                   11000: 	my $nameseed=numval($username) << 21;
1.501     albertel 11001: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11002: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11003: 	
                   11004: 	my $num1=$symbchck+$symbseed+$namechck;
                   11005: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11006: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11007: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 11008: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 11009: 	return "$num1,$num2";
                   11010:     }
                   11011: }
                   11012: 
                   11013: sub rndseed_64bit3 {
                   11014:     my ($symb,$courseid,$domain,$username)=@_;
                   11015:     {
                   11016: 	use integer;
                   11017: 	# strings need to be an even # of cahracters long, it it is odd the
                   11018:         # last characters gets thrown away
                   11019: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11020: 	my $symbseed=numval2($symb) << 10;
                   11021: 	my $namechck=unpack("%32S*",$username.' ');
                   11022: 	
                   11023: 	my $nameseed=numval2($username) << 21;
1.443     albertel 11024: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11025: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11026: 	
                   11027: 	my $num1=$symbchck+$symbseed+$namechck;
                   11028: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11029: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11030: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 11031: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11032: 	
1.503     albertel 11033: 	return "$num1:$num2";
1.443     albertel 11034:     }
                   11035: }
                   11036: 
1.575     albertel 11037: sub rndseed_64bit4 {
                   11038:     my ($symb,$courseid,$domain,$username)=@_;
                   11039:     {
                   11040: 	use integer;
                   11041: 	# strings need to be an even # of cahracters long, it it is odd the
                   11042:         # last characters gets thrown away
                   11043: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11044: 	my $symbseed=numval3($symb) << 10;
                   11045: 	my $namechck=unpack("%32S*",$username.' ');
                   11046: 	
                   11047: 	my $nameseed=numval3($username) << 21;
                   11048: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11049: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11050: 	
                   11051: 	my $num1=$symbchck+$symbseed+$namechck;
                   11052: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11053: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11054: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 11055: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11056: 	
1.575     albertel 11057: 	return "$num1:$num2";
                   11058:     }
                   11059: }
                   11060: 
1.675     albertel 11061: sub rndseed_64bit5 {
                   11062:     my ($symb,$courseid,$domain,$username)=@_;
                   11063:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   11064:     return "$num1:$num2";
                   11065: }
                   11066: 
1.366     albertel 11067: sub rndseed_CODE_64bit {
                   11068:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 11069:     {
1.366     albertel 11070: 	use integer;
1.443     albertel 11071: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 11072: 	my $symbseed=numval2($symb);
1.491     albertel 11073: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11074: 	my $CODEseed=numval(&getCODE());
1.443     albertel 11075: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 11076: 	my $num1=$symbseed+$CODEchck;
                   11077: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11078: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11079: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 11080: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11081: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 11082: 	return "$num1:$num2";
1.366     albertel 11083:     }
                   11084: }
                   11085: 
1.575     albertel 11086: sub rndseed_CODE_64bit4 {
                   11087:     my ($symb,$courseid,$domain,$username)=@_;
                   11088:     {
                   11089: 	use integer;
                   11090: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   11091: 	my $symbseed=numval3($symb);
                   11092: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11093: 	my $CODEseed=numval3(&getCODE());
                   11094: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11095: 	my $num1=$symbseed+$CODEchck;
                   11096: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11097: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11098: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 11099: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11100: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   11101: 	return "$num1:$num2";
                   11102:     }
                   11103: }
                   11104: 
1.675     albertel 11105: sub rndseed_CODE_64bit5 {
                   11106:     my ($symb,$courseid,$domain,$username)=@_;
                   11107:     my $code = &getCODE();
                   11108:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   11109:     return "$num1:$num2";
                   11110: }
                   11111: 
1.366     albertel 11112: sub setup_random_from_rndseed {
                   11113:     my ($rndseed)=@_;
1.503     albertel 11114:     if ($rndseed =~/([,:])/) {
                   11115: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 11116: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   11117:     } else {
                   11118: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 11119:     }
1.36      albertel 11120: }
                   11121: 
1.474     albertel 11122: sub latest_receipt_algorithm_id {
1.835     albertel 11123:     return 'receipt3';
1.474     albertel 11124: }
                   11125: 
1.480     www      11126: sub recunique {
                   11127:     my $fucourseid=shift;
                   11128:     my $unique;
1.835     albertel 11129:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   11130: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11131: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      11132:     } else {
                   11133: 	$unique=$perlvar{'lonReceipt'};
                   11134:     }
                   11135:     return unpack("%32C*",$unique);
                   11136: }
                   11137: 
                   11138: sub recprefix {
                   11139:     my $fucourseid=shift;
                   11140:     my $prefix;
1.835     albertel 11141:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   11142: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11143: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      11144:     } else {
                   11145: 	$prefix=$perlvar{'lonHostID'};
                   11146:     }
                   11147:     return unpack("%32C*",$prefix);
                   11148: }
                   11149: 
1.76      www      11150: sub ireceipt {
1.474     albertel 11151:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 11152: 
                   11153:     my $return =&recprefix($fucourseid).'-';
                   11154: 
                   11155:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   11156: 	$env{'request.state'} eq 'construct') {
                   11157: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   11158: 	return $return;
                   11159:     }
                   11160: 
1.76      www      11161:     my $cuname=unpack("%32C*",$funame);
                   11162:     my $cudom=unpack("%32C*",$fudom);
                   11163:     my $cucourseid=unpack("%32C*",$fucourseid);
                   11164:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      11165:     my $cunique=&recunique($fucourseid);
1.474     albertel 11166:     my $cpart=unpack("%32S*",$part);
1.835     albertel 11167:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   11168: 
1.790     albertel 11169: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 11170: 			       
                   11171: 	$return.= ($cunique%$cuname+
                   11172: 		   $cunique%$cudom+
                   11173: 		   $cusymb%$cuname+
                   11174: 		   $cusymb%$cudom+
                   11175: 		   $cucourseid%$cuname+
                   11176: 		   $cucourseid%$cudom+
                   11177: 		   $cpart%$cuname+
                   11178: 		   $cpart%$cudom);
                   11179:     } else {
                   11180: 	$return.= ($cunique%$cuname+
                   11181: 		   $cunique%$cudom+
                   11182: 		   $cusymb%$cuname+
                   11183: 		   $cusymb%$cudom+
                   11184: 		   $cucourseid%$cuname+
                   11185: 		   $cucourseid%$cudom);
                   11186:     }
                   11187:     return $return;
1.76      www      11188: }
                   11189: 
                   11190: sub receipt {
1.474     albertel 11191:     my ($part)=@_;
1.790     albertel 11192:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 11193:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      11194: }
1.260     ng       11195: 
1.790     albertel 11196: sub whichuser {
                   11197:     my ($passedsymb)=@_;
                   11198:     my ($symb,$courseid,$domain,$name,$publicuser);
                   11199:     if (defined($env{'form.grade_symb'})) {
                   11200: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   11201: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   11202: 	if (!$allowed &&
                   11203: 	    exists($env{'request.course.sec'}) &&
                   11204: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   11205: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   11206: 			      '/'.$env{'request.course.sec'});
                   11207: 	}
                   11208: 	if ($allowed) {
                   11209: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   11210: 	    $courseid=$tmp_courseid;
                   11211: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   11212: 	    ($name)=&get_env_multiple('form.grade_username');
                   11213: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   11214: 	}
                   11215:     }
                   11216:     if (!$passedsymb) {
                   11217: 	$symb=&symbread();
                   11218:     } else {
                   11219: 	$symb=$passedsymb;
                   11220:     }
                   11221:     $courseid=$env{'request.course.id'};
                   11222:     $domain=$env{'user.domain'};
                   11223:     $name=$env{'user.name'};
                   11224:     if ($name eq 'public' && $domain eq 'public') {
                   11225: 	if (!defined($env{'form.username'})) {
                   11226: 	    $env{'form.username'}.=time.rand(10000000);
                   11227: 	}
                   11228: 	$name.=$env{'form.username'};
                   11229:     }
                   11230:     return ($symb,$courseid,$domain,$name,$publicuser);
                   11231: 
                   11232: }
                   11233: 
1.36      albertel 11234: # ------------------------------------------------------------ Serves up a file
1.472     albertel 11235: # returns either the contents of the file or 
                   11236: # -1 if the file doesn't exist
1.481     raeburn  11237: #
                   11238: # if the target is a file that was uploaded via DOCS, 
                   11239: # a check will be made to see if a current copy exists on the local server,
                   11240: # if it does this will be served, otherwise a copy will be retrieved from
                   11241: # the home server for the course and stored in /home/httpd/html/userfiles on
                   11242: # the local server.   
1.472     albertel 11243: 
1.36      albertel 11244: sub getfile {
1.538     albertel 11245:     my ($file) = @_;
1.609     banghart 11246:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 11247:     &repcopy($file);
                   11248:     return &readfile($file);
                   11249: }
                   11250: 
                   11251: sub repcopy_userfile {
                   11252:     my ($file)=@_;
1.1142    raeburn  11253:     my $londocroot = $perlvar{'lonDocRoot'};
                   11254:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  11255:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 11256:     my ($cdom,$cnum,$filename) = 
1.811     albertel 11257: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 11258:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   11259:     if (-e "$file") {
1.828     www      11260: # we already have a local copy, check it out
1.538     albertel 11261: 	my @fileinfo = stat($file);
1.828     www      11262: 	my $rtncode;
                   11263: 	my $info;
1.538     albertel 11264: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 11265: 	if ($lwpresp ne 'ok') {
1.828     www      11266: # there is no such file anymore, even though we had a local copy
1.482     albertel 11267: 	    if ($rtncode eq '404') {
1.538     albertel 11268: 		unlink($file);
1.482     albertel 11269: 	    }
                   11270: 	    return -1;
                   11271: 	}
                   11272: 	if ($info < $fileinfo[9]) {
1.828     www      11273: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  11274: 	    return 'ok';
1.828     www      11275: 	} else {
                   11276: # the file is outdated, get rid of it
                   11277: 	    unlink($file);
1.482     albertel 11278: 	}
1.828     www      11279:     }
                   11280: # one way or the other, at this point, we don't have the file
                   11281: # construct the correct path for the file
                   11282:     my @parts = ($cdom,$cnum); 
                   11283:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   11284: 	push @parts, split(/\//,$1);
                   11285:     }
                   11286:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   11287:     foreach my $part (@parts) {
                   11288: 	$path .= '/'.$part;
                   11289: 	if (!-e $path) {
                   11290: 	    mkdir($path,0770);
1.482     albertel 11291: 	}
                   11292:     }
1.828     www      11293: # now the path exists for sure
                   11294: # get a user agent
                   11295:     my $ua=new LWP::UserAgent;
                   11296:     my $transferfile=$file.'.in.transfer';
                   11297: # FIXME: this should flock
                   11298:     if (-e $transferfile) { return 'ok'; }
                   11299:     my $request;
                   11300:     $uri=~s/^\///;
1.980     raeburn  11301:     my $homeserver = &homeserver($cnum,$cdom);
                   11302:     my $protocol = $protocol{$homeserver};
                   11303:     $protocol = 'http' if ($protocol ne 'https');
                   11304:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      11305:     my $response=$ua->request($request,$transferfile);
                   11306: # did it work?
                   11307:     if ($response->is_error()) {
                   11308: 	unlink($transferfile);
                   11309: 	&logthis("Userfile repcopy failed for $uri");
                   11310: 	return -1;
                   11311:     }
                   11312: # worked, rename the transfer file
                   11313:     rename($transferfile,$file);
1.607     raeburn  11314:     return 'ok';
1.481     raeburn  11315: }
                   11316: 
1.517     albertel 11317: sub tokenwrapper {
                   11318:     my $uri=shift;
1.980     raeburn  11319:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 11320:     $uri=~s|^/||;
1.620     albertel 11321:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 11322:     my $token=$1;
1.552     albertel 11323:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   11324:     if ($udom && $uname && $file) {
                   11325: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  11326:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  11327:         my $homeserver = &homeserver($uname,$udom);
                   11328:         my $protocol = $protocol{$homeserver};
                   11329:         $protocol = 'http' if ($protocol ne 'https');
                   11330:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 11331:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   11332:                                '&tokenissued='.$perlvar{'lonHostID'};
                   11333:     } else {
                   11334:         return '/adm/notfound.html';
                   11335:     }
                   11336: }
                   11337: 
1.828     www      11338: # call with reqtype HEAD: get last modification time
                   11339: # call with reqtype GET: get the file contents
                   11340: # Do not call this with reqtype GET for large files! It loads everything into memory
                   11341: #
1.481     raeburn  11342: sub getuploaded {
                   11343:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   11344:     $uri=~s/^\///;
1.980     raeburn  11345:     my $homeserver = &homeserver($cnum,$cdom);
                   11346:     my $protocol = $protocol{$homeserver};
                   11347:     $protocol = 'http' if ($protocol ne 'https');
                   11348:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  11349:     my $ua=new LWP::UserAgent;
                   11350:     my $request=new HTTP::Request($reqtype,$uri);
                   11351:     my $response=$ua->request($request);
                   11352:     $$rtncode = $response->code;
1.482     albertel 11353:     if (! $response->is_success()) {
                   11354: 	return 'failed';
                   11355:     }      
                   11356:     if ($reqtype eq 'HEAD') {
1.486     www      11357: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 11358:     } elsif ($reqtype eq 'GET') {
                   11359: 	$$info = $response->content;
1.472     albertel 11360:     }
1.482     albertel 11361:     return 'ok';
1.36      albertel 11362: }
                   11363: 
1.481     raeburn  11364: sub readfile {
                   11365:     my $file = shift;
                   11366:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   11367:     my $fh;
                   11368:     open($fh,"<$file");
                   11369:     my $a='';
1.800     albertel 11370:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  11371:     return $a;
                   11372: }
                   11373: 
1.36      albertel 11374: sub filelocation {
1.590     banghart 11375:     my ($dir,$file) = @_;
                   11376:     my $location;
                   11377:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 11378: 
                   11379:     if ($file =~ m-^/adm/-) {
                   11380: 	$file=~s-^/adm/wrapper/-/-;
                   11381: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   11382:     }
1.882     albertel 11383: 
1.1139    www      11384:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  11385:         $location = $file;
1.609     banghart 11386:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 11387:         my ($udom,$uname,$filename)=
1.811     albertel 11388:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 11389:         my $home=&homeserver($uname,$udom);
                   11390:         my $is_me=0;
                   11391:         my @ids=&current_machine_ids();
                   11392:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   11393:         if ($is_me) {
1.1117    foxr     11394:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 11395:         } else {
                   11396:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   11397:   	      $udom.'/'.$uname.'/'.$filename;
                   11398:         }
1.882     albertel 11399:     } elsif ($file =~ m-^/adm/-) {
                   11400: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 11401:     } else {
                   11402:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      11403:         $file=~s:^/(res|priv)/:/:;
                   11404:         my $space=$1;
1.590     banghart 11405:         if ( !( $file =~ m:^/:) ) {
                   11406:             $location = $dir. '/'.$file;
                   11407:         } else {
1.1142    raeburn  11408:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 11409:         }
1.59      albertel 11410:     }
1.590     banghart 11411:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 11412:     while ($location=~m{/\.\./}) {
                   11413: 	if ($location =~ m{/[^/]+/\.\./}) {
                   11414: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   11415: 	} else {
                   11416: 	    $location=~ s{/\.\./}{/}g;
                   11417: 	}
                   11418:     } #remove dir/..
1.590     banghart 11419:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   11420:     return $location;
1.46      www      11421: }
1.36      albertel 11422: 
1.46      www      11423: sub hreflocation {
                   11424:     my ($dir,$file)=@_;
1.980     raeburn  11425:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 11426: 	$file=filelocation($dir,$file);
1.700     albertel 11427:     } elsif ($file=~m-^/adm/-) {
                   11428: 	$file=~s-^/adm/wrapper/-/-;
                   11429: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 11430:     }
                   11431:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   11432: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   11433:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  11434: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   11435: 	        {/uploaded/$1/$2/}x;
1.46      www      11436:     }
1.913     albertel 11437:     if ($file=~ m{^/userfiles/}) {
                   11438: 	$file =~ s{^/userfiles/}{/uploaded/};
                   11439:     }
1.462     albertel 11440:     return $file;
1.465     albertel 11441: }
                   11442: 
1.1139    www      11443: 
                   11444: 
                   11445: 
                   11446: 
1.465     albertel 11447: sub current_machine_domains {
1.853     albertel 11448:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   11449: }
                   11450: 
                   11451: sub machine_domains {
                   11452:     my ($hostname) = @_;
1.465     albertel 11453:     my @domains;
1.838     albertel 11454:     my %hostname = &all_hostnames();
1.465     albertel 11455:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  11456: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 11457: 	if ($hostname eq $name) {
1.844     albertel 11458: 	    push(@domains,&host_domain($id));
1.465     albertel 11459: 	}
                   11460:     }
                   11461:     return @domains;
                   11462: }
                   11463: 
                   11464: sub current_machine_ids {
1.853     albertel 11465:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   11466: }
                   11467: 
                   11468: sub machine_ids {
                   11469:     my ($hostname) = @_;
                   11470:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 11471:     my @ids;
1.888     albertel 11472:     my %name_to_host = &all_names();
1.889     albertel 11473:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   11474: 	return @{ $name_to_host{$hostname} };
                   11475:     }
                   11476:     return;
1.31      www      11477: }
                   11478: 
1.824     raeburn  11479: sub additional_machine_domains {
                   11480:     my @domains;
                   11481:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   11482:     while( my $line = <$fh>) {
                   11483:         $line =~ s/\s//g;
                   11484:         push(@domains,$line);
                   11485:     }
                   11486:     return @domains;
                   11487: }
                   11488: 
                   11489: sub default_login_domain {
                   11490:     my $domain = $perlvar{'lonDefDomain'};
                   11491:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   11492:     foreach my $posdom (&current_machine_domains(),
                   11493:                         &additional_machine_domains()) {
                   11494:         if (lc($posdom) eq lc($testdomain)) {
                   11495:             $domain=$posdom;
                   11496:             last;
                   11497:         }
                   11498:     }
                   11499:     return $domain;
                   11500: }
                   11501: 
1.31      www      11502: # ------------------------------------------------------------- Declutters URLs
                   11503: 
                   11504: sub declutter {
                   11505:     my $thisfn=shift;
1.569     albertel 11506:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 11507:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      11508:     $thisfn=~s/^\///;
1.697     albertel 11509:     $thisfn=~s|^adm/wrapper/||;
                   11510:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      11511:     $thisfn=~s/^res\///;
1.1172    bisitz   11512:     $thisfn=~s/^priv\///;
1.1032    raeburn  11513:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   11514:         $thisfn=~s/\?.+$//;
                   11515:     }
1.268     www      11516:     return $thisfn;
                   11517: }
                   11518: 
                   11519: # ------------------------------------------------------------- Clutter up URLs
                   11520: 
                   11521: sub clutter {
                   11522:     my $thisfn='/'.&declutter(shift);
1.887     albertel 11523:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 11524: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      11525:        $thisfn='/res'.$thisfn; 
                   11526:     }
1.1031    raeburn  11527:     if ($thisfn !~m|^/adm|) {
                   11528: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 11529: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 11530: 	} else {
                   11531: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   11532: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 11533: 	    if ($embstyle eq 'ssi'
                   11534: 		|| ($embstyle eq 'hdn')
                   11535: 		|| ($embstyle eq 'rat')
                   11536: 		|| ($embstyle eq 'prv')
                   11537: 		|| ($embstyle eq 'ign')) {
                   11538: 		#do nothing with these
                   11539: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 11540: 		|| ($embstyle eq 'emb')
                   11541: 		|| ($embstyle eq 'wrp')) {
                   11542: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 11543: 	    } elsif ($embstyle eq 'unk'
                   11544: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 11545: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 11546: 	    } else {
1.718     www      11547: #		&logthis("Got a blank emb style");
1.695     albertel 11548: 	    }
1.694     albertel 11549: 	}
                   11550:     }
1.31      www      11551:     return $thisfn;
1.12      www      11552: }
                   11553: 
1.787     albertel 11554: sub clutter_with_no_wrapper {
                   11555:     my $uri = &clutter(shift);
                   11556:     if ($uri =~ m-^/adm/-) {
                   11557: 	$uri =~ s-^/adm/wrapper/-/-;
                   11558: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   11559:     }
                   11560:     return $uri;
                   11561: }
                   11562: 
1.557     albertel 11563: sub freeze_escape {
                   11564:     my ($value)=@_;
                   11565:     if (ref($value)) {
                   11566: 	$value=&nfreeze($value);
                   11567: 	return '__FROZEN__'.&escape($value);
                   11568:     }
                   11569:     return &escape($value);
                   11570: }
                   11571: 
1.11      www      11572: 
1.557     albertel 11573: sub thaw_unescape {
                   11574:     my ($value)=@_;
                   11575:     if ($value =~ /^__FROZEN__/) {
                   11576: 	substr($value,0,10,undef);
                   11577: 	$value=&unescape($value);
                   11578: 	return &thaw($value);
                   11579:     }
                   11580:     return &unescape($value);
                   11581: }
                   11582: 
1.436     albertel 11583: sub correct_line_ends {
                   11584:     my ($result)=@_;
                   11585:     $$result =~s/\r\n/\n/mg;
                   11586:     $$result =~s/\r/\n/mg;
1.415     albertel 11587: }
1.1       albertel 11588: # ================================================================ Main Program
                   11589: 
1.184     www      11590: sub goodbye {
1.204     albertel 11591:    &logthis("Starting Shut down");
1.443     albertel 11592: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 11593:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 11594: #converted
1.599     albertel 11595: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 11596:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   11597: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   11598: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 11599: #1.1 only
1.870     albertel 11600: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   11601: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   11602: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   11603: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   11604:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 11605:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   11606:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      11607:    &flushcourselogs();
                   11608:    &logthis("Shutting down");
                   11609: }
                   11610: 
1.852     albertel 11611: sub get_dns {
1.1172.2.17  raeburn  11612:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 11613:     if (!$ignore_cache) {
                   11614: 	my ($content,$cached)=
                   11615: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   11616: 	if ($cached) {
1.1172.2.17  raeburn  11617: 	    &$func($content,$hashref);
1.869     albertel 11618: 	    return;
                   11619: 	}
                   11620:     }
                   11621: 
                   11622:     my %alldns;
1.852     albertel 11623:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11624:     foreach my $dns (<$config>) {
                   11625: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  11626:         my $line = $1;
                   11627:         my ($host,$protocol) = split(/:/,$line);
                   11628:         if ($protocol ne 'https') {
                   11629:             $protocol = 'http';
                   11630:         }
                   11631: 	$alldns{$host} = $protocol;
1.869     albertel 11632:     }
                   11633:     while (%alldns) {
                   11634: 	my ($dns) = keys(%alldns);
1.852     albertel 11635: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  11636:         $ua->timeout(30);
1.979     raeburn  11637: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 11638: 	my $response=$ua->request($request);
1.979     raeburn  11639:         delete($alldns{$dns});
1.852     albertel 11640: 	next if ($response->is_error());
                   11641: 	my @content = split("\n",$response->content);
1.1172.2.17  raeburn  11642:         unless ($nocache) {
1.1172.2.23  raeburn  11643: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  11644:         }
                   11645: 	&$func(\@content,$hashref);
1.869     albertel 11646: 	return;
1.852     albertel 11647:     }
                   11648:     close($config);
1.871     albertel 11649:     my $which = (split('/',$url))[3];
                   11650:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   11651:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 11652:     my @content = <$config>;
1.1172.2.17  raeburn  11653:     &$func(\@content,$hashref);
                   11654:     return;
                   11655: }
                   11656: 
                   11657: # ------------------------------------------------------Get DNS checksums file
                   11658: sub parse_dns_checksums_tab {
                   11659:     my ($lines,$hashref) = @_;
                   11660:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
                   11661:     my $loncaparev = &get_server_loncaparev($machine_dom);
                   11662:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   11663:     my (%chksum,%revnum);
                   11664:     if (ref($lines) eq 'ARRAY') {
                   11665:         chomp(@{$lines});
                   11666:         my $versions = shift(@{$lines});
                   11667:         my %supported;
                   11668:         if ($versions =~ /^VERSIONS\:([\w\.\,]+)$/) {
                   11669:             my $releaseslist = $1;
                   11670:             if ($releaseslist =~ /,/) {
                   11671:                 map { $supported{$_} = 1; } split(/,/,$releaseslist);
                   11672:             } elsif ($releaseslist) {
                   11673:                 $supported{$releaseslist} = 1;
                   11674:             }
                   11675:         }
                   11676:         if ($supported{$release}) {
                   11677:             my $matchthis = 0;
                   11678:             foreach my $line (@{$lines}) {
                   11679:                 if ($line =~ /^(\d[\w\.]+)$/) {
                   11680:                     if ($matchthis) {
                   11681:                         last;
                   11682:                     } elsif ($1 eq $release) {
                   11683:                         $matchthis = 1;
                   11684:                     }
                   11685:                 } elsif ($matchthis) {
                   11686:                     my ($file,$version,$shasum) = split(/,/,$line);
                   11687:                     $chksum{$file} = $shasum;
                   11688:                     $revnum{$file} = $version;
                   11689:                 }
                   11690:             }
                   11691:             if (ref($hashref) eq 'HASH') {
                   11692:                 %{$hashref} = (
                   11693:                                 sums     => \%chksum,
                   11694:                                 versions => \%revnum,
                   11695:                               );
                   11696:             }
                   11697:         }
                   11698:     }
1.869     albertel 11699:     return;
1.852     albertel 11700: }
1.1172.2.17  raeburn  11701: 
                   11702: sub fetch_dns_checksums {
                   11703:     my %checksums;
                   11704:     &get_dns('/adm/dns/checksums',\&parse_dns_checksums_tab,1,1,
                   11705:              \%checksums);
                   11706:     return \%checksums;
                   11707: }
                   11708: 
1.327     albertel 11709: # ------------------------------------------------------------ Read domain file
                   11710: {
1.852     albertel 11711:     my $loaded;
1.846     albertel 11712:     my %domain;
                   11713: 
1.852     albertel 11714:     sub parse_domain_tab {
                   11715: 	my ($lines) = @_;
                   11716: 	foreach my $line (@$lines) {
                   11717: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      11718: 
1.846     albertel 11719: 	    chomp($line);
1.852     albertel 11720: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 11721: 	    my %this_domain;
                   11722: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   11723: 			       'lang_def', 'city', 'longi', 'lati',
                   11724: 			       'primary') {
                   11725: 		$this_domain{$field} = shift(@elements);
                   11726: 	    }
                   11727: 	    $domain{$name} = \%this_domain;
1.852     albertel 11728: 	}
                   11729:     }
1.864     albertel 11730: 
                   11731:     sub reset_domain_info {
                   11732: 	undef($loaded);
                   11733: 	undef(%domain);
                   11734:     }
                   11735: 
1.852     albertel 11736:     sub load_domain_tab {
1.869     albertel 11737: 	my ($ignore_cache) = @_;
                   11738: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 11739: 	my $fh;
                   11740: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   11741: 	    my @lines = <$fh>;
                   11742: 	    &parse_domain_tab(\@lines);
1.448     albertel 11743: 	}
1.852     albertel 11744: 	close($fh);
                   11745: 	$loaded = 1;
1.327     albertel 11746:     }
1.846     albertel 11747: 
                   11748:     sub domain {
1.852     albertel 11749: 	&load_domain_tab() if (!$loaded);
                   11750: 
1.846     albertel 11751: 	my ($name,$what) = @_;
                   11752: 	return if ( !exists($domain{$name}) );
                   11753: 
                   11754: 	if (!$what) {
                   11755: 	    return $domain{$name}{'description'};
                   11756: 	}
                   11757: 	return $domain{$name}{$what};
                   11758:     }
1.974     raeburn  11759: 
                   11760:     sub domain_info {
                   11761:         &load_domain_tab() if (!$loaded);
                   11762:         return %domain;
                   11763:     }
                   11764: 
1.327     albertel 11765: }
                   11766: 
                   11767: 
1.1       albertel 11768: # ------------------------------------------------------------- Read hosts file
                   11769: {
1.838     albertel 11770:     my %hostname;
1.844     albertel 11771:     my %hostdom;
1.845     albertel 11772:     my %libserv;
1.852     albertel 11773:     my $loaded;
1.888     albertel 11774:     my %name_to_host;
1.1074    raeburn  11775:     my %internetdom;
1.1107    raeburn  11776:     my %LC_dns_serv;
1.852     albertel 11777: 
                   11778:     sub parse_hosts_tab {
                   11779: 	my ($file) = @_;
                   11780: 	foreach my $configline (@$file) {
                   11781: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  11782:             chomp($configline);
                   11783: 	    if ($configline =~ /^\^/) {
                   11784:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   11785:                     $LC_dns_serv{$1} = 1;
                   11786:                 }
                   11787:                 next;
                   11788:             }
1.1074    raeburn  11789: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 11790: 	    $name=~s/\s//g;
                   11791: 	    if ($id && $domain && $role && $name) {
                   11792: 		$hostname{$id}=$name;
1.888     albertel 11793: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 11794: 		$hostdom{$id}=$domain;
                   11795: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  11796:                 if (defined($protocol)) {
                   11797:                     if ($protocol eq 'https') {
                   11798:                         $protocol{$id} = $protocol;
                   11799:                     } else {
                   11800:                         $protocol{$id} = 'http'; 
                   11801:                     }
1.968     raeburn  11802:                 } else {
1.969     raeburn  11803:                     $protocol{$id} = 'http';
1.968     raeburn  11804:                 }
1.1074    raeburn  11805:                 if (defined($intdom)) {
                   11806:                     $internetdom{$id} = $intdom;
                   11807:                 }
1.852     albertel 11808: 	    }
                   11809: 	}
                   11810:     }
1.864     albertel 11811:     
                   11812:     sub reset_hosts_info {
1.897     albertel 11813: 	&purge_remembered();
1.864     albertel 11814: 	&reset_domain_info();
                   11815: 	&reset_hosts_ip_info();
1.892     albertel 11816: 	undef(%name_to_host);
1.864     albertel 11817: 	undef(%hostname);
                   11818: 	undef(%hostdom);
                   11819: 	undef(%libserv);
                   11820: 	undef($loaded);
                   11821:     }
1.1       albertel 11822: 
1.852     albertel 11823:     sub load_hosts_tab {
1.869     albertel 11824: 	my ($ignore_cache) = @_;
                   11825: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 11826: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11827: 	my @config = <$config>;
                   11828: 	&parse_hosts_tab(\@config);
                   11829: 	close($config);
                   11830: 	$loaded=1;
1.1       albertel 11831:     }
1.852     albertel 11832: 
1.838     albertel 11833:     sub hostname {
1.852     albertel 11834: 	&load_hosts_tab() if (!$loaded);
                   11835: 
1.838     albertel 11836: 	my ($lonid) = @_;
                   11837: 	return $hostname{$lonid};
                   11838:     }
1.845     albertel 11839: 
1.838     albertel 11840:     sub all_hostnames {
1.852     albertel 11841: 	&load_hosts_tab() if (!$loaded);
                   11842: 
1.838     albertel 11843: 	return %hostname;
                   11844:     }
1.845     albertel 11845: 
1.888     albertel 11846:     sub all_names {
                   11847: 	&load_hosts_tab() if (!$loaded);
                   11848: 
                   11849: 	return %name_to_host;
                   11850:     }
                   11851: 
1.974     raeburn  11852:     sub all_host_domain {
                   11853:         &load_hosts_tab() if (!$loaded);
                   11854:         return %hostdom;
                   11855:     }
                   11856: 
1.845     albertel 11857:     sub is_library {
1.852     albertel 11858: 	&load_hosts_tab() if (!$loaded);
                   11859: 
1.845     albertel 11860: 	return exists($libserv{$_[0]});
                   11861:     }
                   11862: 
                   11863:     sub all_library {
1.852     albertel 11864: 	&load_hosts_tab() if (!$loaded);
                   11865: 
1.845     albertel 11866: 	return %libserv;
                   11867:     }
                   11868: 
1.1062    droeschl 11869:     sub unique_library {
                   11870: 	#2x reverse removes all hostnames that appear more than once
                   11871:         my %unique = reverse &all_library();
                   11872:         return reverse %unique;
                   11873:     }
                   11874: 
1.841     albertel 11875:     sub get_servers {
1.852     albertel 11876: 	&load_hosts_tab() if (!$loaded);
                   11877: 
1.841     albertel 11878: 	my ($domain,$type) = @_;
                   11879: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   11880: 	                                          : %hostname;
                   11881: 	my %result;
1.842     albertel 11882: 	if (ref($domain) eq 'ARRAY') {
                   11883: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 11884: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 11885: 		    $result{$host} = $hostname;
                   11886: 		}
                   11887: 	    }
                   11888: 	} else {
                   11889: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   11890: 		if ($hostdom{$host} eq $domain) {
                   11891: 		    $result{$host} = $hostname;
                   11892: 		}
1.841     albertel 11893: 	    }
                   11894: 	}
                   11895: 	return %result;
                   11896:     }
1.845     albertel 11897: 
1.1062    droeschl 11898:     sub get_unique_servers {
                   11899:         my %unique = reverse &get_servers(@_);
                   11900: 	return reverse %unique;
                   11901:     }
                   11902: 
1.844     albertel 11903:     sub host_domain {
1.852     albertel 11904: 	&load_hosts_tab() if (!$loaded);
                   11905: 
1.844     albertel 11906: 	my ($lonid) = @_;
                   11907: 	return $hostdom{$lonid};
                   11908:     }
                   11909: 
1.841     albertel 11910:     sub all_domains {
1.852     albertel 11911: 	&load_hosts_tab() if (!$loaded);
                   11912: 
1.841     albertel 11913: 	my %seen;
                   11914: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   11915: 	return @uniq;
                   11916:     }
1.1074    raeburn  11917: 
                   11918:     sub internet_dom {
                   11919:         &load_hosts_tab() if (!$loaded);
                   11920: 
                   11921:         my ($lonid) = @_;
                   11922:         return $internetdom{$lonid};
                   11923:     }
1.1107    raeburn  11924: 
                   11925:     sub is_LC_dns {
                   11926:         &load_hosts_tab() if (!$loaded);
                   11927: 
                   11928:         my ($hostname) = @_;
                   11929:         return exists($LC_dns_serv{$hostname});
                   11930:     }
                   11931: 
1.1       albertel 11932: }
                   11933: 
1.847     albertel 11934: { 
                   11935:     my %iphost;
1.856     albertel 11936:     my %name_to_ip;
                   11937:     my %lonid_to_ip;
1.869     albertel 11938: 
1.847     albertel 11939:     sub get_hosts_from_ip {
                   11940: 	my ($ip) = @_;
                   11941: 	my %iphosts = &get_iphost();
                   11942: 	if (ref($iphosts{$ip})) {
                   11943: 	    return @{$iphosts{$ip}};
                   11944: 	}
                   11945: 	return;
1.839     albertel 11946:     }
1.864     albertel 11947:     
                   11948:     sub reset_hosts_ip_info {
                   11949: 	undef(%iphost);
                   11950: 	undef(%name_to_ip);
                   11951: 	undef(%lonid_to_ip);
                   11952:     }
1.856     albertel 11953: 
                   11954:     sub get_host_ip {
                   11955: 	my ($lonid) = @_;
                   11956: 	if (exists($lonid_to_ip{$lonid})) {
                   11957: 	    return $lonid_to_ip{$lonid};
                   11958: 	}
                   11959: 	my $name=&hostname($lonid);
                   11960:    	my $ip = gethostbyname($name);
                   11961: 	return if (!$ip || length($ip) ne 4);
                   11962: 	$ip=inet_ntoa($ip);
                   11963: 	$name_to_ip{$name}   = $ip;
                   11964: 	$lonid_to_ip{$lonid} = $ip;
                   11965: 	return $ip;
                   11966:     }
1.847     albertel 11967:     
                   11968:     sub get_iphost {
1.869     albertel 11969: 	my ($ignore_cache) = @_;
1.894     albertel 11970: 
1.869     albertel 11971: 	if (!$ignore_cache) {
                   11972: 	    if (%iphost) {
                   11973: 		return %iphost;
                   11974: 	    }
                   11975: 	    my ($ip_info,$cached)=
                   11976: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   11977: 	    if ($cached) {
                   11978: 		%iphost      = %{$ip_info->[0]};
                   11979: 		%name_to_ip  = %{$ip_info->[1]};
                   11980: 		%lonid_to_ip = %{$ip_info->[2]};
                   11981: 		return %iphost;
                   11982: 	    }
                   11983: 	}
1.894     albertel 11984: 
                   11985: 	# get yesterday's info for fallback
                   11986: 	my %old_name_to_ip;
                   11987: 	my ($ip_info,$cached)=
                   11988: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   11989: 	if ($cached) {
                   11990: 	    %old_name_to_ip = %{$ip_info->[1]};
                   11991: 	}
                   11992: 
1.888     albertel 11993: 	my %name_to_host = &all_names();
                   11994: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 11995: 	    my $ip;
                   11996: 	    if (!exists($name_to_ip{$name})) {
                   11997: 		$ip = gethostbyname($name);
                   11998: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 11999: 		    if (defined($old_name_to_ip{$name})) {
                   12000: 			$ip = $old_name_to_ip{$name};
                   12001: 			&logthis("Can't find $name defaulting to old $ip");
                   12002: 		    } else {
                   12003: 			&logthis("Name $name no IP found");
                   12004: 			next;
                   12005: 		    }
                   12006: 		} else {
                   12007: 		    $ip=inet_ntoa($ip);
1.847     albertel 12008: 		}
                   12009: 		$name_to_ip{$name} = $ip;
                   12010: 	    } else {
                   12011: 		$ip = $name_to_ip{$name};
1.653     albertel 12012: 	    }
1.888     albertel 12013: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   12014: 		$lonid_to_ip{$id} = $ip;
                   12015: 	    }
                   12016: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 12017: 	}
1.1172.2.23  raeburn  12018: 	&do_cache_new('iphost','iphost',
                   12019: 		      [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   12020: 		      48*60*60);
1.869     albertel 12021: 
1.847     albertel 12022: 	return %iphost;
1.598     albertel 12023:     }
                   12024: 
1.992     raeburn  12025:     #
                   12026:     #  Given a DNS returns the loncapa host name for that DNS 
                   12027:     # 
                   12028:     sub host_from_dns {
                   12029:         my ($dns) = @_;
                   12030:         my @hosts;
                   12031:         my $ip;
                   12032: 
1.993     raeburn  12033:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  12034:             $ip = $name_to_ip{$dns};
                   12035:         }
                   12036:         if (!$ip) {
                   12037:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   12038:             if (length($ip) == 4) { 
                   12039: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   12040:             }
                   12041:         }
                   12042:         if ($ip) {
                   12043: 	    @hosts = get_hosts_from_ip($ip);
                   12044: 	    return $hosts[0];
                   12045:         }
                   12046:         return undef;
1.986     foxr     12047:     }
1.992     raeburn  12048: 
1.1074    raeburn  12049:     sub get_internet_names {
                   12050:         my ($lonid) = @_;
                   12051:         return if ($lonid eq '');
                   12052:         my ($idnref,$cached)=
                   12053:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   12054:         if ($cached) {
                   12055:             return $idnref;
                   12056:         }
                   12057:         my $ip = &get_host_ip($lonid);
                   12058:         my @hosts = &get_hosts_from_ip($ip);
                   12059:         my %iphost = &get_iphost();
                   12060:         my (@idns,%seen);
                   12061:         foreach my $id (@hosts) {
                   12062:             my $dom = &host_domain($id);
                   12063:             my $prim_id = &domain($dom,'primary');
                   12064:             my $prim_ip = &get_host_ip($prim_id);
                   12065:             next if ($seen{$prim_ip});
                   12066:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   12067:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   12068:                     my $intdom = &internet_dom($id);
                   12069:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   12070:                         push(@idns,$intdom);
                   12071:                     }
                   12072:                 }
                   12073:             }
                   12074:             $seen{$prim_ip} = 1;
                   12075:         }
1.1172.2.23  raeburn  12076:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  12077:     }
                   12078: 
1.986     foxr     12079: }
                   12080: 
1.1079    raeburn  12081: sub all_loncaparevs {
                   12082:     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);
                   12083: }
                   12084: 
1.862     albertel 12085: BEGIN {
                   12086: 
                   12087: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   12088:     unless ($readit) {
                   12089: {
                   12090:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   12091:     %perlvar = (%perlvar,%{$configvars});
                   12092: }
                   12093: 
                   12094: 
1.1       albertel 12095: # ------------------------------------------------------ Read spare server file
                   12096: {
1.448     albertel 12097:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 12098: 
                   12099:     while (my $configline=<$config>) {
                   12100:        chomp($configline);
1.284     matthew  12101:        if ($configline) {
1.784     albertel 12102: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 12103: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 12104: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 12105:        }
                   12106:     }
1.448     albertel 12107:     close($config);
1.1       albertel 12108: }
1.11      www      12109: # ------------------------------------------------------------ Read permissions
                   12110: {
1.448     albertel 12111:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      12112: 
                   12113:     while (my $configline=<$config>) {
1.448     albertel 12114: 	chomp($configline);
                   12115: 	if ($configline) {
                   12116: 	    my ($role,$perm)=split(/ /,$configline);
                   12117: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   12118: 	}
1.11      www      12119:     }
1.448     albertel 12120:     close($config);
1.11      www      12121: }
                   12122: 
                   12123: # -------------------------------------------- Read plain texts for permissions
                   12124: {
1.448     albertel 12125:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      12126: 
                   12127:     while (my $configline=<$config>) {
1.448     albertel 12128: 	chomp($configline);
                   12129: 	if ($configline) {
1.742     raeburn  12130: 	    my ($short,@plain)=split(/:/,$configline);
                   12131:             %{$prp{$short}} = ();
                   12132: 	    if (@plain > 0) {
                   12133:                 $prp{$short}{'std'} = $plain[0];
                   12134:                 for (my $i=1; $i<@plain; $i++) {
                   12135:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   12136:                 }
                   12137:             }
1.448     albertel 12138: 	}
1.135     www      12139:     }
1.448     albertel 12140:     close($config);
1.135     www      12141: }
                   12142: 
                   12143: # ---------------------------------------------------------- Read package table
                   12144: {
1.448     albertel 12145:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      12146: 
                   12147:     while (my $configline=<$config>) {
1.483     albertel 12148: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 12149: 	chomp($configline);
                   12150: 	my ($short,$plain)=split(/:/,$configline);
                   12151: 	my ($pack,$name)=split(/\&/,$short);
                   12152: 	if ($plain ne '') {
                   12153: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   12154: 	    $packagetab{$short}=$plain; 
                   12155: 	}
1.11      www      12156:     }
1.448     albertel 12157:     close($config);
1.329     matthew  12158: }
                   12159: 
1.1073    raeburn  12160: # ---------------------------------------------------------- Read loncaparev table
                   12161: {
                   12162:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   12163:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   12164:             while (my $configline=<$config>) {
                   12165:                 chomp($configline);
                   12166:                 my ($hostid,$loncaparev)=split(/:/,$configline);
                   12167:                 $loncaparevs{$hostid}=$loncaparev;
                   12168:             }
                   12169:             close($config);
                   12170:         }
                   12171:     }
                   12172: }
                   12173: 
1.1074    raeburn  12174: # ---------------------------------------------------------- Read serverhostID table
                   12175: {
                   12176:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   12177:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   12178:             while (my $configline=<$config>) {
                   12179:                 chomp($configline);
                   12180:                 my ($name,$id)=split(/:/,$configline);
                   12181:                 $serverhomeIDs{$name}=$id;
                   12182:             }
                   12183:             close($config);
                   12184:         }
                   12185:     }
                   12186: }
                   12187: 
1.1079    raeburn  12188: {
                   12189:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   12190:     if (-e $file) {
                   12191:         my $parser = HTML::LCParser->new($file);
                   12192:         while (my $token = $parser->get_token()) {
                   12193:             if ($token->[0] eq 'S') {
                   12194:                 my $item = $token->[1];
                   12195:                 my $name = $token->[2]{'name'};
                   12196:                 my $value = $token->[2]{'value'};
                   12197:                 if ($item ne '' && $name ne '' && $value ne '') {
                   12198:                     my $release = $parser->get_text();
                   12199:                     $release =~ s/(^\s*|\s*$ )//gx;
                   12200:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   12201:                 }
                   12202:             }
                   12203:         }
                   12204:     }
1.1073    raeburn  12205: }
                   12206: 
1.1138    raeburn  12207: # ---------------------------------------------------------- Read managers table
                   12208: {
                   12209:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   12210:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   12211:             while (my $configline=<$config>) {
                   12212:                 chomp($configline);
                   12213:                 next if ($configline =~ /^\#/);
                   12214:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   12215:                     $managerstab{$configline} = 1;
                   12216:                 }
                   12217:             }
                   12218:             close($config);
                   12219:         }
                   12220:     }
                   12221: }
                   12222: 
1.329     matthew  12223: # ------------- set up temporary directory
                   12224: {
1.1117    foxr     12225:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  12226: 
1.11      www      12227: }
                   12228: 
1.794     albertel 12229: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   12230: 				'compress_threshold'=> 20_000,
                   12231:  			        });
1.185     www      12232: 
1.281     www      12233: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      12234: $dumpcount=0;
1.958     www      12235: $locknum=0;
1.22      www      12236: 
1.163     harris41 12237: &logtouch();
1.672     albertel 12238: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      12239: $readit=1;
1.564     albertel 12240:     {
                   12241: 	use integer;
                   12242: 	my $test=(2**32)+1;
1.568     albertel 12243: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 12244: 	&logthis(" Detected 64bit platform ($_64bit)");
                   12245:     }
1.1172.2.18  raeburn  12246: 
                   12247:     {
                   12248:         eval {
                   12249:             ($apache) =
                   12250:                 (Apache2::ServerUtil::get_server_version() =~ m{Apache/(\d+\.\d+)});
                   12251:         };
                   12252:         if ($@) {
                   12253:            $apache = 1.3;
                   12254:         }
                   12255:     }
                   12256: 
1.195     www      12257: }
1.1       albertel 12258: }
1.179     www      12259: 
1.1       albertel 12260: 1;
1.191     harris41 12261: __END__
                   12262: 
1.243     albertel 12263: =pod
                   12264: 
1.191     harris41 12265: =head1 NAME
                   12266: 
1.243     albertel 12267: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 12268: 
                   12269: =head1 SYNOPSIS
                   12270: 
1.243     albertel 12271: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 12272: 
                   12273:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   12274: 
1.243     albertel 12275: Common parameters:
                   12276: 
                   12277: =over 4
                   12278: 
                   12279: =item *
                   12280: 
                   12281: $uname : an internal username (if $cname expecting a course Id specifically)
                   12282: 
                   12283: =item *
                   12284: 
                   12285: $udom : a domain (if $cdom expecting a course's domain specifically)
                   12286: 
                   12287: =item *
                   12288: 
                   12289: $symb : a resource instance identifier
                   12290: 
                   12291: =item *
                   12292: 
                   12293: $namespace : the name of a .db file that contains the data needed or
                   12294: being set.
                   12295: 
                   12296: =back
                   12297: 
1.394     bowersj2 12298: =head1 OVERVIEW
1.191     harris41 12299: 
1.394     bowersj2 12300: lonnet provides subroutines which interact with the
                   12301: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   12302: about classes, users, and resources.
1.243     albertel 12303: 
                   12304: For many of these objects you can also use this to store data about
                   12305: them or modify them in various ways.
1.191     harris41 12306: 
1.394     bowersj2 12307: =head2 Symbs
1.191     harris41 12308: 
1.394     bowersj2 12309: To identify a specific instance of a resource, LON-CAPA uses symbols
                   12310: or "symbs"X<symb>. These identifiers are built from the URL of the
                   12311: map, the resource number of the resource in the map, and the URL of
                   12312: the resource itself. The latter is somewhat redundant, but might help
                   12313: if maps change.
                   12314: 
                   12315: An example is
                   12316: 
                   12317:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   12318: 
                   12319: The respective map entry is
                   12320: 
                   12321:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   12322:   title="Problem 2">
                   12323:  </resource>
                   12324: 
                   12325: Symbs are used by the random number generator, as well as to store and
                   12326: restore data specific to a certain instance of for example a problem.
                   12327: 
                   12328: =head2 Storing And Retrieving Data
                   12329: 
                   12330: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   12331: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   12332: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   12333: is is the non-critical message twin of cstore. These functions are for
                   12334: handlers to store a perl hash to a user's permanent data space in an
                   12335: easy manner, and to retrieve it again on another call. It is expected
                   12336: that a handler would use this once at the beginning to retrieve data,
                   12337: and then again once at the end to send only the new data back.
                   12338: 
                   12339: The data is stored in the user's data directory on the user's
                   12340: homeserver under the ID of the course.
                   12341: 
                   12342: The hash that is returned by restore will have all of the previous
                   12343: value for all of the elements of the hash.
                   12344: 
                   12345: Example:
                   12346: 
                   12347:  #creating a hash
                   12348:  my %hash;
                   12349:  $hash{'foo'}='bar';
                   12350: 
                   12351:  #storing it
                   12352:  &Apache::lonnet::cstore(\%hash);
                   12353: 
                   12354:  #changing a value
                   12355:  $hash{'foo'}='notbar';
                   12356: 
                   12357:  #adding a new value
                   12358:  $hash{'bar'}='foo';
                   12359:  &Apache::lonnet::cstore(\%hash);
                   12360: 
                   12361:  #retrieving the hash
                   12362:  my %history=&Apache::lonnet::restore();
                   12363: 
                   12364:  #print the hash
                   12365:  foreach my $key (sort(keys(%history))) {
                   12366:    print("\%history{$key} = $history{$key}");
                   12367:  }
                   12368: 
                   12369: Will print out:
1.191     harris41 12370: 
1.394     bowersj2 12371:  %history{1:foo} = bar
                   12372:  %history{1:keys} = foo:timestamp
                   12373:  %history{1:timestamp} = 990455579
                   12374:  %history{2:bar} = foo
                   12375:  %history{2:foo} = notbar
                   12376:  %history{2:keys} = foo:bar:timestamp
                   12377:  %history{2:timestamp} = 990455580
                   12378:  %history{bar} = foo
                   12379:  %history{foo} = notbar
                   12380:  %history{timestamp} = 990455580
                   12381:  %history{version} = 2
                   12382: 
                   12383: Note that the special hash entries C<keys>, C<version> and
                   12384: C<timestamp> were added to the hash. C<version> will be equal to the
                   12385: total number of versions of the data that have been stored. The
                   12386: C<timestamp> attribute will be the UNIX time the hash was
                   12387: stored. C<keys> is available in every historical section to list which
                   12388: keys were added or changed at a specific historical revision of a
                   12389: hash.
                   12390: 
                   12391: B<Warning>: do not store the hash that restore returns directly. This
                   12392: will cause a mess since it will restore the historical keys as if the
                   12393: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 12394: 
1.394     bowersj2 12395: Calling convention:
1.191     harris41 12396: 
1.394     bowersj2 12397:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   12398:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 12399: 
1.394     bowersj2 12400: For more detailed information, see lonnet specific documentation.
1.191     harris41 12401: 
1.394     bowersj2 12402: =head1 RETURN MESSAGES
1.191     harris41 12403: 
1.394     bowersj2 12404: =over 4
1.191     harris41 12405: 
1.394     bowersj2 12406: =item * B<con_lost>: unable to contact remote host
1.191     harris41 12407: 
1.394     bowersj2 12408: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   12409: when the connection is brought back up
1.191     harris41 12410: 
1.394     bowersj2 12411: =item * B<con_failed>: unable to contact remote host and unable to save message
                   12412: for later delivery
1.191     harris41 12413: 
1.967     bisitz   12414: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 12415: 
1.394     bowersj2 12416: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 12417: that was requested
1.191     harris41 12418: 
1.243     albertel 12419: =back
1.191     harris41 12420: 
1.243     albertel 12421: =head1 PUBLIC SUBROUTINES
1.191     harris41 12422: 
1.243     albertel 12423: =head2 Session Environment Functions
1.191     harris41 12424: 
1.243     albertel 12425: =over 4
1.191     harris41 12426: 
1.394     bowersj2 12427: =item * 
                   12428: X<appenv()>
1.949     raeburn  12429: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 12430: the user envirnoment file, and will be restored for each access this
1.620     albertel 12431: user makes during this session, also modifies the %env for the current
1.949     raeburn  12432: process. Optional rolesarrayref - if defined contains a reference to an array
                   12433: of roles which are exempt from the restriction on modifying user.role entries 
                   12434: in the user's environment.db and in %env.    
1.191     harris41 12435: 
                   12436: =item *
1.394     bowersj2 12437: X<delenv()>
1.987     raeburn  12438: B<delenv($delthis,$regexp)>: removes all items from the session
                   12439: environment file that begin with $delthis. If the 
                   12440: optional second arg - $regexp - is true, $delthis is treated as a 
                   12441: regular expression, otherwise \Q$delthis\E is used. 
                   12442: The values are also deleted from the current processes %env.
1.191     harris41 12443: 
1.795     albertel 12444: =item * get_env_multiple($name) 
                   12445: 
                   12446: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   12447: values may be defined and end up as an array ref.
                   12448: 
                   12449: returns an array of values
                   12450: 
1.243     albertel 12451: =back
                   12452: 
                   12453: =head2 User Information
1.191     harris41 12454: 
1.243     albertel 12455: =over 4
1.191     harris41 12456: 
                   12457: =item *
1.394     bowersj2 12458: X<queryauthenticate()>
                   12459: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 12460: authentication scheme
                   12461: 
                   12462: =item *
1.394     bowersj2 12463: X<authenticate()>
1.1073    raeburn  12464: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 12465: authenticate user from domain's lib servers (first use the current
                   12466: one). C<$upass> should be the users password.
1.1073    raeburn  12467: $checkdefauth is optional (value is 1 if a check should be made to
                   12468:    authenticate user using default authentication method, and allow
                   12469:    account creation if username does not have account in the domain).
                   12470: $clientcancheckhost is optional (value is 1 if checking whether the
                   12471:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 12472: 
                   12473: =item *
1.394     bowersj2 12474: X<homeserver()>
                   12475: B<homeserver($uname,$udom)>: find the server which has
                   12476: the user's directory and files (there must be only one), this caches
                   12477: the answer, and also caches if there is a borken connection.
1.191     harris41 12478: 
                   12479: =item *
1.394     bowersj2 12480: X<idget()>
                   12481: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   12482: (IDs are a unique resource in a domain, there must be only 1 ID per
                   12483: username, and only 1 username per ID in a specific domain) (returns
                   12484: hash: id=>name,id=>name)
1.191     harris41 12485: 
                   12486: =item *
1.394     bowersj2 12487: X<idrget()>
                   12488: B<idrget($udom,@unames)>: find the IDs behind a list of
                   12489: usernames (returns hash: name=>id,name=>id)
1.191     harris41 12490: 
                   12491: =item *
1.394     bowersj2 12492: X<idput()>
                   12493: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 12494: 
                   12495: =item *
1.394     bowersj2 12496: X<rolesinit()>
1.1169    droeschl 12497: B<rolesinit($udom,$username)>: get user privileges.
                   12498: returns user role, first access and timer interval hashes
1.243     albertel 12499: 
                   12500: =item *
1.1171    droeschl 12501: X<privileged()>
                   12502: B<privileged($username,$domain)>: returns a true if user has a
                   12503: privileged and active role (i.e. su or dc), false otherwise.
                   12504: 
                   12505: =item *
1.551     albertel 12506: X<getsection()>
                   12507: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 12508: course $cname, return section name/number or '' for "not in course"
                   12509: and '-1' for "no section"
                   12510: 
                   12511: =item *
1.394     bowersj2 12512: X<userenvironment()>
                   12513: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 12514: passed in @what from the requested user's environment, returns a hash
                   12515: 
1.858     raeburn  12516: =item * 
                   12517: X<userlog_query()>
1.859     albertel 12518: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   12519: activity.log file. %filters defines filters applied when parsing the
                   12520: log file. These can be start or end timestamps, or the type of action
                   12521: - log to look for Login or Logout events, check for Checkin or
                   12522: Checkout, role for role selection. The response is in the form
                   12523: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   12524: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  12525: 
1.243     albertel 12526: =back
                   12527: 
                   12528: =head2 User Roles
                   12529: 
                   12530: =over 4
                   12531: 
                   12532: =item *
                   12533: 
1.810     raeburn  12534: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 12535:  F: full access
                   12536:  U,I,K: authentication modes (cxx only)
                   12537:  '': forbidden
                   12538:  1: user needs to choose course
                   12539:  2: browse allowed
1.766     albertel 12540:  A: passphrase authentication needed
1.243     albertel 12541: 
                   12542: =item *
                   12543: 
1.1172.2.13  raeburn  12544: constructaccess($url,$setpriv) : check for access to construction space URL
                   12545: 
                   12546: See if the owner domain and name in the URL match those in the
                   12547: expected environment.  If so, return three element list
                   12548: ($ownername,$ownerdomain,$ownerhome).
                   12549: 
                   12550: Otherwise return the null string.
                   12551: 
                   12552: If second argument 'setpriv' is true, it assigns the privileges,
                   12553: and returns the same three element list, unless the owner has
                   12554: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   12555: in which case the null string is returned.
                   12556: 
                   12557: =item *
                   12558: 
1.243     albertel 12559: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   12560: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   12561: and course level
                   12562: 
                   12563: =item *
                   12564: 
1.988     raeburn  12565: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   12566: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  12567: $type is Course (default) or Community.
1.988     raeburn  12568: If $forcedefault evaluates to true, text returned will be default 
                   12569: text for $type. Otherwise, if this is a course, the text returned 
                   12570: will be a custom name for the role (if defined in the course's 
                   12571: environment).  If no custom name is defined the default is returned.
                   12572:    
1.832     raeburn  12573: =item *
                   12574: 
1.1172.2.23  raeburn  12575: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  12576: All arguments are optional. Returns a hash of a roles, either for
                   12577: co-author/assistant author roles for a user's Construction Space
1.906     albertel 12578: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  12579: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   12580: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   12581: For each key, value is set to colon-separated start and end times for
                   12582: the role.  If no username and domain are specified, will default to
1.934     raeburn  12583: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  12584: of role statuses (active, future or previous), roles 
                   12585: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   12586: to restrict the list of roles reported. If no array ref is 
                   12587: provided for types, will default to return only active roles.
1.834     albertel 12588: 
1.1172.2.13  raeburn  12589: =item *
                   12590: 
                   12591: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   12592: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   12593: 
                   12594: Additional optional arguments are: $type (if role checking is to be restricted
                   12595: to certain user status types -- previous (expired roles), active (currently
                   12596: available roles) or future (roles available in the future), and
                   12597: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  12598: have active Domain Coordinator role in course's domain or in additional
                   12599: domains (specified in 'Domains to check for privileged users' in course
                   12600: environment -- set via:  Course Settings -> Classlists and staff listing).
                   12601: 
                   12602: =item *
                   12603: 
                   12604: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   12605: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   12606: $possdomains and $possroles are optional array refs -- to domains to check and
                   12607: roles to check.  If $possdomains is not specified, a dump will be done of the
                   12608: users' roles.db to check for a dc or su role in any domain. This can be
                   12609: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   12610: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   12611: this then allows &privileged_by_domain() to be used, which caches the identity
                   12612: of privileged users, eliminating the need for repeated calls to &dump().
                   12613: 
                   12614: =item *
                   12615: 
                   12616: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   12617: where the outer hash keys are domains specified in the $possdomains array ref,
                   12618: next inner hash keys are privileged roles specified in the $roles array ref,
                   12619: and the innermost hash contains key = value pairs for username:domain = end:start
                   12620: for active or future "privileged" users with that role in that domain. To avoid
                   12621: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   12622: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  12623: 
1.243     albertel 12624: =back
                   12625: 
                   12626: =head2 User Modification
                   12627: 
                   12628: =over 4
                   12629: 
                   12630: =item *
                   12631: 
1.957     raeburn  12632: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 12633: user for the level given by URL.  Optional start and end dates (leave empty
                   12634: string or zero for "no date")
1.191     harris41 12635: 
                   12636: =item *
                   12637: 
1.243     albertel 12638: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   12639: change a users, password, possible return values are: ok,
                   12640: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   12641: refused
1.191     harris41 12642: 
                   12643: =item *
                   12644: 
1.243     albertel 12645: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 12646: 
                   12647: =item *
                   12648: 
1.1058    raeburn  12649: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   12650:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   12651: 
                   12652: will update user information (firstname,middlename,lastname,generation,
                   12653: permanentemail), and if forceid is true, student/employee ID also.
                   12654: A user's institutional affiliation(s) can also be updated.
                   12655: User information fields will not be overwritten with empty entries 
                   12656: unless the field is included in the $candelete array reference.
                   12657: This array is included when a single user is modified via "Manage Users",
                   12658: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 12659: 
                   12660: =item *
                   12661: 
1.286     matthew  12662: modifystudent
                   12663: 
1.957     raeburn  12664: modify a student's enrollment and identification information.
1.286     matthew  12665: The course id is resolved based on the current users environment.  
                   12666: This means the envoking user must be a course coordinator or otherwise
                   12667: associated with a course.
                   12668: 
1.297     matthew  12669: This call is essentially a wrapper for lonnet::modifyuser and
                   12670: lonnet::modify_student_enrollment
1.286     matthew  12671: 
                   12672: Inputs: 
                   12673: 
                   12674: =over 4
                   12675: 
1.957     raeburn  12676: =item B<$udom> Student's loncapa domain
1.286     matthew  12677: 
1.957     raeburn  12678: =item B<$uname> Student's loncapa login name
1.286     matthew  12679: 
1.964     bisitz   12680: =item B<$uid> Student/Employee ID
1.286     matthew  12681: 
1.957     raeburn  12682: =item B<$umode> Student's authentication mode
1.286     matthew  12683: 
1.957     raeburn  12684: =item B<$upass> Student's password
1.286     matthew  12685: 
1.957     raeburn  12686: =item B<$first> Student's first name
1.286     matthew  12687: 
1.957     raeburn  12688: =item B<$middle> Student's middle name
1.286     matthew  12689: 
1.957     raeburn  12690: =item B<$last> Student's last name
1.286     matthew  12691: 
1.957     raeburn  12692: =item B<$gene> Student's generation
1.286     matthew  12693: 
1.957     raeburn  12694: =item B<$usec> Student's section in course
1.286     matthew  12695: 
                   12696: =item B<$end> Unix time of the roles expiration
                   12697: 
                   12698: =item B<$start> Unix time of the roles start date
                   12699: 
                   12700: =item B<$forceid> If defined, allow $uid to be changed
                   12701: 
                   12702: =item B<$desiredhome> server to use as home server for student
                   12703: 
1.957     raeburn  12704: =item B<$email> Student's permanent e-mail address
                   12705: 
                   12706: =item B<$type> Type of enrollment (auto or manual)
                   12707: 
1.963     raeburn  12708: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   12709: 
                   12710: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  12711: 
1.963     raeburn  12712: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  12713: 
1.963     raeburn  12714: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  12715: 
1.1172.2.19  raeburn  12716: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   12717: 
                   12718: =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  12719: 
1.286     matthew  12720: =back
1.297     matthew  12721: 
                   12722: =item *
                   12723: 
                   12724: modify_student_enrollment
                   12725: 
                   12726: Change a students enrollment status in a class.  The environment variable
                   12727: 'role.request.course' must be defined for this function to proceed.
                   12728: 
                   12729: Inputs:
                   12730: 
                   12731: =over 4
                   12732: 
                   12733: =item $udom, students domain
                   12734: 
                   12735: =item $uname, students name
                   12736: 
                   12737: =item $uid, students user id
                   12738: 
                   12739: =item $first, students first name
                   12740: 
                   12741: =item $middle
                   12742: 
                   12743: =item $last
                   12744: 
                   12745: =item $gene
                   12746: 
                   12747: =item $usec
                   12748: 
                   12749: =item $end
                   12750: 
                   12751: =item $start
                   12752: 
1.957     raeburn  12753: =item $type
                   12754: 
                   12755: =item $locktype
                   12756: 
                   12757: =item $cid
                   12758: 
                   12759: =item $selfenroll
                   12760: 
                   12761: =item $context
                   12762: 
1.1172.2.19  raeburn  12763: =item $credits, number of credits student will earn from this class
                   12764: 
1.297     matthew  12765: =back
                   12766: 
1.191     harris41 12767: 
                   12768: =item *
                   12769: 
1.243     albertel 12770: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   12771: custom role; give a custom role to a user for the level given by URL.  Specify
                   12772: name and domain of role author, and role name
1.191     harris41 12773: 
                   12774: =item *
                   12775: 
1.243     albertel 12776: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 12777: 
                   12778: =item *
                   12779: 
1.243     albertel 12780: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   12781: 
                   12782: =back
                   12783: 
                   12784: =head2 Course Infomation
                   12785: 
                   12786: =over 4
1.191     harris41 12787: 
                   12788: =item *
                   12789: 
1.1118    foxr     12790: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 12791: specified course id, including all environment settings for the
                   12792: course, the description of the course will be in the hash under the
                   12793: key 'description'
1.191     harris41 12794: 
1.1118    foxr     12795: $options is an optional parameter that if supplied is a hash reference that controls
                   12796: what how this function works.  It has the following key/values:
                   12797: 
                   12798: =over 4
                   12799: 
                   12800: =item freshen_cache
                   12801: 
                   12802: If defined, and the environment cache for the course is valid, it is 
                   12803: returned in the returned hash.
                   12804: 
                   12805: =item one_time
                   12806: 
                   12807: If defined, the last cache time is set to _now_
                   12808: 
                   12809: =item user
                   12810: 
                   12811: If defined, the supplied username is used instead of the current user.
                   12812: 
                   12813: 
                   12814: =back
                   12815: 
1.191     harris41 12816: =item *
                   12817: 
1.624     albertel 12818: resdata($name,$domain,$type,@which) : request for current parameter
                   12819: setting for a specific $type, where $type is either 'course' or 'user',
                   12820: @what should be a list of parameters to ask about. This routine caches
                   12821: answers for 5 minutes.
1.243     albertel 12822: 
1.877     foxr     12823: =item *
                   12824: 
                   12825: get_courseresdata($courseid, $domain) : dump the entire course resource
                   12826: data base, returning a hash that is keyed by the resource name and has
                   12827: values that are the resource value.  I believe that the timestamps and
                   12828: versions are also returned.
                   12829: 
1.243     albertel 12830: =back
                   12831: 
                   12832: =head2 Course Modification
                   12833: 
                   12834: =over 4
1.191     harris41 12835: 
                   12836: =item *
                   12837: 
1.243     albertel 12838: writecoursepref($courseid,%prefs) : write preferences (environment
                   12839: database) for a course
1.191     harris41 12840: 
                   12841: =item *
                   12842: 
1.1011    raeburn  12843: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   12844: 
                   12845: =item *
                   12846: 
1.1038    raeburn  12847: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 12848: 
1.1167    droeschl 12849: =item *
                   12850: 
                   12851: is_course($courseid), is_course($cdom, $cnum)
                   12852: 
                   12853: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   12854: two component version $cdom, $cnum. It checks if the specified course exists.
                   12855: 
                   12856: Returns:
                   12857:     undef if the course doesn't exist, otherwise
                   12858:     in scalar context the combined courseid.
                   12859:     in list context the two components of the course identifier, domain and 
                   12860:     courseid.    
                   12861: 
1.243     albertel 12862: =back
                   12863: 
                   12864: =head2 Resource Subroutines
                   12865: 
                   12866: =over 4
1.191     harris41 12867: 
                   12868: =item *
                   12869: 
1.243     albertel 12870: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 12871: 
                   12872: =item *
                   12873: 
1.243     albertel 12874: repcopy($filename) : subscribes to the requested file, and attempts to
                   12875: replicate from the owning library server, Might return
1.607     raeburn  12876: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   12877: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 12878: resource. Expects the local filesystem pathname
                   12879: (/home/httpd/html/res/....)
                   12880: 
                   12881: =back
                   12882: 
                   12883: =head2 Resource Information
                   12884: 
                   12885: =over 4
1.191     harris41 12886: 
                   12887: =item *
                   12888: 
1.243     albertel 12889: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   12890: a vairety of different possible values, $varname should be a request
                   12891: string, and the other parameters can be used to specify who and what
                   12892: one is asking about.
                   12893: 
                   12894: Possible values for $varname are environment.lastname (or other item
                   12895: from the envirnment hash), user.name (or someother aspect about the
                   12896: user), resource.0.maxtries (or some other part and parameter of a
                   12897: resource)
1.204     albertel 12898: 
                   12899: =item *
                   12900: 
1.243     albertel 12901: directcondval($number) : get current value of a condition; reads from a state
                   12902: string
1.204     albertel 12903: 
                   12904: =item *
                   12905: 
1.243     albertel 12906: condval($condidx) : value of condition index based on state
1.204     albertel 12907: 
                   12908: =item *
                   12909: 
1.243     albertel 12910: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   12911: resource's metadata, $what should be either a specific key, or either
                   12912: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   12913: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   12914: 
                   12915: this function automatically caches all requests
1.191     harris41 12916: 
                   12917: =item *
                   12918: 
1.243     albertel 12919: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   12920: network of library servers; returns file handle of where SQL and regex results
                   12921: will be stored for query
1.191     harris41 12922: 
                   12923: =item *
                   12924: 
1.243     albertel 12925: symbread($filename) : return symbolic list entry (filename argument optional);
                   12926: returns the data handle
1.191     harris41 12927: 
                   12928: =item *
                   12929: 
1.1172.2.17  raeburn  12930: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  12931: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 12932: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  12933: on failure, user must be in a course, as it assumes the existence of
                   12934: the course initial hash, and uses $env('request.course.id'}.  The third
                   12935: arg is an optional reference to a scalar.  If this arg is passed in the
                   12936: call to symbverify, it will be set to 1 if the symb has been set to be 
                   12937: encrypted; otherwise it will be null.
1.243     albertel 12938: 
1.191     harris41 12939: =item *
                   12940: 
1.243     albertel 12941: symbclean($symb) : removes versions numbers from a symb, returns the
                   12942: cleaned symb
1.191     harris41 12943: 
                   12944: =item *
                   12945: 
1.243     albertel 12946: is_on_map($uri) : checks if the $uri is somewhere on the current
                   12947: course map, user must be in a course for it to work.
1.191     harris41 12948: 
                   12949: =item *
                   12950: 
1.243     albertel 12951: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 12952: 
                   12953: =item *
                   12954: 
1.243     albertel 12955: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   12956: a random seed, all arguments are optional, if they aren't sent it uses the
                   12957: environment to derive them. Note: if symb isn't sent and it can't get one
                   12958: from &symbread it will use the current time as its return value
1.191     harris41 12959: 
                   12960: =item *
                   12961: 
1.243     albertel 12962: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   12963: unfakeable, receipt
1.191     harris41 12964: 
                   12965: =item *
                   12966: 
1.620     albertel 12967: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 12968: 
                   12969: =item *
                   12970: 
1.243     albertel 12971: countacc($url) : count the number of accesses to a given URL
1.191     harris41 12972: 
                   12973: =item *
                   12974: 
1.243     albertel 12975: 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 12976: 
                   12977: =item *
                   12978: 
1.243     albertel 12979: 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 12980: 
                   12981: =item *
                   12982: 
1.243     albertel 12983: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 12984: 
                   12985: =item *
                   12986: 
1.243     albertel 12987: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   12988: forcing spreadsheet to reevaluate the resource scores next time.
                   12989: 
1.1172.2.13  raeburn  12990: =item *
                   12991: 
                   12992: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   12993: when viewing in course context.
                   12994: 
                   12995:  input: six args -- filename (decluttered), course number, course domain,
                   12996:                     url, symb (if registered) and group (if this is a
                   12997:                     group item -- e.g., bulletin board, group page etc.).
                   12998: 
                   12999:  output: array of five scalars --
                   13000:          $cfile -- url for file editing if editable on current server
                   13001:          $home -- homeserver of resource (i.e., for author if published,
                   13002:                                           or course if uploaded.).
                   13003:          $switchserver --  1 if server switch will be needed.
                   13004:          $forceedit -- 1 if icon/link should be to go to edit mode
                   13005:          $forceview -- 1 if icon/link should be to go to view mode
                   13006: 
                   13007: =item *
                   13008: 
                   13009: is_course_upload($file,$cnum,$cdom)
                   13010: 
                   13011: Used in course context to determine if current file was uploaded to
                   13012: the course (i.e., would be found in /userfiles/docs on the course's
                   13013: homeserver.
                   13014: 
                   13015:   input: 3 args -- filename (decluttered), course number and course domain.
                   13016:   output: boolean -- 1 if file was uploaded.
                   13017: 
1.243     albertel 13018: =back
                   13019: 
                   13020: =head2 Storing/Retreiving Data
                   13021: 
                   13022: =over 4
1.191     harris41 13023: 
                   13024: =item *
                   13025: 
1.243     albertel 13026: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   13027: for this url; hashref needs to be given and should be a \%hashname; the
                   13028: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 13029: be derived from the env
1.191     harris41 13030: 
                   13031: =item *
                   13032: 
1.243     albertel 13033: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   13034: uses critical subroutine
1.191     harris41 13035: 
                   13036: =item *
                   13037: 
1.243     albertel 13038: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   13039: all args are optional
1.191     harris41 13040: 
                   13041: =item *
                   13042: 
1.717     albertel 13043: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   13044: dumps the complete (or key matching regexp) namespace into a hash
                   13045: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   13046: normally &store()ed into
                   13047: 
                   13048: $range should be either an integer '100' (give me the first 100
                   13049:                                            matching records)
                   13050:               or be  two integers sperated by a - with no spaces
                   13051:                  '30-50' (give me the 30th through the 50th matching
                   13052:                           records)
                   13053: 
                   13054: 
                   13055: =item *
                   13056: 
                   13057: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   13058: replaces a &store() version of data with a replacement set of data
                   13059: for a particular resource in a namespace passed in the $storehash hash 
                   13060: reference
                   13061: 
                   13062: =item *
                   13063: 
1.243     albertel 13064: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   13065: works very similar to store/cstore, but all data is stored in a
                   13066: temporary location and can be reset using tmpreset, $storehash should
                   13067: be a hash reference, returns nothing on success
1.191     harris41 13068: 
                   13069: =item *
                   13070: 
1.243     albertel 13071: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   13072: similar to restore, but all data is stored in a temporary location and
                   13073: can be reset using tmpreset. Returns a hash of values on success,
                   13074: error string otherwise.
1.191     harris41 13075: 
                   13076: =item *
                   13077: 
1.243     albertel 13078: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   13079: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 13080: 
                   13081: =item *
                   13082: 
1.243     albertel 13083: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13084: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 13085: 
                   13086: =item *
                   13087: 
1.243     albertel 13088: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   13089: namesp ($udom and $uname are optional)
1.191     harris41 13090: 
                   13091: =item *
                   13092: 
1.702     albertel 13093: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 13094: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 13095: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  13096: 
1.702     albertel 13097: $range should be either an integer '100' (give me the first 100
                   13098:                                            matching records)
                   13099:               or be  two integers sperated by a - with no spaces
                   13100:                  '30-50' (give me the 30th through the 50th matching
                   13101:                           records)
1.449     matthew  13102: =item *
                   13103: 
                   13104: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   13105: $store can be a scalar, an array reference, or if the amount to be 
                   13106: incremented is > 1, a hash reference.
                   13107: 
                   13108: ($udom and $uname are optional)
1.191     harris41 13109: 
                   13110: =item *
                   13111: 
1.243     albertel 13112: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   13113: ($udom and $uname are optional)
1.191     harris41 13114: 
                   13115: =item *
                   13116: 
1.243     albertel 13117: cput($namespace,$storehash,$udom,$uname) : critical put
                   13118: ($udom and $uname are optional)
1.191     harris41 13119: 
                   13120: =item *
                   13121: 
1.748     albertel 13122: newput($namespace,$storehash,$udom,$uname) :
                   13123: 
                   13124: Attempts to store the items in the $storehash, but only if they don't
                   13125: currently exist, if this succeeds you can be certain that you have 
                   13126: successfully created a new key value pair in the $namespace db.
                   13127: 
                   13128: 
                   13129: Args:
                   13130:  $namespace: name of database to store values to
                   13131:  $storehash: hashref to store to the db
                   13132:  $udom: (optional) domain of user containing the db
                   13133:  $uname: (optional) name of user caontaining the db
                   13134: 
                   13135: Returns:
                   13136:  'ok' -> succeeded in storing all keys of $storehash
                   13137:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   13138:                         least <key> already existed in the db (other
                   13139:                         requested keys may also already exist)
1.967     bisitz   13140:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 13141:  'con_lost' -> unable to contact request server
                   13142:  'refused' -> action was not allowed by remote machine
                   13143: 
                   13144: 
                   13145: =item *
                   13146: 
1.243     albertel 13147: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13148: reference filled in from namesp (encrypts the return communication)
                   13149: ($udom and $uname are optional)
1.191     harris41 13150: 
                   13151: =item *
                   13152: 
1.243     albertel 13153: log($udom,$name,$home,$message) : write to permanent log for user; use
                   13154: critical subroutine
                   13155: 
1.806     raeburn  13156: =item *
                   13157: 
1.860     raeburn  13158: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   13159: array reference filled in from namespace found in domain level on either
                   13160: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  13161: 
                   13162: =item *
                   13163: 
1.860     raeburn  13164: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   13165: domain level either on specified domain server ($uhome) or primary domain 
                   13166: server ($udom and $uhome are optional)
1.806     raeburn  13167: 
1.943     raeburn  13168: =item * 
                   13169: 
                   13170: get_domain_defaults($target_domain) : returns hash with defaults for
                   13171: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   13172: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   13173: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   13174: Values are retrieved from cache (if current), or from domain's configuration.db
                   13175: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   13176: or lonTabs/domain.tab. 
                   13177: 
                   13178: %domdefaults = &get_auth_defaults($target_domain);
                   13179: 
1.243     albertel 13180: =back
                   13181: 
                   13182: =head2 Network Status Functions
                   13183: 
                   13184: =over 4
1.191     harris41 13185: 
                   13186: =item *
                   13187: 
1.1137    raeburn  13188: dirlist() : return directory list based on URI (first arg).
                   13189: 
                   13190: Inputs: 1 required, 5 optional.
                   13191: 
                   13192: =over
                   13193: 
                   13194: =item 
                   13195: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   13196: 
                   13197: =item
                   13198: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   13199: 
                   13200: =item
                   13201: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   13202: 
                   13203: =item
                   13204: $getpropath - boolean: 1 if prepend path using &propath(). 
                   13205: 
                   13206: =item
                   13207: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   13208: 
                   13209: =item 
                   13210: $alternateRoot - path to prepend in place of path from $uri.
                   13211: 
                   13212: =back
                   13213: 
                   13214: Returns: Array of up to two items.
                   13215: 
                   13216: =over
                   13217: 
                   13218: a reference to an array of files/subdirectories
                   13219: 
                   13220: =over
                   13221: 
                   13222: Each element in the array of files/subdirectories is a & separated list of
                   13223: item name and the result of running stat on the item.  If dirlist was requested
                   13224: for a file instead of a directory, the item name will be ''. For a directory 
                   13225: listing, if the item is a metadata file, the element will end &N&M 
                   13226: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   13227: default copyright set (1).  
                   13228: 
                   13229: =back
                   13230: 
                   13231: a scalar containing error condition (if encountered).
                   13232: 
                   13233: =over
                   13234: 
                   13235: =item 
                   13236: no_host (no homeserver identified for $username:$domain).
                   13237: 
                   13238: =item 
                   13239: no_such_host (server contacted for listing not identified as valid host).
                   13240: 
                   13241: =item 
                   13242: con_lost (connection to remote server failed).
                   13243: 
                   13244: =item 
                   13245: refused (invalid $username:$domain received on lond side).
                   13246: 
                   13247: =item 
                   13248: no_such_dir (directory at specified path on lond side does not exist). 
                   13249: 
                   13250: =item 
                   13251: empty (directory at specified path on lond side is empty).
                   13252: 
                   13253: =over
                   13254: 
                   13255: This is currently not encountered because the &ls3, &ls2, 
                   13256: &ls (_handler) routines on the lond side do not filter out
                   13257: . and .. from a directory listing. 
                   13258: 
                   13259: =back
                   13260: 
                   13261: =back
                   13262: 
                   13263: =back
1.191     harris41 13264: 
                   13265: =item *
                   13266: 
1.243     albertel 13267: spareserver() : find server with least workload from spare.tab
                   13268: 
1.986     foxr     13269: 
                   13270: =item *
                   13271: 
                   13272: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   13273: if there is no corresponding loncapa host.
                   13274: 
1.243     albertel 13275: =back
                   13276: 
1.986     foxr     13277: 
1.243     albertel 13278: =head2 Apache Request
                   13279: 
                   13280: =over 4
1.191     harris41 13281: 
                   13282: =item *
                   13283: 
1.243     albertel 13284: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   13285: localhost, posts hash
                   13286: 
                   13287: =back
                   13288: 
                   13289: =head2 Data to String to Data
                   13290: 
                   13291: =over 4
1.191     harris41 13292: 
                   13293: =item *
                   13294: 
1.243     albertel 13295: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   13296: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 13297: 
                   13298: =item *
                   13299: 
1.243     albertel 13300: hashref2str($hashref) : convert a hashref into a string complete with
                   13301: escaping and '=' and '&' separators, supports elements that are
                   13302: arrayrefs and hashrefs
1.191     harris41 13303: 
                   13304: =item *
                   13305: 
1.243     albertel 13306: arrayref2str($arrayref) : convert an arrayref into a string complete
                   13307: with escaping and '&' separators, supports elements that are arrayrefs
                   13308: and hashrefs
1.191     harris41 13309: 
                   13310: =item *
                   13311: 
1.243     albertel 13312: str2hash($string) : convert string to hash using unescaping and
                   13313: splitting on '=' and '&', supports elements that are arrayrefs and
                   13314: hashrefs
1.191     harris41 13315: 
                   13316: =item *
                   13317: 
1.243     albertel 13318: str2array($string) : convert string to hash using unescaping and
                   13319: splitting on '&', supports elements that are arrayrefs and hashrefs
                   13320: 
                   13321: =back
                   13322: 
                   13323: =head2 Logging Routines
                   13324: 
                   13325: 
                   13326: These routines allow one to make log messages in the lonnet.log and
                   13327: lonnet.perm logfiles.
1.191     harris41 13328: 
1.1119    foxr     13329: =over 4
                   13330: 
1.191     harris41 13331: =item *
                   13332: 
1.243     albertel 13333: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 13334: 
                   13335: =item *
                   13336: 
1.243     albertel 13337: logthis() : append message to the normal lonnet.log file, it gets
                   13338: preiodically rolled over and deleted.
1.191     harris41 13339: 
                   13340: =item *
                   13341: 
1.243     albertel 13342: logperm() : append a permanent message to lonnet.perm.log, this log
                   13343: file never gets deleted by any automated portion of the system, only
                   13344: messages of critical importance should go in here.
                   13345: 
1.1119    foxr     13346: 
1.243     albertel 13347: =back
                   13348: 
                   13349: =head2 General File Helper Routines
                   13350: 
                   13351: =over 4
1.191     harris41 13352: 
                   13353: =item *
                   13354: 
1.481     raeburn  13355: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   13356: (a) files in /uploaded
                   13357:   (i) If a local copy of the file exists - 
                   13358:       compares modification date of local copy with last-modified date for 
                   13359:       definitive version stored on home server for course. If local copy is 
                   13360:       stale, requests a new version from the home server and stores it. 
                   13361:       If the original has been removed from the home server, then local copy 
                   13362:       is unlinked.
                   13363:   (ii) If local copy does not exist -
                   13364:       requests the file from the home server and stores it. 
                   13365:   
                   13366:   If $caller is 'uploadrep':  
                   13367:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   13368:     for request for files originally uploaded via DOCS. 
                   13369:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   13370:   
                   13371:   Otherwise:
                   13372:      This indicates a call from the content generation phase of the request.
                   13373:      -  returns the entire contents of the file or -1.
                   13374:      
                   13375: (b) files in /res
                   13376:    - returns the entire contents of a file or -1; 
                   13377:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 13378: 
1.712     albertel 13379: 
                   13380: =item *
                   13381: 
                   13382: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   13383:                   reference
                   13384: 
                   13385: returns either a stat() list of data about the file or an empty list
                   13386: if the file doesn't exist or couldn't find out about it (connection
                   13387: problems or user unknown)
                   13388: 
1.191     harris41 13389: =item *
                   13390: 
1.243     albertel 13391: filelocation($dir,$file) : returns file system location of a file
                   13392: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   13393: directory that relative $file lookups are to looked in ($dir of /a/dir
                   13394: and a file of ../bob will become /a/bob)
1.191     harris41 13395: 
                   13396: =item *
                   13397: 
                   13398: hreflocation($dir,$file) : returns file system location or a URL; same as
                   13399: filelocation except for hrefs
                   13400: 
                   13401: =item *
                   13402: 
                   13403: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   13404: 
1.243     albertel 13405: =back
                   13406: 
1.608     albertel 13407: =head2 Usererfile file routines (/uploaded*)
                   13408: 
                   13409: =over 4
                   13410: 
                   13411: =item *
                   13412: 
                   13413: userfileupload(): main rotine for putting a file in a user or course's
                   13414:                   filespace, arguments are,
                   13415: 
1.620     albertel 13416:  formname - required - this is the name of the element in $env where the
1.608     albertel 13417:            filename, and the contents of the file to create/modifed exist
1.620     albertel 13418:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   13419:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  13420:  context - if coursedoc, store the file in the course of the active role
                   13421:              of the current user; 
                   13422:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   13423:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 13424:  subdir - required - subdirectory to put the file in under ../userfiles/
                   13425:          if undefined, it will be placed in "unknown"
                   13426: 
                   13427:  (This routine calls clean_filename() to remove any dangerous
                   13428:  characters from the filename, and then calls finuserfileupload() to
                   13429:  complete the transaction)
                   13430: 
                   13431:  returns either the url of the uploaded file (/uploaded/....) if successful
                   13432:  and /adm/notfound.html if unsuccessful
                   13433: 
                   13434: =item *
                   13435: 
                   13436: clean_filename(): routine for cleaing a filename up for storage in
                   13437:                  userfile space, argument is:
                   13438: 
                   13439:  filename - proposed filename
                   13440: 
                   13441: returns: the new clean filename
                   13442: 
                   13443: =item *
                   13444: 
1.1090    raeburn  13445: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 13446: userspace, probably shouldn't be called directly
                   13447: 
                   13448:   docuname: username or courseid of destination for the file
                   13449:   docudom: domain of user/course of destination for the file
                   13450:   formname: same as for userfileupload()
1.1090    raeburn  13451:   fname: filename (including subdirectories) for the file
                   13452:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   13453:   allfiles: reference to hash used to store objects found by parser
                   13454:   codebase: reference to hash used for codebases of java objects found by parser
                   13455:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   13456:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   13457:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   13458:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   13459:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   13460:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  13461:   mimetype: reference to scalar to accommodate mime type determined
                   13462:             from File::MMagic if $parser = parse.
1.608     albertel 13463: 
                   13464:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  13465:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   13466:  was 'overwrite').
                   13467:  
1.608     albertel 13468: 
                   13469: =item *
                   13470: 
                   13471: renameuserfile(): renames an existing userfile to a new name
                   13472: 
                   13473:   Args:
                   13474:    docuname: username or courseid of destination for the file
                   13475:    docudom: domain of user/course of destination for the file
                   13476:    old: current file name (including any subdirs under userfiles)
                   13477:    new: desired file name (including any subdirs under userfiles)
                   13478: 
                   13479: =item *
                   13480: 
                   13481: mkdiruserfile(): creates a directory is a userfiles dir
                   13482: 
                   13483:   Args:
                   13484:    docuname: username or courseid of destination for the file
                   13485:    docudom: domain of user/course of destination for the file
                   13486:    dir: dir to create (including any subdirs under userfiles)
                   13487: 
                   13488: =item *
                   13489: 
                   13490: removeuserfile(): removes a file that exists in userfiles
                   13491: 
                   13492:   Args:
                   13493:    docuname: username or courseid of destination for the file
                   13494:    docudom: domain of user/course of destination for the file
                   13495:    fname: filname to delete (including any subdirs under userfiles)
                   13496: 
                   13497: =item *
                   13498: 
                   13499: removeuploadedurl(): convience function for removeuserfile()
                   13500: 
                   13501:   Args:
                   13502:    url:  a full /uploaded/... url to delete
                   13503: 
1.747     albertel 13504: =item * 
                   13505: 
                   13506: get_portfile_permissions():
                   13507:   Args:
                   13508:     domain: domain of user or course contain the portfolio files
                   13509:     user: name of user or num of course contain the portfolio files
                   13510:   Returns:
                   13511:     hashref of a dump of the proper file_permissions.db
                   13512:    
                   13513: 
                   13514: =item * 
                   13515: 
                   13516: get_access_controls():
                   13517: 
                   13518: Args:
                   13519:   current_permissions: the hash ref returned from get_portfile_permissions()
                   13520:   group: (optional) the group you want the files associated with
                   13521:   file: (optional) the file you want access info on
                   13522: 
                   13523: Returns:
1.749     raeburn  13524:     a hash (keys are file names) of hashes containing
                   13525:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   13526:         values are XML containing access control settings (see below) 
1.747     albertel 13527: 
                   13528: Internal notes:
                   13529: 
1.749     raeburn  13530:  access controls are stored in file_permissions.db as key=value pairs.
                   13531:     key -> path to file/file_name\0uniqueID:scope_end_start
                   13532:         where scope -> public,guest,course,group,domains or users.
                   13533:               end -> UNIX time for end of access (0 -> no end date)
                   13534:               start -> UNIX time for start of access
                   13535: 
                   13536:     value -> XML description of access control
                   13537:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   13538:             <start></start>
                   13539:             <end></end>
                   13540: 
                   13541:             <password></password>  for scope type = guest
                   13542: 
                   13543:             <domain></domain>     for scope type = course or group
                   13544:             <number></number>
                   13545:             <roles id="">
                   13546:              <role></role>
                   13547:              <access></access>
                   13548:              <section></section>
                   13549:              <group></group>
                   13550:             </roles>
                   13551: 
                   13552:             <dom></dom>         for scope type = domains
                   13553: 
                   13554:             <users>             for scope type = users
                   13555:              <user>
                   13556:               <uname></uname>
                   13557:               <udom></udom>
                   13558:              </user>
                   13559:             </users>
                   13560:            </scope> 
                   13561:               
                   13562:  Access data is also aggregated for each file in an additional key=value pair:
                   13563:  key -> path to file/file_name\0accesscontrol 
                   13564:  value -> reference to hash
                   13565:           hash contains key = value pairs
                   13566:           where key = uniqueID:scope_end_start
                   13567:                 value = UNIX time record was last updated
                   13568: 
                   13569:           Used to improve speed of look-ups of access controls for each file.  
                   13570:  
                   13571:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   13572: 
1.1172.2.13  raeburn  13573: =item *
                   13574: 
1.749     raeburn  13575: modify_access_controls():
                   13576: 
                   13577: Modifies access controls for a portfolio file
                   13578: Args
                   13579: 1. file name
                   13580: 2. reference to hash of required changes,
                   13581: 3. domain
                   13582: 4. username
                   13583:   where domain,username are the domain of the portfolio owner 
                   13584:   (either a user or a course) 
                   13585: 
                   13586: Returns:
                   13587: 1. result of additions or updates ('ok' or 'error', with error message). 
                   13588: 2. result of deletions ('ok' or 'error', with error message).
                   13589: 3. reference to hash of any new or updated access controls.
                   13590: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   13591:    key = integer (inbound ID)
1.1172.2.13  raeburn  13592:    value = uniqueID
                   13593: 
                   13594: =item *
                   13595: 
                   13596: get_timebased_id():
                   13597: 
                   13598: Attempts to get a unique timestamp-based suffix for use with items added to a
                   13599: course via the Course Editor (e.g., folders, composite pages,
                   13600: group bulletin boards).
                   13601: 
                   13602: Args: (first three required; six others optional)
                   13603: 
                   13604: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   13605:    docssequence, or name of group
                   13606: 
                   13607: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   13608:    e.g., num, boardids
                   13609: 
                   13610: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   13611:    file will be named nohist_namespace.db
                   13612: 
                   13613: 4. cdom: domain of course; default is current course domain from %env
                   13614: 
                   13615: 5. cnum: course number; default is current course number from %env
                   13616: 
                   13617: 6. idtype: set to concat if an additional digit is to be appended to the
                   13618:    unix timestamp to form the suffix, if the plain timestamp is already
                   13619:    in use.  Default is to not do this, but simply increment the unix
                   13620:    timestamp by 1 until a unique key is obtained.
                   13621: 
                   13622: 7. who: holder of locking key; defaults to user:domain for user.
                   13623: 
                   13624: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   13625:    retrying); default is 3.
                   13626: 
                   13627: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   13628: 
                   13629: Returns:
                   13630: 
                   13631: 1. suffix obtained (numeric)
                   13632: 
                   13633: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   13634: 
                   13635: 3. error: contains (localized) error message if an error occurred.
                   13636: 
1.747     albertel 13637: 
1.608     albertel 13638: =back
                   13639: 
1.243     albertel 13640: =head2 HTTP Helper Routines
                   13641: 
                   13642: =over 4
                   13643: 
1.191     harris41 13644: =item *
                   13645: 
                   13646: escape() : unpack non-word characters into CGI-compatible hex codes
                   13647: 
                   13648: =item *
                   13649: 
                   13650: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   13651: 
1.243     albertel 13652: =back
                   13653: 
                   13654: =head1 PRIVATE SUBROUTINES
                   13655: 
                   13656: =head2 Underlying communication routines (Shouldn't call)
                   13657: 
                   13658: =over 4
                   13659: 
                   13660: =item *
                   13661: 
                   13662: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   13663: 
                   13664: =item *
                   13665: 
                   13666: reply() : uses subreply to send a message to remote machine, logs all failures
                   13667: 
                   13668: =item *
                   13669: 
                   13670: critical() : passes a critical message to another server; if cannot
                   13671: get through then place message in connection buffer directory and
                   13672: returns con_delayed, if incapable of saving message, returns
                   13673: con_failed
                   13674: 
                   13675: =item *
                   13676: 
                   13677: reconlonc() : tries to reconnect lonc client processes.
                   13678: 
                   13679: =back
                   13680: 
                   13681: =head2 Resource Access Logging
                   13682: 
                   13683: =over 4
                   13684: 
                   13685: =item *
                   13686: 
                   13687: flushcourselogs() : flush (save) buffer logs and access logs
                   13688: 
                   13689: =item *
                   13690: 
                   13691: courselog($what) : save message for course in hash
                   13692: 
                   13693: =item *
                   13694: 
                   13695: courseacclog($what) : save message for course using &courselog().  Perform
                   13696: special processing for specific resource types (problems, exams, quizzes, etc).
                   13697: 
1.191     harris41 13698: =item *
                   13699: 
                   13700: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   13701: as a PerlChildExitHandler
1.243     albertel 13702: 
                   13703: =back
                   13704: 
                   13705: =head2 Other
                   13706: 
                   13707: =over 4
                   13708: 
                   13709: =item *
                   13710: 
                   13711: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 13712: 
                   13713: =back
                   13714: 
                   13715: =cut
1.877     foxr     13716: 

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