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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.13! raeburn     4: # $Id: lonnet.pm,v 1.1172.2.12 2012/09/25 23:15:25 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.871     albertel   78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138    raeburn    79:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
                     80:             %managerstab);
1.871     albertel   81: 
                     82: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     83:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     84:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        85:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        86: 
1.1       albertel   87: use IO::Socket;
1.31      www        88: use GDBM_File;
1.208     albertel   89: use HTML::LCParser;
1.88      www        90: use Fcntl qw(:flock);
1.870     albertel   91: use Storable qw(thaw nfreeze);
1.539     albertel   92: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   93: use Cache::Memcached;
1.676     albertel   94: use Digest::MD5;
1.790     albertel   95: use Math::Random;
1.1024    raeburn    96: use File::MMagic;
1.807     albertel   97: use LONCAPA qw(:DEFAULT :match);
1.740     www        98: use LONCAPA::Configuration;
1.1160    www        99: use LONCAPA::lonmetadata;
1.1117    foxr      100: 
1.1090    raeburn   101: use File::Copy;
1.676     albertel  102: 
1.195     www       103: my $readit;
1.550     foxr      104: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel  105: 
1.619     albertel  106: require Exporter;
                    107: 
                    108: our @ISA = qw (Exporter);
                    109: our @EXPORT = qw(%env);
                    110: 
1.1172.2.9  raeburn   111: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729     www       112: {
                    113:     my $logid;
1.1172.2.9  raeburn   114:     sub write_log {
                    115: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    116:         if ($context eq 'course') {
                    117:             if (($cnum eq '') || ($cdom eq '')) {
                    118:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    119:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    120:             }
1.957     raeburn   121:         }
1.1172.2.13! raeburn   122: 	$logid ++;
1.957     raeburn   123:         my $now = time();
                    124: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.1172.2.9  raeburn   125:         my $logentry = {
                    126:                          $id => {
                    127:                                   'exe_uname' => $env{'user.name'},
                    128:                                   'exe_udom'  => $env{'user.domain'},
                    129:                                   'exe_time'  => $now,
                    130:                                   'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    131:                                   'delflag'   => $delflag,
                    132:                                   'logentry'  => $storehash,
                    133:                                   'uname'     => $uname,
                    134:                                   'udom'      => $udom,
                    135:                                 }
                    136:                        };
                    137:         return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729     www       138:     }
                    139: }
1.1       albertel  140: 
1.163     harris41  141: sub logtouch {
                    142:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  143:     unless (-e "$execdir/logs/lonnet.log") {	
                    144: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  145: 	close $fh;
                    146:     }
                    147:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    148:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    149: }
                    150: 
1.1       albertel  151: sub logthis {
                    152:     my $message=shift;
                    153:     my $execdir=$perlvar{'lonDaemons'};
                    154:     my $now=time;
                    155:     my $local=localtime($now);
1.448     albertel  156:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986     foxr      157: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    158: 	print $fh $logstring;
1.448     albertel  159: 	close($fh);
                    160:     }
1.1       albertel  161:     return 1;
                    162: }
                    163: 
                    164: sub logperm {
                    165:     my $message=shift;
                    166:     my $execdir=$perlvar{'lonDaemons'};
                    167:     my $now=time;
                    168:     my $local=localtime($now);
1.448     albertel  169:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    170: 	print $fh "$now:$message:$local\n";
                    171: 	close($fh);
                    172:     }
1.1       albertel  173:     return 1;
                    174: }
                    175: 
1.850     albertel  176: sub create_connection {
1.853     albertel  177:     my ($hostname,$lonid) = @_;
1.851     albertel  178:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  179: 				     Type    => SOCK_STREAM,
                    180: 				     Timeout => 10);
                    181:     return 0 if (!$client);
1.890     albertel  182:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  183:     my $result = <$client>;
                    184:     chomp($result);
                    185:     return 1 if ($result eq 'done');
                    186:     return 0;
                    187: }
                    188: 
1.983     raeburn   189: sub get_server_timezone {
                    190:     my ($cnum,$cdom) = @_;
                    191:     my $home=&homeserver($cnum,$cdom);
                    192:     if ($home ne 'no_host') {
                    193:         my $cachetime = 24*3600;
                    194:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    195:         if (defined($cached)) {
                    196:             return $timezone;
                    197:         } else {
                    198:             my $timezone = &reply('servertimezone',$home);
                    199:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    200:         }
                    201:     }
                    202: }
1.850     albertel  203: 
1.1106    raeburn   204: sub get_server_distarch {
                    205:     my ($lonhost,$ignore_cache) = @_;
                    206:     if (defined($lonhost)) {
                    207:         if (!defined(&hostname($lonhost))) {
                    208:             return;
                    209:         }
                    210:         my $cachetime = 12*3600;
                    211:         if (!$ignore_cache) {
                    212:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    213:             if (defined($cached)) {
                    214:                 return $distarch;
                    215:             }
                    216:         }
                    217:         my $rep = &reply('serverdistarch',$lonhost);
                    218:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    219:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    220:                 $rep eq '') {
                    221:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    222:         }
                    223:     }
                    224:     return;
                    225: }
                    226: 
1.993     raeburn   227: sub get_server_loncaparev {
1.1073    raeburn   228:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   229:     if (defined($lonhost)) {
                    230:         if (!defined(&hostname($lonhost))) {
                    231:             undef($lonhost);
                    232:         }
                    233:     }
                    234:     if (!defined($lonhost)) {
                    235:         if (defined(&domain($dom,'primary'))) {
                    236:             $lonhost=&domain($dom,'primary');
                    237:             if ($lonhost eq 'no_host') {
                    238:                 undef($lonhost);
                    239:             }
                    240:         }
                    241:     }
                    242:     if (defined($lonhost)) {
1.1073    raeburn   243:         my $cachetime = 12*3600;
                    244:         if (!$ignore_cache) {
                    245:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    246:             if (defined($cached)) {
                    247:                 return $loncaparev;
                    248:             }
                    249:         }
                    250:         my ($answer,$loncaparev);
                    251:         my @ids=&current_machine_ids();
                    252:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    253:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   254:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   255:                 $loncaparev = $1;
                    256:             }
                    257:         } else {
                    258:             $answer = &reply('serverloncaparev',$lonhost);
                    259:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    260:                 if ($caller eq 'loncron') {
                    261:                     my $ua=new LWP::UserAgent;
1.1082    raeburn   262:                     $ua->timeout(4);
1.1073    raeburn   263:                     my $protocol = $protocol{$lonhost};
                    264:                     $protocol = 'http' if ($protocol ne 'https');
                    265:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
                    266:                     my $request=new HTTP::Request('GET',$url);
                    267:                     my $response=$ua->request($request);
                    268:                     unless ($response->is_error()) {
                    269:                         my $content = $response->content;
1.1081    raeburn   270:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   271:                             $loncaparev = $1;
                    272:                         }
                    273:                     }
                    274:                 } else {
                    275:                     $loncaparev = $loncaparevs{$lonhost};
                    276:                 }
1.1081    raeburn   277:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   278:                 $loncaparev = $1;
                    279:             }
1.993     raeburn   280:         }
1.1073    raeburn   281:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   282:     }
                    283: }
                    284: 
1.1074    raeburn   285: sub get_server_homeID {
                    286:     my ($hostname,$ignore_cache,$caller) = @_;
                    287:     unless ($ignore_cache) {
                    288:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    289:         if (defined($cached)) {
                    290:             return $serverhomeID;
                    291:         }
                    292:     }
                    293:     my $cachetime = 12*3600;
                    294:     my $serverhomeID;
                    295:     if ($caller eq 'loncron') { 
                    296:         my @machine_ids = &machine_ids($hostname);
                    297:         foreach my $id (@machine_ids) {
                    298:             my $response = &reply('serverhomeID',$id);
                    299:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    300:                 $serverhomeID = $response;
                    301:                 last;
                    302:             }
                    303:         }
                    304:         if ($serverhomeID eq '') {
                    305:             $serverhomeID = $machine_ids[-1];
                    306:         }
                    307:     } else {
                    308:         $serverhomeID = $serverhomeIDs{$hostname};
                    309:     }
                    310:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    311: }
                    312: 
1.1121    raeburn   313: sub get_remote_globals {
                    314:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   315:     my ($result,%returnhash,%whatneeded);
                    316:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   317:         foreach my $what (sort(keys(%{$whathash}))) {
                    318:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   319:             my ($response,$cached);
1.1121    raeburn   320:             unless ($ignore_cache) {
1.1125    raeburn   321:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   322:             }
                    323:             if (defined($cached)) {
1.1125    raeburn   324:                 $returnhash{$what} = $response;
1.1121    raeburn   325:             } else {
1.1125    raeburn   326:                 $whatneeded{$what} = 1;
1.1121    raeburn   327:             }
                    328:         }
1.1125    raeburn   329:         if (keys(%whatneeded) == 0) {
                    330:             $result = 'ok';
                    331:         } else {
1.1121    raeburn   332:             my $requested = &freeze_escape(\%whatneeded);
                    333:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   334:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    335:                 ($rep eq 'unknown_cmd')) {
                    336:                 $result = $rep;
                    337:             } else {
                    338:                 $result = 'ok';
1.1121    raeburn   339:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   340:                 foreach my $item (@pairs) {
                    341:                     my ($key,$value)=split(/=/,$item,2);
                    342:                     my $what = &unescape($key);
                    343:                     my $hashid = $lonhost.'-'.$what;
                    344:                     $returnhash{$what}=&thaw_unescape($value);
                    345:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   346:                 }
                    347:             }
                    348:         }
                    349:     }
1.1125    raeburn   350:     return ($result,\%returnhash);
1.1121    raeburn   351: }
                    352: 
1.1124    raeburn   353: sub remote_devalidate_cache {
                    354:     my ($lonhost,$name,$id) = @_;
1.1130    raeburn   355:     my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
1.1124    raeburn   356:     return $response;
                    357: }
                    358: 
1.1       albertel  359: # -------------------------------------------------- Non-critical communication
                    360: sub subreply {
                    361:     my ($cmd,$server)=@_;
1.838     albertel  362:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      363:     #
                    364:     #  With loncnew process trimming, there's a timing hole between lonc server
                    365:     #  process exit and the master server picking up the listen on the AF_UNIX
                    366:     #  socket.  In that time interval, a lock file will exist:
                    367: 
                    368:     my $lockfile=$peerfile.".lock";
                    369:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    370: 	sleep(1);
                    371:     }
                    372:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      373:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      374:     #
1.550     foxr      375:     #   We'll give the connection a few tries before abandoning it.  If
                    376:     #   connection is not possible, we'll con_lost back to the client.
                    377:     #   
                    378:     my $client;
                    379:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    380: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    381: 				      Type    => SOCK_STREAM,
                    382: 				      Timeout => 10);
1.869     albertel  383: 	if ($client) {
1.550     foxr      384: 	    last;		# Connected!
1.850     albertel  385: 	} else {
1.853     albertel  386: 	    &create_connection(&hostname($server),$server);
1.550     foxr      387: 	}
1.850     albertel  388:         sleep(1);		# Try again later if failed connection.
1.550     foxr      389:     }
                    390:     my $answer;
                    391:     if ($client) {
1.704     albertel  392: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      393: 	$answer=<$client>;
                    394: 	if (!$answer) { $answer="con_lost"; }
                    395: 	chomp($answer);
                    396:     } else {
                    397: 	$answer = 'con_lost';	# Failed connection.
                    398:     }
1.1       albertel  399:     return $answer;
                    400: }
                    401: 
                    402: sub reply {
                    403:     my ($cmd,$server)=@_;
1.838     albertel  404:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  405:     my $answer=subreply($cmd,$server);
1.65      www       406:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  407:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       408:                 " $cmd to $server returned $answer</font>");
                    409:     }
1.1       albertel  410:     return $answer;
                    411: }
                    412: 
                    413: # ----------------------------------------------------------- Send USR1 to lonc
                    414: 
                    415: sub reconlonc {
1.891     albertel  416:     my ($lonid) = @_;
                    417:     my $hostname = &hostname($lonid);
                    418:     if ($lonid) {
                    419: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    420: 	if ($hostname && -e $peerfile) {
                    421: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    422: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    423: 					     Type    => SOCK_STREAM,
                    424: 					     Timeout => 10);
                    425: 	    if ($client) {
                    426: 		print $client ("reset_retries\n");
                    427: 		my $answer=<$client>;
                    428: 		#reset just this one.
                    429: 	    }
                    430: 	}
                    431: 	return;
                    432:     }
                    433: 
1.836     www       434:     &logthis("Trying to reconnect lonc");
1.1       albertel  435:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  436:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  437: 	my $loncpid=<$fh>;
                    438:         chomp($loncpid);
                    439:         if (kill 0 => $loncpid) {
                    440: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    441:             kill USR1 => $loncpid;
                    442:             sleep 1;
1.836     www       443:          } else {
1.12      www       444: 	    &logthis(
1.672     albertel  445:                "<font color=\"blue\">WARNING:".
1.12      www       446:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  447:         }
                    448:     } else {
1.836     www       449: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  450:     }
                    451: }
                    452: 
                    453: # ------------------------------------------------------ Critical communication
1.12      www       454: 
1.1       albertel  455: sub critical {
                    456:     my ($cmd,$server)=@_;
1.838     albertel  457:     unless (&hostname($server)) {
1.672     albertel  458:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       459:                " Critical message to unknown server ($server)</font>");
                    460:         return 'no_such_host';
                    461:     }
1.1       albertel  462:     my $answer=reply($cmd,$server);
                    463:     if ($answer eq 'con_lost') {
                    464: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  465: 	my $answer=reply($cmd,$server);
1.1       albertel  466:         if ($answer eq 'con_lost') {
                    467:             my $now=time;
                    468:             my $middlename=$cmd;
1.5       www       469:             $middlename=substr($middlename,0,16);
1.1       albertel  470:             $middlename=~s/\W//g;
                    471:             my $dfilename=
1.305     www       472:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    473:             $dumpcount++;
1.1       albertel  474:             {
1.448     albertel  475: 		my $dfh;
                    476: 		if (open($dfh,">$dfilename")) {
                    477: 		    print $dfh "$cmd\n"; 
                    478: 		    close($dfh);
                    479: 		}
1.1       albertel  480:             }
                    481:             sleep 2;
                    482:             my $wcmd='';
                    483:             {
1.448     albertel  484: 		my $dfh;
                    485: 		if (open($dfh,"<$dfilename")) {
                    486: 		    $wcmd=<$dfh>; 
                    487: 		    close($dfh);
                    488: 		}
1.1       albertel  489:             }
                    490:             chomp($wcmd);
1.7       www       491:             if ($wcmd eq $cmd) {
1.672     albertel  492: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       493:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  494:                 &logperm("D:$server:$cmd");
                    495: 	        return 'con_delayed';
                    496:             } else {
1.672     albertel  497:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       498:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  499:                 &logperm("F:$server:$cmd");
                    500:                 return 'con_failed';
                    501:             }
                    502:         }
                    503:     }
                    504:     return $answer;
1.405     albertel  505: }
                    506: 
1.755     albertel  507: # ------------------------------------------- check if return value is an error
                    508: 
                    509: sub error {
                    510:     my ($result) = @_;
1.756     albertel  511:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  512: 	if ($2 == 2) { return undef; }
                    513: 	return $1;
                    514:     }
                    515:     return undef;
                    516: }
                    517: 
1.783     albertel  518: sub convert_and_load_session_env {
                    519:     my ($lonidsdir,$handle)=@_;
                    520:     my @profile;
                    521:     {
1.917     albertel  522: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    523: 	if (!$opened) {
1.915     albertel  524: 	    return 0;
                    525: 	}
1.783     albertel  526: 	flock($idf,LOCK_SH);
                    527: 	@profile=<$idf>;
                    528: 	close($idf);
                    529:     }
                    530:     my %temp_env;
                    531:     foreach my $line (@profile) {
1.786     albertel  532: 	if ($line !~ m/=/) {
                    533: 	    return 0;
                    534: 	}
1.783     albertel  535: 	chomp($line);
                    536: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    537: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    538:     }
                    539:     unlink("$lonidsdir/$handle.id");
                    540:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    541: 	    0640)) {
                    542: 	%disk_env = %temp_env;
                    543: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    544: 	untie(%disk_env);
                    545:     }
1.786     albertel  546:     return 1;
1.783     albertel  547: }
                    548: 
1.374     www       549: # ------------------------------------------- Transfer profile into environment
1.780     albertel  550: my $env_loaded;
                    551: sub transfer_profile_to_env {
1.788     albertel  552:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    553:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       554: 
1.720     albertel  555:     if (!defined($lonidsdir)) {
                    556: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    557:     }
                    558:     if (!defined($handle)) {
                    559:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    560:     }
                    561: 
1.786     albertel  562:     my $convert;
                    563:     {
1.917     albertel  564:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    565: 	if (!$opened) {
1.915     albertel  566: 	    return;
                    567: 	}
1.786     albertel  568: 	flock($idf,LOCK_SH);
                    569: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    570: 		&GDBM_READER(),0640)) {
                    571: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    572: 	    untie(%disk_env);
                    573: 	} else {
                    574: 	    $convert = 1;
                    575: 	}
                    576:     }
                    577:     if ($convert) {
                    578: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    579: 	    &logthis("Failed to load session, or convert session.");
                    580: 	}
1.374     www       581:     }
1.783     albertel  582: 
1.786     albertel  583:     my %remove;
1.783     albertel  584:     while ( my $envname = each(%env) ) {
1.433     matthew   585:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    586:             if ($time < time-300) {
1.783     albertel  587:                 $remove{$key}++;
1.433     matthew   588:             }
                    589:         }
                    590:     }
1.783     albertel  591: 
1.619     albertel  592:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  593:     $env_loaded=1;
1.783     albertel  594:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   595:         &delenv($expired_key);
1.374     www       596:     }
1.1       albertel  597: }
                    598: 
1.916     albertel  599: # ---------------------------------------------------- Check for valid session 
                    600: sub check_for_valid_session {
1.1155    raeburn   601:     my ($r,$name) = @_;
1.916     albertel  602:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155    raeburn   603:     if ($name eq '') {
                    604:         $name = 'lonID';
                    605:     }
                    606:     my $lonid=$cookies{$name};
1.916     albertel  607:     return undef if (!$lonid);
                    608: 
                    609:     my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155    raeburn   610:     my $lonidsdir;
                    611:     if ($name eq 'lonDAV') {
                    612:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    613:     } else {
                    614:         $lonidsdir=$r->dir_config('lonIDsDir');
                    615:     }
1.916     albertel  616:     return undef if (!-e "$lonidsdir/$handle.id");
                    617: 
1.917     albertel  618:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    619:     return undef if (!$opened);
1.916     albertel  620: 
                    621:     flock($idf,LOCK_SH);
                    622:     my %disk_env;
                    623:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    624: 	    &GDBM_READER(),0640)) {
                    625: 	return undef;	
                    626:     }
                    627: 
                    628:     if (!defined($disk_env{'user.name'})
                    629: 	|| !defined($disk_env{'user.domain'})) {
                    630: 	return undef;
                    631:     }
                    632:     return $handle;
                    633: }
                    634: 
1.830     albertel  635: sub timed_flock {
                    636:     my ($file,$lock_type) = @_;
                    637:     my $failed=0;
                    638:     eval {
                    639: 	local $SIG{__DIE__}='DEFAULT';
                    640: 	local $SIG{ALRM}=sub {
                    641: 	    $failed=1;
                    642: 	    die("failed lock");
                    643: 	};
                    644: 	alarm(13);
                    645: 	flock($file,$lock_type);
                    646: 	alarm(0);
                    647:     };
                    648:     if ($failed) {
                    649: 	return undef;
                    650:     } else {
                    651: 	return 1;
                    652:     }
                    653: }
                    654: 
1.5       www       655: # ---------------------------------------------------------- Append Environment
                    656: 
                    657: sub appenv {
1.949     raeburn   658:     my ($newenv,$roles) = @_;
                    659:     if (ref($newenv) eq 'HASH') {
                    660:         foreach my $key (keys(%{$newenv})) {
                    661:             my $refused = 0;
                    662: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    663:                 $refused = 1;
                    664:                 if (ref($roles) eq 'ARRAY') {
                    665:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
                    666:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    667:                         $refused = 0;
                    668:                     }
                    669:                 }
                    670:             }
                    671:             if ($refused) {
                    672:                 &logthis("<font color=\"blue\">WARNING: ".
                    673:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    674:                          .'</font>');
                    675: 	        delete($newenv->{$key});
                    676:             } else {
                    677:                 $env{$key}=$newenv->{$key};
                    678:             }
                    679:         }
                    680:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    681:         if ($opened
                    682: 	    && &timed_flock($env_file,LOCK_EX)
                    683: 	    &&
                    684: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    685: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    686: 	    while (my ($key,$value) = each(%{$newenv})) {
                    687: 	        $disk_env{$key} = $value;
                    688: 	    }
                    689: 	    untie(%disk_env);
1.35      www       690:         }
1.191     harris41  691:     }
1.56      www       692:     return 'ok';
                    693: }
                    694: # ----------------------------------------------------- Delete from Environment
                    695: 
                    696: sub delenv {
1.1104    raeburn   697:     my ($delthis,$regexp,$roles) = @_;
                    698:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    699:         my $refused = 1;
                    700:         if (ref($roles) eq 'ARRAY') {
                    701:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    702:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    703:                 $refused = 0;
                    704:             }
                    705:         }
                    706:         if ($refused) {
                    707:             &logthis("<font color=\"blue\">WARNING: ".
                    708:                      "Attempt to delete from environment ".$delthis);
                    709:             return 'error';
                    710:         }
1.56      www       711:     }
1.917     albertel  712:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    713:     if ($opened
1.915     albertel  714: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  715: 	&&
                    716: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    717: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  718: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   719: 	    if ($regexp) {
                    720:                 if ($key=~/^$delthis/) {
                    721:                     delete($env{$key});
                    722:                     delete($disk_env{$key});
                    723:                 } 
                    724:             } else {
                    725:                 if ($key=~/^\Q$delthis\E/) {
                    726: 		    delete($env{$key});
                    727: 		    delete($disk_env{$key});
                    728: 	        }
                    729:             }
1.448     albertel  730: 	}
1.783     albertel  731: 	untie(%disk_env);
1.5       www       732:     }
                    733:     return 'ok';
1.369     albertel  734: }
                    735: 
1.790     albertel  736: sub get_env_multiple {
                    737:     my ($name) = @_;
                    738:     my @values;
                    739:     if (defined($env{$name})) {
                    740:         # exists is it an array
                    741:         if (ref($env{$name})) {
                    742:             @values=@{ $env{$name} };
                    743:         } else {
                    744:             $values[0]=$env{$name};
                    745:         }
                    746:     }
                    747:     return(@values);
                    748: }
                    749: 
1.958     www       750: # ------------------------------------------------------------------- Locking
                    751: 
                    752: sub set_lock {
                    753:     my ($text)=@_;
                    754:     $locknum++;
                    755:     my $id=$$.'-'.$locknum;
                    756:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    757:              'session.lock.'.$id => $text});
                    758:     return $id;
                    759: }
                    760: 
                    761: sub get_locks {
                    762:     my $num=0;
                    763:     my %texts=();
                    764:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    765:        if ($lock=~/\w/) {
                    766:           $num++;
                    767:           $texts{$lock}=$env{'session.lock.'.$lock};
                    768:        }
                    769:    }
                    770:    return ($num,%texts);
                    771: }
                    772: 
                    773: sub remove_lock {
                    774:     my ($id)=@_;
                    775:     my $newlocks='';
                    776:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    777:        if (($lock=~/\w/) && ($lock ne $id)) {
                    778:           $newlocks.=','.$lock;
                    779:        }
                    780:     }
                    781:     &appenv({'session.locks' => $newlocks});
                    782:     &delenv('session.lock.'.$id);
                    783: }
                    784: 
                    785: sub remove_all_locks {
                    786:     my $activelocks=$env{'session.locks'};
                    787:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    788:        if ($lock=~/\w/) {
                    789:           &remove_lock($lock);
                    790:        }
                    791:     }
                    792: }
                    793: 
                    794: 
1.369     albertel  795: # ------------------------------------------ Find out current server userload
                    796: sub userload {
                    797:     my $numusers=0;
                    798:     {
                    799: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    800: 	my $filename;
                    801: 	my $curtime=time;
                    802: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  803: 	    next if ($filename eq '.' || $filename eq '..');
                    804: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  805: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  806: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  807: 	}
                    808: 	closedir(LONIDS);
                    809:     }
                    810:     my $userloadpercent=0;
                    811:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    812:     if ($maxuserload) {
1.371     albertel  813: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  814:     }
1.372     albertel  815:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  816:     return $userloadpercent;
1.283     www       817: }
                    818: 
1.1       albertel  819: # ------------------------------ Find server with least workload from spare.tab
1.11      www       820: 
1.1       albertel  821: sub spareserver {
1.1083    raeburn   822:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  823:     my $spare_server;
1.370     albertel  824:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  825:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    826:                                                      :  $userloadpercent;
1.1083    raeburn   827:     my ($uint_dom,$remotesessions);
                    828:     if (($udom ne '') && (&domain($udom) ne '')) {
                    829:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    830:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    831:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    832:         $remotesessions = $udomdefaults{'remotesessions'};
                    833:     }
1.1123    raeburn   834:     my $spareshash = &this_host_spares($udom);
                    835:     if (ref($spareshash) eq 'HASH') {
                    836:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    837:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    838:                 if ($uint_dom) {
                    839:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    840:                                                  $try_server));
                    841:                 }
                    842: 	        ($spare_server, $lowest_load) =
                    843: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    844:             }
1.1083    raeburn   845:         }
1.784     albertel  846: 
1.1123    raeburn   847:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    848: 
                    849:         if (!$found_server) {
                    850:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    851: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
                    852:                     if ($uint_dom) {
                    853:                         next unless (&spare_can_host($udom,$uint_dom,
                    854:                                                      $remotesessions,$try_server));
                    855:                     }
                    856: 	            ($spare_server, $lowest_load) =
                    857: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    858:                 }
                    859: 	    }
                    860:         }
1.784     albertel  861:     }
                    862: 
                    863:     if (!$want_server_name) {
1.968     raeburn   864:         my $protocol = 'http';
                    865:         if ($protocol{$spare_server} eq 'https') {
                    866:             $protocol = $protocol{$spare_server};
                    867:         }
1.1001    raeburn   868:         if (defined($spare_server)) {
                    869:             my $hostname = &hostname($spare_server);
1.1083    raeburn   870:             if (defined($hostname)) {
1.1001    raeburn   871: 	        $spare_server = $protocol.'://'.$hostname;
                    872:             }
                    873:         }
1.784     albertel  874:     }
                    875:     return $spare_server;
                    876: }
                    877: 
                    878: sub compare_server_load {
                    879:     my ($try_server, $spare_server, $lowest_load) = @_;
                    880: 
                    881:     my $loadans     = &reply('load',    $try_server);
                    882:     my $userloadans = &reply('userload',$try_server);
                    883: 
                    884:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   885: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  886:     }
                    887: 
                    888:     my $load;
                    889:     if ($loadans =~ /\d/) {
                    890: 	if ($userloadans =~ /\d/) {
                    891: 	    #both are numbers, pick the bigger one
                    892: 	    $load = ($loadans > $userloadans) ? $loadans 
                    893: 		                              : $userloadans;
1.411     albertel  894: 	} else {
1.784     albertel  895: 	    $load = $loadans;
1.411     albertel  896: 	}
1.784     albertel  897:     } else {
                    898: 	$load = $userloadans;
                    899:     }
                    900: 
                    901:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    902: 	$spare_server = $try_server;
                    903: 	$lowest_load  = $load;
1.370     albertel  904:     }
1.784     albertel  905:     return ($spare_server,$lowest_load);
1.202     matthew   906: }
1.914     albertel  907: 
                    908: # --------------------------- ask offload servers if user already has a session
                    909: sub find_existing_session {
                    910:     my ($udom,$uname) = @_;
1.1123    raeburn   911:     my $spareshash = &this_host_spares($udom);
                    912:     if (ref($spareshash) eq 'HASH') {
                    913:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    914:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    915:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    916:             }
                    917:         }
                    918:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                    919:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                    920:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    921:             }
                    922:         }
1.914     albertel  923:     }
                    924:     return;
                    925: }
                    926: 
                    927: # -------------------------------- ask if server already has a session for user
                    928: sub has_user_session {
                    929:     my ($lonid,$udom,$uname) = @_;
                    930:     my $result = &reply(join(':','userhassession',
                    931: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    932:     return 1 if ($result eq 'ok');
                    933: 
                    934:     return 0;
                    935: }
                    936: 
1.1076    raeburn   937: # --------- determine least loaded server in a user's domain which allows login
                    938: 
                    939: sub choose_server {
1.1115    raeburn   940:     my ($udom,$checkloginvia) = @_;
1.1076    raeburn   941:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn   942:     my %servers = &get_servers($udom);
1.1076    raeburn   943:     my $lowest_load = 30000;
1.1151    raeburn   944:     my ($login_host,$hostname,$portal_path,$isredirect);
1.1076    raeburn   945:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn   946:         my $loginvia;
                    947:         if ($checkloginvia) {
                    948:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn   949:             if ($loginvia) {
                    950:                 my ($server,$path) = split(/:/,$loginvia);
                    951:                 ($login_host, $lowest_load) =
                    952:                     &compare_server_load($server, $login_host, $lowest_load);
                    953:                 if ($login_host eq $server) {
                    954:                     $portal_path = $path;
1.1151    raeburn   955:                     $isredirect = 1;
1.1116    raeburn   956:                 }
                    957:             } else {
                    958:                 ($login_host, $lowest_load) =
                    959:                     &compare_server_load($lonhost, $login_host, $lowest_load);
                    960:                 if ($login_host eq $lonhost) {
                    961:                     $portal_path = '';
1.1151    raeburn   962:                     $isredirect = ''; 
1.1116    raeburn   963:                 }
                    964:             }
                    965:         } else {
1.1076    raeburn   966:             ($login_host, $lowest_load) =
1.1116    raeburn   967:                 &compare_server_load($lonhost, $login_host, $lowest_load);
1.1076    raeburn   968:         }
                    969:     }
                    970:     if ($login_host ne '') {
1.1116    raeburn   971:         $hostname = &hostname($login_host);
1.1076    raeburn   972:     }
1.1151    raeburn   973:     return ($login_host,$hostname,$portal_path,$isredirect);
1.1076    raeburn   974: }
                    975: 
1.202     matthew   976: # --------------------------------------------- Try to change a user's password
                    977: 
                    978: sub changepass {
1.799     raeburn   979:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   980:     $currentpass = &escape($currentpass);
                    981:     $newpass     = &escape($newpass);
1.1030    raeburn   982:     my $lonhost = $perlvar{'lonHostID'};
                    983:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew   984: 		       $server);
                    985:     if (! $answer) {
                    986: 	&logthis("No reply on password change request to $server ".
                    987: 		 "by $uname in domain $udom.");
                    988:     } elsif ($answer =~ "^ok") {
                    989:         &logthis("$uname in $udom successfully changed their password ".
                    990: 		 "on $server.");
                    991:     } elsif ($answer =~ "^pwchange_failure") {
                    992: 	&logthis("$uname in $udom was unable to change their password ".
                    993: 		 "on $server.  The action was blocked by either lcpasswd ".
                    994: 		 "or pwchange");
                    995:     } elsif ($answer =~ "^non_authorized") {
                    996:         &logthis("$uname in $udom did not get their password correct when ".
                    997: 		 "attempting to change it on $server.");
                    998:     } elsif ($answer =~ "^auth_mode_error") {
                    999:         &logthis("$uname in $udom attempted to change their password despite ".
                   1000: 		 "not being locally or internally authenticated on $server.");
                   1001:     } elsif ($answer =~ "^unknown_user") {
                   1002:         &logthis("$uname in $udom attempted to change their password ".
                   1003: 		 "on $server but were unable to because $server is not ".
                   1004: 		 "their home server.");
                   1005:     } elsif ($answer =~ "^refused") {
                   1006: 	&logthis("$server refused to change $uname in $udom password because ".
                   1007: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1008:     } elsif ($answer =~ "invalid_client") {
                   1009:         &logthis("$server refused to change $uname in $udom password because ".
                   1010:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1011:     }
                   1012:     return $answer;
1.1       albertel 1013: }
                   1014: 
1.169     harris41 1015: # ----------------------- Try to determine user's current authentication scheme
                   1016: 
                   1017: sub queryauthenticate {
                   1018:     my ($uname,$udom)=@_;
1.456     albertel 1019:     my $uhome=&homeserver($uname,$udom);
                   1020:     if (!$uhome) {
                   1021: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1022: 	return 'no_host';
                   1023:     }
                   1024:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1025:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1026: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1027:     }
1.456     albertel 1028:     return $answer;
1.169     harris41 1029: }
                   1030: 
1.1       albertel 1031: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1032: 
1.1       albertel 1033: sub authenticate {
1.1073    raeburn  1034:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1035:     $upass=&escape($upass);
                   1036:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1037:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1038:     my $newhome;
1.836     www      1039:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1040: # Maybe the machine was offline and only re-appeared again recently?
                   1041:         &reconlonc();
                   1042: # One more
1.952     raeburn  1043: 	$uhome=&homeserver($uname,$udom,1);
                   1044:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1045:             if (defined(&domain($udom,'primary'))) {
                   1046:                 $newhome=&domain($udom,'primary');
                   1047:             }
                   1048:             if ($newhome ne '') {
                   1049:                 $uhome = $newhome;
                   1050:             }
                   1051:         }
1.836     www      1052: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1053: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1054: 	    return 'no_host';
                   1055:         }
1.1       albertel 1056:     }
1.1073    raeburn  1057:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1058:     if ($answer eq 'authorized') {
1.952     raeburn  1059:         if ($newhome) {
                   1060:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1061:             return 'no_account_on_host'; 
                   1062:         } else {
                   1063:             &logthis("User $uname at $udom authorized by $uhome");
                   1064:             return $uhome;
                   1065:         }
1.471     albertel 1066:     }
                   1067:     if ($answer eq 'non_authorized') {
                   1068: 	&logthis("User $uname at $udom rejected by $uhome");
                   1069: 	return 'no_host'; 
1.9       www      1070:     }
1.471     albertel 1071:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1072:     return 'no_host';
                   1073: }
                   1074: 
1.1073    raeburn  1075: sub can_host_session {
1.1074    raeburn  1076:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1077:     my $canhost = 1;
1.1074    raeburn  1078:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1079:     if (ref($remotesessions) eq 'HASH') {
                   1080:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1081:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1082:                 $canhost = 0;
                   1083:             } else {
                   1084:                 $canhost = 1;
                   1085:             }
                   1086:         }
                   1087:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1088:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1089:                 $canhost = 1;
                   1090:             } else {
                   1091:                 $canhost = 0;
                   1092:             }
                   1093:         }
                   1094:         if ($canhost) {
                   1095:             if ($remotesessions->{'version'} ne '') {
                   1096:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1097:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1098:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1099:                         my $major = $1;
                   1100:                         my $minor = $2;
                   1101:                         if (($major < $reqmajor ) ||
                   1102:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1103:                             $canhost = 0;
                   1104:                         }
                   1105:                     } else {
                   1106:                         $canhost = 0;
                   1107:                     }
                   1108:                 }
                   1109:             }
                   1110:         }
                   1111:     }
                   1112:     if ($canhost) {
                   1113:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1114:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1115:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1116:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1117:                 if (($uint_dom ne '') && 
                   1118:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1119:                     $canhost = 0;
                   1120:                 } else {
                   1121:                     $canhost = 1;
                   1122:                 }
                   1123:             }
                   1124:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1125:                 if (($uint_dom ne '') && 
                   1126:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1127:                     $canhost = 1;
                   1128:                 } else {
                   1129:                     $canhost = 0;
                   1130:                 }
                   1131:             }
                   1132:         }
                   1133:     }
                   1134:     return $canhost;
                   1135: }
                   1136: 
1.1083    raeburn  1137: sub spare_can_host {
                   1138:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1139:     my $canhost=1;
                   1140:     my @intdoms;
                   1141:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
                   1142:     if (ref($internet_names) eq 'ARRAY') {
                   1143:         @intdoms = @{$internet_names};
                   1144:     }
                   1145:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1146:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
                   1147:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   1148:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   1149:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
                   1150:         $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1151:                                      $remotesessions,
                   1152:                                      $defdomdefaults{'hostedsessions'});
                   1153:     }
                   1154:     return $canhost;
                   1155: }
                   1156: 
1.1123    raeburn  1157: sub this_host_spares {
                   1158:     my ($dom) = @_;
1.1126    raeburn  1159:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1160:     my @hosts = &current_machine_ids();
                   1161:     foreach my $lonhost (@hosts) {
                   1162:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1163:             $dom_in_use = $dom;
                   1164:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1165:             last;
                   1166:         }
                   1167:     }
1.1126    raeburn  1168:     if ($dom_in_use ne '') {
                   1169:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1170:     }
                   1171:     if (ref($result) ne 'HASH') {
                   1172:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1173:         $dom_in_use = &host_domain($lonhost_in_use);
                   1174:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1175:         if (ref($result) ne 'HASH') {
                   1176:             $result = \%spareid;
                   1177:         }
                   1178:     }
                   1179:     return $result;
                   1180: }
                   1181: 
                   1182: sub spares_for_offload  {
                   1183:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1184:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1185:     if (defined($cached)) {
                   1186:         return $result;
                   1187:     } else {
1.1126    raeburn  1188:         my $cachetime = 60*60*24;
                   1189:         my %domconfig =
                   1190:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1191:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1192:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1193:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1194:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1195:                 }
                   1196:             }
                   1197:         }
                   1198:     }
1.1126    raeburn  1199:     return;
1.1123    raeburn  1200: }
                   1201: 
1.1129    raeburn  1202: sub get_lonbalancer_config {
                   1203:     my ($servers) = @_;
                   1204:     my ($currbalancer,$currtargets);
                   1205:     if (ref($servers) eq 'HASH') {
                   1206:         foreach my $server (keys(%{$servers})) {
                   1207:             my %what = (
                   1208:                          spareid => 1,
                   1209:                          perlvar => 1,
                   1210:                        );
                   1211:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1212:             if ($result eq 'ok') {
                   1213:                 if (ref($returnhash) eq 'HASH') {
                   1214:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1215:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1216:                             $currbalancer = $server;
                   1217:                             $currtargets = {};
                   1218:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1219:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1220:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1221:                                 }
                   1222:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1223:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1224:                                 }
                   1225:                             }
                   1226:                             last;
                   1227:                         }
                   1228:                     }
                   1229:                 }
                   1230:             }
                   1231:         }
                   1232:     }
                   1233:     return ($currbalancer,$currtargets);
                   1234: }
                   1235: 
                   1236: sub check_loadbalancing {
                   1237:     my ($uname,$udom) = @_;
1.1172.2.12  raeburn  1238:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
                   1239:         $rule_in_effect,$offloadto,$otherserver);
1.1129    raeburn  1240:     my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4  raeburn  1241:     my @hosts = &current_machine_ids();
1.1129    raeburn  1242:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1243:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1244:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1245:     my $serverhomedom = &host_domain($lonhost);
                   1246: 
                   1247:     my $cachetime = 60*60*24;
                   1248: 
                   1249:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1250:         $dom_in_use = $udom;
                   1251:         $homeintdom = 1;
                   1252:     } else {
                   1253:         $dom_in_use = $serverhomedom;
                   1254:     }
                   1255:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1256:     unless (defined($cached)) {
                   1257:         my %domconfig =
                   1258:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1259:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1260:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1261:         }
                   1262:     }
                   1263:     if (ref($result) eq 'HASH') {
1.1172.2.12  raeburn  1264:         ($is_balancer,$currtargets,$currrules) =
                   1265:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1266:         if ($is_balancer) {
                   1267:             if (ref($currrules) eq 'HASH') {
                   1268:                 if ($homeintdom) {
                   1269:                     if ($uname ne '') {
                   1270:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1271:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1272:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1273:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1274:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1275:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1276:                             }
                   1277:                         }
                   1278:                         if ($rule_in_effect eq '') {
                   1279:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1280:                             if ($userenv{'inststatus'} ne '') {
                   1281:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1282:                                 my ($othertitle,$usertypes,$types) =
                   1283:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1284:                                 if (ref($types) eq 'ARRAY') {
                   1285:                                     foreach my $type (@{$types}) {
                   1286:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1287:                                             if (exists($currrules->{$type})) {
                   1288:                                                 $rule_in_effect = $currrules->{$type};
                   1289:                                             }
                   1290:                                         }
                   1291:                                     }
                   1292:                                 }
                   1293:                             } else {
                   1294:                                 if (exists($currrules->{'default'})) {
                   1295:                                     $rule_in_effect = $currrules->{'default'};
                   1296:                                 }
                   1297:                             }
                   1298:                         }
                   1299:                     } else {
                   1300:                         if (exists($currrules->{'default'})) {
                   1301:                             $rule_in_effect = $currrules->{'default'};
                   1302:                         }
                   1303:                     }
                   1304:                 } else {
                   1305:                     if ($currrules->{'_LC_external'} ne '') {
                   1306:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1307:                     }
                   1308:                 }
                   1309:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1310:                                                        $uname,$udom);
                   1311:             }
                   1312:         }
                   1313:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
                   1314:         my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
                   1315:         unless (defined($cached)) {
                   1316:             my %domconfig =
                   1317:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1318:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1319:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1320:             }
                   1321:         }
                   1322:         if (ref($result) eq 'HASH') {
1.1172.2.12  raeburn  1323:             ($is_balancer,$currtargets,$currrules) =
                   1324:                 &check_balancer_result($result,@hosts);
                   1325:             if ($is_balancer) {
1.1129    raeburn  1326:                 if (ref($currrules) eq 'HASH') {
                   1327:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1328:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1329:                     }
                   1330:                 }
                   1331:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1332:                                                        $uname,$udom);
                   1333:             }
                   1334:         } else {
                   1335:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1336:                 $is_balancer = 1;
                   1337:                 $offloadto = &this_host_spares($dom_in_use);
                   1338:             }
                   1339:         }
                   1340:     } else {
                   1341:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1342:             $is_balancer = 1;
                   1343:             $offloadto = &this_host_spares($dom_in_use);
                   1344:         }
                   1345:     }
1.1172.2.5  raeburn  1346:     if ($is_balancer) {
                   1347:         my $lowest_load = 30000;
                   1348:         if (ref($offloadto) eq 'HASH') {
                   1349:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1350:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1351:                     ($otherserver,$lowest_load) =
                   1352:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1353:                 }
1.1129    raeburn  1354:             }
1.1172.2.5  raeburn  1355:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1356: 
1.1172.2.5  raeburn  1357:             if (!$found_server) {
                   1358:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1359:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1360:                         ($otherserver,$lowest_load) =
                   1361:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1362:                     }
                   1363:                 }
                   1364:             }
                   1365:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1366:             if (@{$offloadto} == 1) {
                   1367:                 $otherserver = $offloadto->[0];
                   1368:             } elsif (@{$offloadto} > 1) {
                   1369:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1370:                     ($otherserver,$lowest_load) =
                   1371:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1372:                 }
                   1373:             }
                   1374:         }
1.1172.2.5  raeburn  1375:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1376:             $is_balancer = 0;
                   1377:             if ($uname ne '' && $udom ne '') {
                   1378:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1379: 
                   1380:                     &appenv({'user.loadbalexempt'     => $lonhost,
                   1381:                              'user.loadbalcheck.time' => time});
                   1382:                 }
1.1129    raeburn  1383:             }
                   1384:         }
                   1385:     }
                   1386:     return ($is_balancer,$otherserver);
                   1387: }
                   1388: 
1.1172.2.12  raeburn  1389: sub check_balancer_result {
                   1390:     my ($result,@hosts) = @_;
                   1391:     my ($is_balancer,$currtargets,$currrules);
                   1392:     if (ref($result) eq 'HASH') {
                   1393:         if ($result->{'lonhost'} ne '') {
                   1394:             my $currbalancer = $result->{'lonhost'};
                   1395:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1396:                 $is_balancer = 1;
                   1397:                 $currtargets = $result->{'targets'};
                   1398:                 $currrules = $result->{'rules'};
                   1399:             }
                   1400:         } else {
                   1401:             foreach my $key (keys(%{$result})) {
                   1402:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1403:                     (ref($result->{$key}) eq 'HASH')) {
                   1404:                     $is_balancer = 1;
                   1405:                     $currrules = $result->{$key}{'rules'};
                   1406:                     $currtargets = $result->{$key}{'targets'};
                   1407:                     last;
                   1408:                 }
                   1409:             }
                   1410:         }
                   1411:     }
                   1412:     return ($is_balancer,$currtargets,$currrules);
                   1413: }
                   1414: 
1.1129    raeburn  1415: sub get_loadbalancer_targets {
                   1416:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1417:     my $offloadto;
1.1172.2.4  raeburn  1418:     if ($rule_in_effect eq 'none') {
                   1419:         return [$perlvar{'lonHostID'}];
                   1420:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1421:         $offloadto = $currtargets;
                   1422:     } else {
                   1423:         if ($rule_in_effect eq 'homeserver') {
                   1424:             my $homeserver = &homeserver($uname,$udom);
                   1425:             if ($homeserver ne 'no_host') {
                   1426:                 $offloadto = [$homeserver];
                   1427:             }
                   1428:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1429:             my %domconfig =
                   1430:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1431:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1432:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1433:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1434:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1435:                     }
                   1436:                 }
                   1437:             } else {
1.1172.2.7  raeburn  1438:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1439:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1440:                 if (&hostname($remotebalancer) ne '') {
                   1441:                     $offloadto = [$remotebalancer];
                   1442:                 }
                   1443:             }
                   1444:         } elsif (&hostname($rule_in_effect) ne '') {
                   1445:             $offloadto = [$rule_in_effect];
                   1446:         }
                   1447:     }
                   1448:     return $offloadto;
                   1449: }
                   1450: 
1.1127    raeburn  1451: sub internet_dom_servers {
                   1452:     my ($dom) = @_;
                   1453:     my (%uniqservers,%servers);
                   1454:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1455:     my @machinedoms = &machine_domains($primaryserver);
                   1456:     foreach my $mdom (@machinedoms) {
                   1457:         my %currservers = %servers;
                   1458:         my %server = &get_servers($mdom);
                   1459:         %servers = (%currservers,%server);
                   1460:     }
                   1461:     my %by_hostname;
                   1462:     foreach my $id (keys(%servers)) {
                   1463:         push(@{$by_hostname{$servers{$id}}},$id);
                   1464:     }
                   1465:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1466:         if (@{$by_hostname{$hostname}} > 1) {
                   1467:             my $match = 0;
                   1468:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1469:                 if (&host_domain($id) eq $dom) {
                   1470:                     $uniqservers{$id} = $hostname;
                   1471:                     $match = 1;
                   1472:                 }
                   1473:             }
                   1474:             unless ($match) {
                   1475:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1476:             }
                   1477:         } else {
                   1478:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1479:         }
                   1480:     }
                   1481:     return %uniqservers;
                   1482: }
                   1483: 
1.1       albertel 1484: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1485: 
1.599     albertel 1486: my %homecache;
1.1       albertel 1487: sub homeserver {
1.230     stredwic 1488:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1489:     my $index="$uname:$udom";
1.426     albertel 1490: 
1.599     albertel 1491:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1492: 
                   1493:     my %servers = &get_servers($udom,'library');
                   1494:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1495:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1496: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1497: 
                   1498: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1499: 	if ($answer eq 'found') {
                   1500: 	    delete($badServerCache{$tryserver}); 
                   1501: 	    return $homecache{$index}=$tryserver;
                   1502: 	} elsif ($answer eq 'no_host') {
                   1503: 	    $badServerCache{$tryserver}=1;
                   1504: 	}
1.1       albertel 1505:     }    
                   1506:     return 'no_host';
1.70      www      1507: }
                   1508: 
                   1509: # ------------------------------------- Find the usernames behind a list of IDs
                   1510: 
                   1511: sub idget {
                   1512:     my ($udom,@ids)=@_;
                   1513:     my %returnhash=();
                   1514:     
1.841     albertel 1515:     my %servers = &get_servers($udom,'library');
                   1516:     foreach my $tryserver (keys(%servers)) {
                   1517: 	my $idlist=join('&',@ids);
                   1518: 	$idlist=~tr/A-Z/a-z/; 
                   1519: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1520: 	my @answer=();
                   1521: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1522: 	    @answer=split(/\&/,$reply);
                   1523: 	}                    ;
                   1524: 	my $i;
                   1525: 	for ($i=0;$i<=$#ids;$i++) {
                   1526: 	    if ($answer[$i]) {
                   1527: 		$returnhash{$ids[$i]}=$answer[$i];
                   1528: 	    } 
                   1529: 	}
                   1530:     } 
1.70      www      1531:     return %returnhash;
                   1532: }
                   1533: 
                   1534: # ------------------------------------- Find the IDs behind a list of usernames
                   1535: 
                   1536: sub idrget {
                   1537:     my ($udom,@unames)=@_;
                   1538:     my %returnhash=();
1.800     albertel 1539:     foreach my $uname (@unames) {
                   1540:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1541:     }
1.70      www      1542:     return %returnhash;
                   1543: }
                   1544: 
                   1545: # ------------------------------- Store away a list of names and associated IDs
                   1546: 
                   1547: sub idput {
                   1548:     my ($udom,%ids)=@_;
                   1549:     my %servers=();
1.800     albertel 1550:     foreach my $uname (keys(%ids)) {
                   1551: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1552:         my $uhom=&homeserver($uname,$udom);
1.70      www      1553:         if ($uhom ne 'no_host') {
1.800     albertel 1554:             my $id=&escape($ids{$uname});
1.70      www      1555:             $id=~tr/A-Z/a-z/;
1.800     albertel 1556:             my $esc_unam=&escape($uname);
1.70      www      1557: 	    if ($servers{$uhom}) {
1.800     albertel 1558: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1559:             } else {
1.800     albertel 1560:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1561:             }
                   1562:         }
1.191     harris41 1563:     }
1.800     albertel 1564:     foreach my $server (keys(%servers)) {
                   1565:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1566:     }
1.344     www      1567: }
                   1568: 
1.1023    raeburn  1569: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1570: sub dump_dom {
1.1165    droeschl 1571:     my ($namespace, $udom, $regexp) = @_;
                   1572: 
                   1573:     $udom ||= $env{'user.domain'};
                   1574: 
                   1575:     return () unless $udom;
                   1576: 
                   1577:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1578: }
                   1579: 
1.1023    raeburn  1580: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1581: 
                   1582: sub get_dom {
1.860     raeburn  1583:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn  1584:     my $items='';
                   1585:     foreach my $item (@$storearr) {
                   1586:         $items.=&escape($item).'&';
                   1587:     }
                   1588:     $items=~s/\&$//;
1.860     raeburn  1589:     if (!$udom) {
                   1590:         $udom=$env{'user.domain'};
                   1591:         if (defined(&domain($udom,'primary'))) {
                   1592:             $uhome=&domain($udom,'primary');
                   1593:         } else {
1.874     albertel 1594:             undef($uhome);
1.860     raeburn  1595:         }
                   1596:     } else {
                   1597:         if (!$uhome) {
                   1598:             if (defined(&domain($udom,'primary'))) {
                   1599:                 $uhome=&domain($udom,'primary');
                   1600:             }
                   1601:         }
                   1602:     }
                   1603:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1604:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1605:         my %returnhash;
1.875     albertel 1606:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1607:             return %returnhash;
                   1608:         }
1.806     raeburn  1609:         my @pairs=split(/\&/,$rep);
                   1610:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1611:             return @pairs;
                   1612:         }
                   1613:         my $i=0;
                   1614:         foreach my $item (@$storearr) {
                   1615:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1616:             $i++;
                   1617:         }
                   1618:         return %returnhash;
                   1619:     } else {
1.880     banghart 1620:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1621:     }
                   1622: }
                   1623: 
                   1624: # -------------------------------------------- put items in domain db files 
                   1625: 
                   1626: sub put_dom {
1.860     raeburn  1627:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1628:     if (!$udom) {
                   1629:         $udom=$env{'user.domain'};
                   1630:         if (defined(&domain($udom,'primary'))) {
                   1631:             $uhome=&domain($udom,'primary');
                   1632:         } else {
1.874     albertel 1633:             undef($uhome);
1.860     raeburn  1634:         }
                   1635:     } else {
                   1636:         if (!$uhome) {
                   1637:             if (defined(&domain($udom,'primary'))) {
                   1638:                 $uhome=&domain($udom,'primary');
                   1639:             }
                   1640:         }
                   1641:     } 
                   1642:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1643:         my $items='';
                   1644:         foreach my $item (keys(%$storehash)) {
                   1645:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1646:         }
                   1647:         $items=~s/\&$//;
                   1648:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1649:     } else {
1.860     raeburn  1650:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1651:     }
                   1652: }
                   1653: 
1.1023    raeburn  1654: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1655: sub newput_dom {
1.1023    raeburn  1656:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1657:     my $result;
                   1658:     if (!$udom) {
                   1659:         $udom=$env{'user.domain'};
                   1660:     }
1.1023    raeburn  1661:     if ($udom) {
                   1662:         my $uname = &get_domainconfiguser($udom);
                   1663:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1664:     }
                   1665:     return $result;
                   1666: }
                   1667: 
1.1023    raeburn  1668: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1669: sub del_dom {
1.1023    raeburn  1670:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1671:     if (ref($storearr) eq 'ARRAY') {
                   1672:         if (!$udom) {
                   1673:             $udom=$env{'user.domain'};
                   1674:         }
1.1023    raeburn  1675:         if ($udom) {
                   1676:             my $uname = &get_domainconfiguser($udom); 
                   1677:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1678:         }
                   1679:     }
                   1680: }
                   1681: 
1.1023    raeburn  1682: # ----------------------------------construct domainconfig user for a domain 
                   1683: sub get_domainconfiguser {
                   1684:     my ($udom) = @_;
                   1685:     return $udom.'-domainconfig';
                   1686: }
                   1687: 
1.837     raeburn  1688: sub retrieve_inst_usertypes {
                   1689:     my ($udom) = @_;
                   1690:     my (%returnhash,@order);
1.989     raeburn  1691:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1692:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1693:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
                   1694:         %returnhash = %{$domdefs{'inststatustypes'}};
                   1695:         @order = @{$domdefs{'inststatusorder'}};
                   1696:     } else {
                   1697:         if (defined(&domain($udom,'primary'))) {
                   1698:             my $uhome=&domain($udom,'primary');
                   1699:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1700:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1701:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1702:                 return (\%returnhash,\@order);
                   1703:             }
                   1704:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1705:             my @pairs=split(/\&/,$hashitems);
                   1706:             foreach my $item (@pairs) {
                   1707:                 my ($key,$value)=split(/=/,$item,2);
                   1708:                 $key = &unescape($key);
                   1709:                 next if ($key =~ /^error: 2 /);
                   1710:                 $returnhash{$key}=&thaw_unescape($value);
                   1711:             }
                   1712:             my @esc_order = split(/\&/,$orderitems);
                   1713:             foreach my $item (@esc_order) {
                   1714:                 push(@order,&unescape($item));
                   1715:             }
                   1716:         } else {
                   1717:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1718:         }
                   1719:     }
                   1720:     return (\%returnhash,\@order);
                   1721: }
                   1722: 
1.868     raeburn  1723: sub is_domainimage {
                   1724:     my ($url) = @_;
                   1725:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1726:         if (&domain($1) ne '') {
                   1727:             return '1';
                   1728:         }
                   1729:     }
                   1730:     return;
                   1731: }
                   1732: 
1.899     raeburn  1733: sub inst_directory_query {
                   1734:     my ($srch) = @_;
                   1735:     my $udom = $srch->{'srchdomain'};
                   1736:     my %results;
                   1737:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1738:     my $outcome;
1.899     raeburn  1739:     if ($homeserver ne '') {
1.904     albertel 1740: 	my $queryid=&reply("querysend:instdirsearch:".
                   1741: 			   &escape($srch->{'srchby'}).':'.
                   1742: 			   &escape($srch->{'srchterm'}).':'.
                   1743: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1744: 	my $host=&hostname($homeserver);
                   1745: 	if ($queryid !~/^\Q$host\E\_/) {
                   1746: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1747: 	    return;
                   1748: 	}
                   1749: 	my $response = &get_query_reply($queryid);
                   1750: 	my $maxtries = 5;
                   1751: 	my $tries = 1;
                   1752: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1753: 	    $response = &get_query_reply($queryid);
                   1754: 	    $tries ++;
                   1755: 	}
                   1756: 
                   1757:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1758:             if ($response eq 'unavailable') {
                   1759:                 $outcome = $response;
                   1760:             } else {
                   1761:                 $outcome = 'ok';
                   1762:                 my @matches = split(/\n/,$response);
                   1763:                 foreach my $match (@matches) {
                   1764:                     my ($key,$value) = split(/=/,$match);
                   1765:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1766:                 }
1.899     raeburn  1767:             }
                   1768:         }
                   1769:     }
1.909     raeburn  1770:     return ($outcome,%results);
1.899     raeburn  1771: }
                   1772: 
                   1773: sub usersearch {
                   1774:     my ($srch) = @_;
                   1775:     my $dom = $srch->{'srchdomain'};
                   1776:     my %results;
                   1777:     my %libserv = &all_library();
                   1778:     my $query = 'usersearch';
                   1779:     foreach my $tryserver (keys(%libserv)) {
                   1780:         if (&host_domain($tryserver) eq $dom) {
                   1781:             my $host=&hostname($tryserver);
                   1782:             my $queryid=
1.911     raeburn  1783:                 &reply("querysend:".&escape($query).':'.
                   1784:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1785:                        &escape($srch->{'srchtype'}).':'.
                   1786:                        &escape($srch->{'srchterm'}),$tryserver);
                   1787:             if ($queryid !~/^\Q$host\E\_/) {
                   1788:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1789:                 next;
1.899     raeburn  1790:             }
                   1791:             my $reply = &get_query_reply($queryid);
                   1792:             my $maxtries = 1;
                   1793:             my $tries = 1;
                   1794:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1795:                 $reply = &get_query_reply($queryid);
                   1796:                 $tries ++;
                   1797:             }
                   1798:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1799:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1800:             } else {
1.911     raeburn  1801:                 my @matches;
                   1802:                 if ($reply =~ /\n/) {
                   1803:                     @matches = split(/\n/,$reply);
                   1804:                 } else {
                   1805:                     @matches = split(/\&/,$reply);
                   1806:                 }
1.899     raeburn  1807:                 foreach my $match (@matches) {
                   1808:                     my ($uname,$udom,%userhash);
1.911     raeburn  1809:                     foreach my $entry (split(/:/,$match)) {
                   1810:                         my ($key,$value) =
                   1811:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1812:                         $userhash{$key} = $value;
                   1813:                         if ($key eq 'username') {
                   1814:                             $uname = $value;
                   1815:                         } elsif ($key eq 'domain') {
                   1816:                             $udom = $value;
1.911     raeburn  1817:                         }
1.899     raeburn  1818:                     }
                   1819:                     $results{$uname.':'.$udom} = \%userhash;
                   1820:                 }
                   1821:             }
                   1822:         }
                   1823:     }
                   1824:     return %results;
                   1825: }
                   1826: 
1.912     raeburn  1827: sub get_instuser {
                   1828:     my ($udom,$uname,$id) = @_;
                   1829:     my $homeserver = &domain($udom,'primary');
                   1830:     my ($outcome,%results);
                   1831:     if ($homeserver ne '') {
                   1832:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1833:                            &escape($id).':'.&escape($udom),$homeserver);
                   1834:         my $host=&hostname($homeserver);
                   1835:         if ($queryid !~/^\Q$host\E\_/) {
                   1836:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1837:             return;
                   1838:         }
                   1839:         my $response = &get_query_reply($queryid);
                   1840:         my $maxtries = 5;
                   1841:         my $tries = 1;
                   1842:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1843:             $response = &get_query_reply($queryid);
                   1844:             $tries ++;
                   1845:         }
                   1846:         if (!&error($response) && $response ne 'refused') {
                   1847:             if ($response eq 'unavailable') {
                   1848:                 $outcome = $response;
                   1849:             } else {
                   1850:                 $outcome = 'ok';
                   1851:                 my @matches = split(/\n/,$response);
                   1852:                 foreach my $match (@matches) {
                   1853:                     my ($key,$value) = split(/=/,$match);
                   1854:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1855:                 }
                   1856:             }
                   1857:         }
                   1858:     }
                   1859:     my %userinfo;
                   1860:     if (ref($results{$uname}) eq 'HASH') {
                   1861:         %userinfo = %{$results{$uname}};
                   1862:     } 
                   1863:     return ($outcome,%userinfo);
                   1864: }
                   1865: 
                   1866: sub inst_rulecheck {
1.923     raeburn  1867:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1868:     my %returnhash;
                   1869:     if ($udom ne '') {
                   1870:         if (ref($rules) eq 'ARRAY') {
                   1871:             @{$rules} = map {&escape($_);} (@{$rules});
                   1872:             my $rulestr = join(':',@{$rules});
                   1873:             my $homeserver=&domain($udom,'primary');
                   1874:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1875:                 my $response;
                   1876:                 if ($item eq 'username') {                
                   1877:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1878:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1879:                                               $homeserver));
1.923     raeburn  1880:                 } elsif ($item eq 'id') {
                   1881:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1882:                                               ':'.&escape($id).':'.$rulestr,
                   1883:                                               $homeserver));
1.945     raeburn  1884:                 } elsif ($item eq 'selfcreate') {
                   1885:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1886:                                                &escape($udom).':'.&escape($uname).
                   1887:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1888:                 }
1.912     raeburn  1889:                 if ($response ne 'refused') {
                   1890:                     my @pairs=split(/\&/,$response);
                   1891:                     foreach my $item (@pairs) {
                   1892:                         my ($key,$value)=split(/=/,$item,2);
                   1893:                         $key = &unescape($key);
                   1894:                         next if ($key =~ /^error: 2 /);
                   1895:                         $returnhash{$key}=&thaw_unescape($value);
                   1896:                     }
                   1897:                 }
                   1898:             }
                   1899:         }
                   1900:     }
                   1901:     return %returnhash;
                   1902: }
                   1903: 
                   1904: sub inst_userrules {
1.923     raeburn  1905:     my ($udom,$check) = @_;
1.912     raeburn  1906:     my (%ruleshash,@ruleorder);
                   1907:     if ($udom ne '') {
                   1908:         my $homeserver=&domain($udom,'primary');
                   1909:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1910:             my $response;
                   1911:             if ($check eq 'id') {
                   1912:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1913:                                  $homeserver);
1.943     raeburn  1914:             } elsif ($check eq 'email') {
                   1915:                 $response=&reply('instemailrules:'.&escape($udom),
                   1916:                                  $homeserver);
1.923     raeburn  1917:             } else {
                   1918:                 $response=&reply('instuserrules:'.&escape($udom),
                   1919:                                  $homeserver);
                   1920:             }
1.912     raeburn  1921:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1922:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1923:                 ($response ne 'no_such_host')) {
                   1924:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1925:                 my @pairs=split(/\&/,$hashitems);
                   1926:                 foreach my $item (@pairs) {
                   1927:                     my ($key,$value)=split(/=/,$item,2);
                   1928:                     $key = &unescape($key);
                   1929:                     next if ($key =~ /^error: 2 /);
                   1930:                     $ruleshash{$key}=&thaw_unescape($value);
                   1931:                 }
                   1932:                 my @esc_order = split(/\&/,$orderitems);
                   1933:                 foreach my $item (@esc_order) {
                   1934:                     push(@ruleorder,&unescape($item));
                   1935:                 }
                   1936:             }
                   1937:         }
                   1938:     }
                   1939:     return (\%ruleshash,\@ruleorder);
                   1940: }
                   1941: 
1.976     raeburn  1942: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1943: 
                   1944: sub get_domain_defaults {
                   1945:     my ($domain) = @_;
                   1946:     my $cachetime = 60*60*24;
                   1947:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1948:     if (defined($cached)) {
                   1949:         if (ref($result) eq 'HASH') {
                   1950:             return %{$result};
                   1951:         }
                   1952:     }
                   1953:     my %domdefaults;
                   1954:     my %domconfig =
1.989     raeburn  1955:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  1956:                                   'requestcourses','inststatus',
1.1172.2.9  raeburn  1957:                                   'coursedefaults','usersessions',
                   1958:                                   'requestauthor'],$domain);
1.943     raeburn  1959:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1960:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1961:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1962:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  1963:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  1964:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  1965:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943     raeburn  1966:     } else {
                   1967:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1968:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1969:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1970:     }
1.976     raeburn  1971:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1972:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1973:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1974:         } else {
                   1975:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1976:         } 
1.1172.2.6  raeburn  1977:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  1978:         foreach my $item (@usertools) {
                   1979:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1980:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1981:             }
                   1982:         }
                   1983:     }
1.985     raeburn  1984:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006    raeburn  1985:         foreach my $item ('official','unofficial','community') {
1.985     raeburn  1986:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   1987:         }
                   1988:     }
1.1172.2.9  raeburn  1989:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   1990:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   1991:     }
1.989     raeburn  1992:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   1993:         foreach my $item ('inststatustypes','inststatusorder') {
                   1994:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   1995:         }
                   1996:     }
1.1047    raeburn  1997:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
                   1998:         foreach my $item ('canuse_pdfforms') {
                   1999:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
                   2000:         }
                   2001:     }
1.1073    raeburn  2002:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2003:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2004:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2005:         }
                   2006:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2007:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2008:         }
                   2009:     }
1.943     raeburn  2010:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   2011:                                   $cachetime);
                   2012:     return %domdefaults;
                   2013: }
                   2014: 
1.344     www      2015: # --------------------------------------------------- Assign a key to a student
                   2016: 
                   2017: sub assign_access_key {
1.364     www      2018: #
                   2019: # a valid key looks like uname:udom#comments
                   2020: # comments are being appended
                   2021: #
1.498     www      2022:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2023:     $kdom=
1.620     albertel 2024:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2025:     $knum=
1.620     albertel 2026:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2027:     $cdom=
1.620     albertel 2028:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2029:     $cnum=
1.620     albertel 2030:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2031:     $udom=$env{'user.name'} unless (defined($udom));
                   2032:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2033:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2034:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2035:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2036:                                                   # assigned to this person
                   2037:                                                   # - this should not happen,
1.345     www      2038:                                                   # unless something went wrong
                   2039:                                                   # the first time around
                   2040: # ready to assign
1.364     www      2041:         $logentry=$1.'; '.$logentry;
1.496     www      2042:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2043:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2044: # key now belongs to user
1.346     www      2045: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2046:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2047:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2048:                 return 'ok';
                   2049:             } else {
                   2050:                 return 
                   2051:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2052: 	    }
                   2053:         } else {
                   2054:             return 'error: Could not assign key, try again later.';
                   2055:         }
1.364     www      2056:     } elsif (!$existing{$ckey}) {
1.345     www      2057: # the key does not exist
                   2058: 	return 'error: The key does not exist';
                   2059:     } else {
                   2060: # the key is somebody else's
                   2061: 	return 'error: The key is already in use';
                   2062:     }
1.344     www      2063: }
                   2064: 
1.364     www      2065: # ------------------------------------------ put an additional comment on a key
                   2066: 
                   2067: sub comment_access_key {
                   2068: #
                   2069: # a valid key looks like uname:udom#comments
                   2070: # comments are being appended
                   2071: #
                   2072:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2073:     $cdom=
1.620     albertel 2074:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2075:     $cnum=
1.620     albertel 2076:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2077:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2078:     if ($existing{$ckey}) {
                   2079:         $existing{$ckey}.='; '.$logentry;
                   2080: # ready to assign
1.367     www      2081:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2082:                                                  $cdom,$cnum) eq 'ok') {
                   2083: 	    return 'ok';
                   2084:         } else {
                   2085: 	    return 'error: Count not store comment.';
                   2086:         }
                   2087:     } else {
                   2088: # the key does not exist
                   2089: 	return 'error: The key does not exist';
                   2090:     }
                   2091: }
                   2092: 
1.344     www      2093: # ------------------------------------------------------ Generate a set of keys
                   2094: 
                   2095: sub generate_access_keys {
1.364     www      2096:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2097:     $cdom=
1.620     albertel 2098:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2099:     $cnum=
1.620     albertel 2100:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2101:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2102:     unless (($cdom) && ($cnum)) { return 0; }
                   2103:     if ($number>10000) { return 0; }
                   2104:     sleep(2); # make sure don't get same seed twice
                   2105:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2106:     my $total=0;
                   2107:     for (my $i=1;$i<=$number;$i++) {
                   2108:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2109:                   sprintf("%lx",int(100000*rand)).'-'.
                   2110:                   sprintf("%lx",int(100000*rand));
                   2111:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2112:        $newkey=~s/0/h/g; # and also 0 and O
                   2113:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2114:        if ($existing{$newkey}) {
                   2115:            $i--;
                   2116:        } else {
1.364     www      2117: 	  if (&put('accesskeys',
                   2118:               { $newkey => '# generated '.localtime().
1.620     albertel 2119:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2120:                            '; '.$logentry },
                   2121: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2122:               $total++;
                   2123: 	  }
                   2124:        }
                   2125:     }
1.620     albertel 2126:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2127:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2128:     return $total;
                   2129: }
                   2130: 
                   2131: # ------------------------------------------------------- Validate an accesskey
                   2132: 
                   2133: sub validate_access_key {
                   2134:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2135:     $cdom=
1.620     albertel 2136:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2137:     $cnum=
1.620     albertel 2138:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2139:     $udom=$env{'user.domain'} unless (defined($udom));
                   2140:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2141:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2142:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2143: }
                   2144: 
                   2145: # ------------------------------------- Find the section of student in a course
1.652     albertel 2146: sub devalidate_getsection_cache {
                   2147:     my ($udom,$unam,$courseid)=@_;
                   2148:     my $hashid="$udom:$unam:$courseid";
                   2149:     &devalidate_cache_new('getsection',$hashid);
                   2150: }
1.298     matthew  2151: 
1.815     albertel 2152: sub courseid_to_courseurl {
                   2153:     my ($courseid) = @_;
                   2154:     #already url style courseid
                   2155:     return $courseid if ($courseid =~ m{^/});
                   2156: 
                   2157:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2158: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2159: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2160: 	return "/$cdom/$cnum";
                   2161:     }
                   2162: 
                   2163:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2164:     if (exists($courseinfo{'num'})) {
                   2165: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2166:     }
                   2167: 
                   2168:     return undef;
                   2169: }
                   2170: 
1.298     matthew  2171: sub getsection {
                   2172:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2173:     my $cachetime=1800;
1.551     albertel 2174: 
                   2175:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2176:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2177:     if (defined($cached)) { return $result; }
                   2178: 
1.298     matthew  2179:     my %Pending; 
                   2180:     my %Expired;
                   2181:     #
                   2182:     # Each role can either have not started yet (pending), be active, 
                   2183:     #    or have expired.
                   2184:     #
                   2185:     # If there is an active role, we are done.
                   2186:     #
                   2187:     # If there is more than one role which has not started yet, 
                   2188:     #     choose the one which will start sooner
                   2189:     # If there is one role which has not started yet, return it.
                   2190:     #
                   2191:     # If there is more than one expired role, choose the one which ended last.
                   2192:     # If there is a role which has expired, return it.
                   2193:     #
1.815     albertel 2194:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2195:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2196:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2197:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2198:         my $section=$1;
                   2199:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2200:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2201:         my $now=time;
1.548     albertel 2202:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2203:             $Expired{$end}=$section;
                   2204:             next;
                   2205:         }
1.548     albertel 2206:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2207:             $Pending{$start}=$section;
                   2208:             next;
                   2209:         }
1.599     albertel 2210:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2211:     }
                   2212:     #
                   2213:     # Presumedly there will be few matching roles from the above
                   2214:     # loop and the sorting time will be negligible.
                   2215:     if (scalar(keys(%Pending))) {
                   2216:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2217:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2218:     } 
                   2219:     if (scalar(keys(%Expired))) {
                   2220:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2221:         my $time = pop(@sorted);
1.599     albertel 2222:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2223:     }
1.599     albertel 2224:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2225: }
1.70      www      2226: 
1.599     albertel 2227: sub save_cache {
                   2228:     &purge_remembered();
1.722     albertel 2229:     #&Apache::loncommon::validate_page();
1.620     albertel 2230:     undef(%env);
1.780     albertel 2231:     undef($env_loaded);
1.599     albertel 2232: }
1.452     albertel 2233: 
1.599     albertel 2234: my $to_remember=-1;
                   2235: my %remembered;
                   2236: my %accessed;
                   2237: my $kicks=0;
                   2238: my $hits=0;
1.849     albertel 2239: sub make_key {
                   2240:     my ($name,$id) = @_;
1.872     albertel 2241:     if (length($id) > 65 
                   2242: 	&& length(&escape($id)) > 200) {
                   2243: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2244:     }
1.849     albertel 2245:     return &escape($name.':'.$id);
                   2246: }
                   2247: 
1.599     albertel 2248: sub devalidate_cache_new {
                   2249:     my ($name,$id,$debug) = @_;
                   2250:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 2251:     $id=&make_key($name,$id);
1.599     albertel 2252:     $memcache->delete($id);
                   2253:     delete($remembered{$id});
                   2254:     delete($accessed{$id});
                   2255: }
                   2256: 
                   2257: sub is_cached_new {
                   2258:     my ($name,$id,$debug) = @_;
1.849     albertel 2259:     $id=&make_key($name,$id);
1.599     albertel 2260:     if (exists($remembered{$id})) {
1.1133    foxr     2261: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599     albertel 2262: 	$accessed{$id}=[&gettimeofday()];
                   2263: 	$hits++;
                   2264: 	return ($remembered{$id},1);
                   2265:     }
                   2266:     my $value = $memcache->get($id);
                   2267:     if (!(defined($value))) {
                   2268: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2269: 	return (undef,undef);
1.416     albertel 2270:     }
1.599     albertel 2271:     if ($value eq '__undef__') {
                   2272: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2273: 	$value=undef;
                   2274:     }
                   2275:     &make_room($id,$value,$debug);
                   2276:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2277:     return ($value,1);
                   2278: }
                   2279: 
                   2280: sub do_cache_new {
                   2281:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 2282:     $id=&make_key($name,$id);
1.599     albertel 2283:     my $setvalue=$value;
                   2284:     if (!defined($setvalue)) {
                   2285: 	$setvalue='__undef__';
                   2286:     }
1.623     albertel 2287:     if (!defined($time) ) {
                   2288: 	$time=600;
                   2289:     }
1.599     albertel 2290:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2291:     my $result = $memcache->set($id,$setvalue,$time);
                   2292:     if (! $result) {
1.872     albertel 2293: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2294: 	$memcache->disconnect_all();
1.872     albertel 2295:     }
1.600     albertel 2296:     # need to make a copy of $value
1.919     albertel 2297:     &make_room($id,$value,$debug);
1.599     albertel 2298:     return $value;
                   2299: }
                   2300: 
                   2301: sub make_room {
                   2302:     my ($id,$value,$debug)=@_;
1.919     albertel 2303: 
                   2304:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   2305:                                     : $value;
1.599     albertel 2306:     if ($to_remember<0) { return; }
                   2307:     $accessed{$id}=[&gettimeofday()];
                   2308:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2309:     my $to_kick;
                   2310:     my $max_time=0;
                   2311:     foreach my $other (keys(%accessed)) {
                   2312: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2313: 	    $to_kick=$other;
                   2314: 	    $max_time=&tv_interval($accessed{$other});
                   2315: 	}
                   2316:     }
                   2317:     delete($remembered{$to_kick});
                   2318:     delete($accessed{$to_kick});
                   2319:     $kicks++;
                   2320:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2321:     return;
                   2322: }
                   2323: 
1.599     albertel 2324: sub purge_remembered {
1.604     albertel 2325:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2326:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2327:     undef(%remembered);
                   2328:     undef(%accessed);
1.428     albertel 2329: }
1.70      www      2330: # ------------------------------------- Read an entry from a user's environment
                   2331: 
                   2332: sub userenvironment {
                   2333:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2334:     my $items;
                   2335:     foreach my $item (@what) {
                   2336:         $items.=&escape($item).'&';
                   2337:     }
                   2338:     $items=~s/\&$//;
1.70      www      2339:     my %returnhash=();
1.1009    raeburn  2340:     my $uhome = &homeserver($unam,$udom);
                   2341:     unless ($uhome eq 'no_host') {
                   2342:         my @answer=split(/\&/, 
                   2343:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2344:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2345:             return %returnhash;
                   2346:         }
1.1009    raeburn  2347:         my $i;
                   2348:         for ($i=0;$i<=$#what;$i++) {
                   2349: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2350:         }
1.70      www      2351:     }
                   2352:     return %returnhash;
1.1       albertel 2353: }
                   2354: 
1.617     albertel 2355: # ---------------------------------------------------------- Get a studentphoto
                   2356: sub studentphoto {
                   2357:     my ($udom,$unam,$ext) = @_;
                   2358:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2359:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2360:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2361:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2362:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2363:             } else {
                   2364:                 my ($result,$perm_reqd)=
1.707     albertel 2365: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2366:                 if ($result eq 'ok') {
                   2367:                     if (!($perm_reqd eq 'yes')) {
                   2368:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2369:                     }
                   2370:                 }
                   2371:             }
                   2372:         }
                   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:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2383: }
                   2384: 
                   2385: sub retrievestudentphoto {
                   2386:     my ($udom,$unam,$ext,$type) = @_;
                   2387:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2388:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2389:     if ($ret eq 'ok') {
                   2390:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2391:         if ($type eq 'thumbnail') {
                   2392:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2393:         }
                   2394:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2395:         return $tokenurl;
                   2396:     } else {
                   2397:         if ($type eq 'thumbnail') {
                   2398:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2399:         } else { 
                   2400:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2401:         }
1.617     albertel 2402:     }
                   2403: }
                   2404: 
1.263     www      2405: # -------------------------------------------------------------------- New chat
                   2406: 
                   2407: sub chatsend {
1.724     raeburn  2408:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2409:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2410:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2411:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2412:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2413: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2414: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2415: }
                   2416: 
                   2417: # ------------------------------------------ Find current version of a resource
                   2418: 
                   2419: sub getversion {
                   2420:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  2421:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2422:     return &currentversion(&filelocation('',$fname));
                   2423: }
                   2424: 
                   2425: sub currentversion {
                   2426:     my $fname=shift;
                   2427:     my $author=$fname;
                   2428:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2429:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2430:     my $home=&homeserver($uname,$udom);
1.292     www      2431:     if ($home eq 'no_host') { 
                   2432:         return -1; 
                   2433:     }
1.1112    www      2434:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2435:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2436: 	return -1;
                   2437:     }
1.1112    www      2438:     return $answer;
1.263     www      2439: }
                   2440: 
1.1111    www      2441: #
                   2442: # Return special version number of resource if set by override, empty otherwise
                   2443: #
                   2444: sub usedversion {
                   2445:     my $fname=shift;
                   2446:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2447:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2448:     if ($urlversion) { return $urlversion; }
                   2449:     return '';
                   2450: }
                   2451: 
1.1       albertel 2452: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2453: 
1.1       albertel 2454: sub subscribe {
                   2455:     my $fname=shift;
1.761     raeburn  2456:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2457:     $fname=~s/[\n\r]//g;
1.1       albertel 2458:     my $author=$fname;
                   2459:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2460:     my ($udom,$uname)=split(/\//,$author);
                   2461:     my $home=homeserver($uname,$udom);
1.335     albertel 2462:     if ($home eq 'no_host') {
                   2463:         return 'not_found';
1.1       albertel 2464:     }
                   2465:     my $answer=reply("sub:$fname",$home);
1.64      www      2466:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2467: 	$answer.=' by '.$home;
                   2468:     }
1.1       albertel 2469:     return $answer;
                   2470: }
                   2471:     
1.8       www      2472: # -------------------------------------------------------------- Replicate file
                   2473: 
                   2474: sub repcopy {
                   2475:     my $filename=shift;
1.23      www      2476:     $filename=~s/\/+/\//g;
1.1142    raeburn  2477:     my $londocroot = $perlvar{'lonDocRoot'};
                   2478:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2479:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2480:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2481: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2482: 	return &repcopy_userfile($filename);
                   2483:     }
1.532     albertel 2484:     $filename=~s/[\n\r]//g;
1.8       www      2485:     my $transname="$filename.in.transfer";
1.828     www      2486: # FIXME: this should flock
1.607     raeburn  2487:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2488:     my $remoteurl=subscribe($filename);
1.64      www      2489:     if ($remoteurl =~ /^con_lost by/) {
                   2490: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2491:            return 'unavailable';
1.8       www      2492:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2493: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2494: 	   return 'not_found';
1.64      www      2495:     } elsif ($remoteurl =~ /^rejected by/) {
                   2496: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2497:            return 'forbidden';
1.20      www      2498:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2499:            return 'ok';
1.8       www      2500:     } else {
1.290     www      2501:         my $author=$filename;
                   2502:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2503:         my ($udom,$uname)=split(/\//,$author);
                   2504:         my $home=homeserver($uname,$udom);
                   2505:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2506:            my @parts=split(/\//,$filename);
                   2507:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2508:            if ($path ne "$londocroot/res") {
1.8       www      2509:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2510: 	       return 'bad_request';
1.8       www      2511:            }
                   2512:            my $count;
                   2513:            for ($count=5;$count<$#parts;$count++) {
                   2514:                $path.="/$parts[$count]";
                   2515:                if ((-e $path)!=1) {
                   2516: 		   mkdir($path,0777);
                   2517:                }
                   2518:            }
                   2519:            my $ua=new LWP::UserAgent;
                   2520:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2521:            my $response=$ua->request($request,$transname);
                   2522:            if ($response->is_error()) {
                   2523: 	       unlink($transname);
                   2524:                my $message=$response->status_line;
1.672     albertel 2525:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2526:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2527:                return 'unavailable';
1.8       www      2528:            } else {
1.16      www      2529: 	       if ($remoteurl!~/\.meta$/) {
                   2530:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2531:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2532:                   if ($mresponse->is_error()) {
                   2533: 		      unlink($filename.'.meta');
                   2534:                       &logthis(
1.672     albertel 2535:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2536:                   }
                   2537: 	       }
1.8       www      2538:                rename($transname,$filename);
1.607     raeburn  2539:                return 'ok';
1.8       www      2540:            }
1.290     www      2541:        }
1.8       www      2542:     }
1.330     www      2543: }
                   2544: 
                   2545: # ------------------------------------------------ Get server side include body
                   2546: sub ssi_body {
1.381     albertel 2547:     my ($filelink,%form)=@_;
1.606     matthew  2548:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2549:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2550:     }
1.953     www      2551:     my $output='';
                   2552:     my $response;
1.980     raeburn  2553:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2554:        ($output,$response)=&externalssi($filelink);
1.953     www      2555:     } else {
1.1004    droeschl 2556:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2557:        $filelink .= 'inhibitmenu=yes';
1.953     www      2558:        ($output,$response)=&ssi($filelink,%form);
                   2559:     }
1.778     albertel 2560:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2561:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2562:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2563:     if (wantarray) {
                   2564:         return ($output, $response);
                   2565:     } else {
                   2566:         return $output;
                   2567:     }
1.8       www      2568: }
                   2569: 
1.15      www      2570: # --------------------------------------------------------- Server Side Include
                   2571: 
1.782     albertel 2572: sub absolute_url {
                   2573:     my ($host_name) = @_;
                   2574:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2575:     if ($host_name eq '') {
                   2576: 	$host_name = $ENV{'SERVER_NAME'};
                   2577:     }
                   2578:     return $protocol.$host_name;
                   2579: }
                   2580: 
1.942     foxr     2581: #
                   2582: #   Server side include.
                   2583: # Parameters:
                   2584: #  fn     Possibly encrypted resource name/id.
                   2585: #  form   Hash that describes how the rendering should be done
                   2586: #         and other things.
1.944     foxr     2587: # Returns:
1.950     raeburn  2588: #   Scalar context: The content of the response.
                   2589: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2590: #     
1.15      www      2591: sub ssi {
                   2592: 
1.944     foxr     2593:     my ($fn,%form)=@_;
1.15      www      2594:     my $ua=new LWP::UserAgent;
1.23      www      2595:     my $request;
1.711     albertel 2596: 
                   2597:     $form{'no_update_last_known'}=1;
1.895     albertel 2598:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2599:     if (%form) {
1.782     albertel 2600:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2601:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2602:     } else {
1.782     albertel 2603:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2604:     }
                   2605: 
1.15      www      2606:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.2  raeburn  2607:     my $response= $ua->request($request);
1.944     foxr     2608:     if (wantarray) {
1.1172.2.3  raeburn  2609: 	return ($response->content, $response);
1.944     foxr     2610:     } else {
1.1172.2.3  raeburn  2611: 	return $response->content;
1.942     foxr     2612:     }
1.324     www      2613: }
                   2614: 
                   2615: sub externalssi {
                   2616:     my ($url)=@_;
                   2617:     my $ua=new LWP::UserAgent;
                   2618:     my $request=new HTTP::Request('GET',$url);
                   2619:     my $response=$ua->request($request);
1.954     raeburn  2620:     if (wantarray) {
                   2621:         return ($response->content, $response);
                   2622:     } else {
                   2623:         return $response->content;
                   2624:     }
1.15      www      2625: }
1.254     www      2626: 
1.492     albertel 2627: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2628: 
                   2629: sub allowuploaded {
                   2630:     my ($srcurl,$url)=@_;
                   2631:     $url=&clutter(&declutter($url));
                   2632:     my $dir=$url;
                   2633:     $dir=~s/\/[^\/]+$//;
                   2634:     my %httpref=();
                   2635:     my $httpurl=&hreflocation('',$url);
                   2636:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2637:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2638: }
1.477     raeburn  2639: 
1.1172.2.13! raeburn  2640: #
        !          2641: # Determine if the current user should be able to edit a particular resource,
        !          2642: # when viewing in course context.
        !          2643: # (a) When viewing resource used to determine if "Edit" item is included in
        !          2644: #     Functions.
        !          2645: # (b) When displaying folder contents in course editor, used to determine if
        !          2646: #     "Edit" link will be displayed alongside resource.
        !          2647: #
        !          2648: #  input: six args -- filename (decluttered), course number, course domain,
        !          2649: #                   url, symb (if registered) and group (if this is a group
        !          2650: #                   item -- e.g., bulletin board, group page etc.).
        !          2651: #  output: array of five scalars --
        !          2652: #          $cfile -- url for file editing if editable on current server
        !          2653: #          $home -- homeserver of resource (i.e., for author if published,
        !          2654: #                                           or course if uploaded.).
        !          2655: #          $switchserver --  1 if server switch will be needed.
        !          2656: #          $forceedit -- 1 if icon/link should be to go to edit mode
        !          2657: #          $forceview -- 1 if icon/link should be to go to view mode
        !          2658: #
        !          2659: 
        !          2660: sub can_edit_resource {
        !          2661:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
        !          2662:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
        !          2663: #
        !          2664: # For aboutme pages user can only edit his/her own.
        !          2665: #
        !          2666:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
        !          2667:         my ($sdom,$sname) = ($1,$2);
        !          2668:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
        !          2669:             $home = $env{'user.home'};
        !          2670:             $cfile = $resurl;
        !          2671:             if ($env{'form.forceedit'}) {
        !          2672:                 $forceview = 1;
        !          2673:             } else {
        !          2674:                 $forceedit = 1;
        !          2675:             }
        !          2676:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
        !          2677:         } else {
        !          2678:             return;
        !          2679:         }
        !          2680:     }
        !          2681: 
        !          2682:     if ($env{'request.course.id'}) {
        !          2683:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
        !          2684:         if ($group ne '') {
        !          2685: # if this is a group homepage or group bulletin board, check group privs
        !          2686:             my $allowed = 0;
        !          2687:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
        !          2688:                 if ((&allowed('mdg',$env{'request.course.id'}.
        !          2689:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
        !          2690:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
        !          2691:                     $allowed = 1;
        !          2692:                 }
        !          2693:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
        !          2694:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
        !          2695:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
        !          2696:                     $allowed = 1;
        !          2697:                 }
        !          2698:             }
        !          2699:             if ($allowed) {
        !          2700:                 $home=&homeserver($cnum,$cdom);
        !          2701:                 if ($env{'form.forceedit'}) {
        !          2702:                     $forceview = 1;
        !          2703:                 } else {
        !          2704:                     $forceedit = 1;
        !          2705:                 }
        !          2706:                 $cfile = $resurl;
        !          2707:             } else {
        !          2708:                 return;
        !          2709:             }
        !          2710:         } else {
        !          2711: #
        !          2712: # No edit allowed where CC has switched to student role.
        !          2713: #
        !          2714:             unless ($crsedit) {
        !          2715:                 return;
        !          2716:             }
        !          2717:         }
        !          2718:     }
        !          2719: 
        !          2720:     if ($file ne '') {
        !          2721:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
        !          2722:             if (&is_course_upload($file,$cnum,$cdom)) {
        !          2723:                 $uploaded = 1;
        !          2724:                 $incourse = 1;
        !          2725:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
        !          2726:                     $cfile = &hreflocation('',$file);
        !          2727:                     if ($env{'form.forceedit'}) {
        !          2728:                         $forceview = 1;
        !          2729:                     } else {
        !          2730:                         $forceedit = 1;
        !          2731:                     }
        !          2732:                 }
        !          2733:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
        !          2734:                 $incourse = 1;
        !          2735:                 if ($env{'form.forceedit'}) {
        !          2736:                     $forceview = 1;
        !          2737:                 } else {
        !          2738:                     $forceedit = 1;
        !          2739:                 }
        !          2740:                 $cfile = $resurl;
        !          2741:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
        !          2742:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
        !          2743:                     $incourse = 1;
        !          2744:                     if ($env{'form.forceedit'}) {
        !          2745:                         $forceview = 1;
        !          2746:                     } else {
        !          2747:                         $forceedit = 1;
        !          2748:                     }
        !          2749:                     $cfile = $resurl;
        !          2750:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
        !          2751:                     $incourse = 1;
        !          2752:                     $cfile = $resurl.'/smpedit';
        !          2753:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
        !          2754:                     $incourse = 1;
        !          2755:                     if ($env{'form.forceedit'}) {
        !          2756:                         $forceview = 1;
        !          2757:                     } else {
        !          2758:                         $forceedit = 1;
        !          2759:                     }
        !          2760:                     $cfile = $resurl;
        !          2761:                 }
        !          2762:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
        !          2763:                 my $template = '/res/lib/templates/simpleproblem.problem';
        !          2764:                 if (&is_on_map($template)) {
        !          2765:                     $incourse = 1;
        !          2766:                     $forceview = 1;
        !          2767:                     $cfile = $template;
        !          2768:                 }
        !          2769:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
        !          2770:                     $incourse = 1;
        !          2771:                     if ($env{'form.forceedit'}) {
        !          2772:                         $forceview = 1;
        !          2773:                     } else {
        !          2774:                         $forceedit = 1;
        !          2775:                     }
        !          2776:                     $cfile = $resurl;
        !          2777:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
        !          2778:                 $incourse = 1;
        !          2779:                 $forceview = 1;
        !          2780:                 if ($symb) {
        !          2781:                     my ($map,$id,$res)=&decode_symb($symb);
        !          2782:                     $env{'request.symb'} = $symb;
        !          2783:                     $cfile = &clutter($res);
        !          2784:                 } else {
        !          2785:                     $cfile = $env{'form.suppurl'};
        !          2786:                     $cfile =~ s{^http://}{};
        !          2787:                     $cfile = '/adm/wrapper/ext/'.$cfile;
        !          2788:                 }
        !          2789:             }
        !          2790:         }
        !          2791:         if ($uploaded || $incourse) {
        !          2792:             $home=&homeserver($cnum,$cdom);
        !          2793:         } else {
        !          2794:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
        !          2795:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
        !          2796:             # Check that the user has permission to edit this resource
        !          2797:             my $setpriv = 1;
        !          2798:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
        !          2799:             if (defined($cfudom)) {
        !          2800:                 $home=&homeserver($cfuname,$cfudom);
        !          2801:                 $cfile=$file;
        !          2802:             }
        !          2803:         }
        !          2804:         if (($cfile ne '') && (!$incourse || $uploaded) &&
        !          2805:             (($home ne '') && ($home ne 'no_host'))) {
        !          2806:             my @ids=&current_machine_ids();
        !          2807:             unless (grep(/^\Q$home\E$/,@ids)) {
        !          2808:                 $switchserver=1;
        !          2809:             }
        !          2810:         }
        !          2811:     }
        !          2812:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
        !          2813: }
        !          2814: 
        !          2815: sub is_course_upload {
        !          2816:     my ($file,$cnum,$cdom) = @_;
        !          2817:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
        !          2818:     $uploadpath =~ s{^\/}{};
        !          2819:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
        !          2820:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
        !          2821:         return 1;
        !          2822:     }
        !          2823:     return;
        !          2824: }
        !          2825: 
        !          2826: sub in_course {
        !          2827:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
        !          2828:     if ($hideprivileged) {
        !          2829:         my $skipuser;
        !          2830:         if (&privileged($uname,$udom)) {
        !          2831:             $skipuser = 1;
        !          2832:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
        !          2833:             if ($coursehash{'nothideprivileged'}) {
        !          2834:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
        !          2835:                     my $user;
        !          2836:                     if ($item =~ /:/) {
        !          2837:                         $user = $item;
        !          2838:                     } else {
        !          2839:                         $user = join(':',split(/[\@]/,$item));
        !          2840:                     }
        !          2841:                     if ($user eq $uname.':'.$udom) {
        !          2842:                         undef($skipuser);
        !          2843:                         last;
        !          2844:                     }
        !          2845:                 }
        !          2846:             }
        !          2847:             if ($skipuser) {
        !          2848:                 return 0;
        !          2849:             }
        !          2850:         }
        !          2851:     }
        !          2852:     $type ||= 'any';
        !          2853:     if (!defined($cdom) || !defined($cnum)) {
        !          2854:         my $cid  = $env{'request.course.id'};
        !          2855:         $cdom = $env{'course.'.$cid.'.domain'};
        !          2856:         $cnum = $env{'course.'.$cid.'.num'};
        !          2857:     }
        !          2858:     my $typesref;
        !          2859:     if (($type eq 'any') || ($type eq 'all')) {
        !          2860:         $typesref = ['active','previous','future'];
        !          2861:     } elsif ($type eq 'previous' || $type eq 'future') {
        !          2862:         $typesref = [$type];
        !          2863:     }
        !          2864:     my %roles = &get_my_roles($uname,$udom,'userroles',
        !          2865:                               $typesref,undef,[$cdom]);
        !          2866:     my ($tmp) = keys(%roles);
        !          2867:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
        !          2868:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
        !          2869:     if (@course_roles > 0) {
        !          2870:         return 1;
        !          2871:     }
        !          2872:     return 0;
        !          2873: }
        !          2874: 
1.478     albertel 2875: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2876: # input: action, courseID, current domain, intended
1.637     raeburn  2877: #        path to file, source of file, instruction to parse file for objects,
                   2878: #        ref to hash for embedded objects,
                   2879: #        ref to hash for codebase of java objects.
1.1095    raeburn  2880: #        reference to scalar to accommodate mime type determined
                   2881: #          from File::MMagic if $parser = parse.
1.637     raeburn  2882: #
1.485     raeburn  2883: # output: url to file (if action was uploaddoc), 
                   2884: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2885: #
1.478     albertel 2886: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2887: # course.
1.477     raeburn  2888: #
1.478     albertel 2889: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2890: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2891: #          course's home server.
1.477     raeburn  2892: #
1.478     albertel 2893: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2894: #          be copied from $source (current location) to 
                   2895: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2896: #         and will then be copied to
                   2897: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2898: #         course's home server.
1.485     raeburn  2899: #
1.481     raeburn  2900: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2901: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2902: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2903: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2904: #         in course's home server.
1.637     raeburn  2905: #
1.477     raeburn  2906: 
                   2907: sub process_coursefile {
1.1095    raeburn  2908:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   2909:         $mimetype)=@_;
1.477     raeburn  2910:     my $fetchresult;
1.638     albertel 2911:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2912:     if ($action eq 'propagate') {
1.638     albertel 2913:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2914: 			     $home);
1.481     raeburn  2915:     } else {
1.477     raeburn  2916:         my $fpath = '';
                   2917:         my $fname = $file;
1.478     albertel 2918:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2919:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2920:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2921:         if ($action eq 'copy') {
                   2922:             if ($source eq '') {
                   2923:                 $fetchresult = 'no source file';
                   2924:                 return $fetchresult;
                   2925:             } else {
                   2926:                 my $destination = $filepath.'/'.$fname;
                   2927:                 rename($source,$destination);
                   2928:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2929:                                  $home);
1.481     raeburn  2930:             }
                   2931:         } elsif ($action eq 'uploaddoc') {
                   2932:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2933:             print $fh $env{'form.'.$source};
1.481     raeburn  2934:             close($fh);
1.637     raeburn  2935:             if ($parser eq 'parse') {
1.1024    raeburn  2936:                 my $mm = new File::MMagic;
1.1095    raeburn  2937:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   2938:                 if ($type eq 'text/html') {
1.1024    raeburn  2939:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   2940:                     unless ($parse_result eq 'ok') {
                   2941:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2942:                     }
1.637     raeburn  2943:                 }
1.1095    raeburn  2944:                 if (ref($mimetype)) {
                   2945:                     $$mimetype = $type;
                   2946:                 } 
1.637     raeburn  2947:             }
1.477     raeburn  2948:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2949:                                  $home);
1.481     raeburn  2950:             if ($fetchresult eq 'ok') {
                   2951:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2952:             } else {
                   2953:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2954:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2955:                 return '/adm/notfound.html';
                   2956:             }
1.477     raeburn  2957:         }
                   2958:     }
1.485     raeburn  2959:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2960:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2961:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2962:     }
                   2963:     return $fetchresult;
                   2964: }
                   2965: 
1.637     raeburn  2966: sub build_filepath {
                   2967:     my ($fpath) = @_;
                   2968:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2969:     unless ($fpath eq '') {
                   2970:         my @parts=split('/',$fpath);
                   2971:         foreach my $part (@parts) {
                   2972:             $filepath.= '/'.$part;
                   2973:             if ((-e $filepath)!=1) {
                   2974:                 mkdir($filepath,0777);
                   2975:             }
                   2976:         }
                   2977:     }
                   2978:     return $filepath;
                   2979: }
                   2980: 
                   2981: sub store_edited_file {
1.638     albertel 2982:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  2983:     my $file = $primary_url;
                   2984:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   2985:     my $fpath = '';
                   2986:     my $fname = $file;
                   2987:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   2988:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   2989:     my $filepath = &build_filepath($fpath);
                   2990:     open(my $fh,'>'.$filepath.'/'.$fname);
                   2991:     print $fh $content;
                   2992:     close($fh);
1.638     albertel 2993:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  2994:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2995: 			  $home);
1.637     raeburn  2996:     if ($$fetchresult eq 'ok') {
                   2997:         return '/uploaded/'.$fpath.'/'.$fname;
                   2998:     } else {
1.638     albertel 2999:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3000: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3001:         return '/adm/notfound.html';
                   3002:     }
                   3003: }
                   3004: 
1.531     albertel 3005: sub clean_filename {
1.831     albertel 3006:     my ($fname,$args)=@_;
1.315     www      3007: # Replace Windows backslashes by forward slashes
1.257     www      3008:     $fname=~s/\\/\//g;
1.831     albertel 3009:     if (!$args->{'keep_path'}) {
                   3010:         # Get rid of everything but the actual filename
                   3011: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3012:     }
1.315     www      3013: # Replace spaces by underscores
                   3014:     $fname=~s/\s+/\_/g;
                   3015: # Replace all other weird characters by nothing
1.831     albertel 3016:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3017: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3018: # numbers
                   3019:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3020:     return $fname;
                   3021: }
1.1051    raeburn  3022: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3023: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3024: # image with the same aspect ratio as the original, but with dimensions which do 
                   3025: # not exceed $resizewidth and $resizeheight.
                   3026:  
1.984     neumanie 3027: sub resizeImage {
1.1051    raeburn  3028:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3029:     my $ima = Image::Magick->new;
                   3030:     my $resized;
                   3031:     if (-e $img_path) {
                   3032:         $ima->Read($img_path);
                   3033:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3034:             my $width = $ima->Get('width');
                   3035:             my $height = $ima->Get('height');
                   3036:             if ($width > $resizewidth) {
                   3037: 	        my $factor = $width/$resizewidth;
                   3038:                 my $newheight = $height/$factor;
                   3039:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3040:                 $resized = 1;
                   3041:             }
                   3042:         }
                   3043:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3044:             my $width = $ima->Get('width');
                   3045:             my $height = $ima->Get('height');
                   3046:             if ($height > $resizeheight) {
                   3047:                 my $factor = $height/$resizeheight;
                   3048:                 my $newwidth = $width/$factor;
                   3049:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3050:                 $resized = 1;
                   3051:             }
                   3052:         }
                   3053:         if ($resized) {
                   3054:             $ima->Write($img_path);
                   3055:         }
                   3056:     }
                   3057:     return;
1.977     amueller 3058: }
                   3059: 
1.608     albertel 3060: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3061: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3062: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3063: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3064: #                                    canceloverwrite, or ''. 
                   3065: #                   if 'coursedoc': upload to the current course
                   3066: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3067: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3068: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3069: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3070: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3071: #        $allfiles - reference to hash for embedded objects
                   3072: #        $codebase - reference to hash for codebase of java objects
                   3073: #        $desuname - username for permanent storage of uploaded file
                   3074: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3075: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3076: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3077: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3078: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3079: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3080: #                    from File::MMagic.
1.858     raeburn  3081: # 
1.686     albertel 3082: # output: url of file in userspace, or error: <message> 
                   3083: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3084: 
1.531     albertel 3085: sub userfileupload {
1.1090    raeburn  3086:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3087:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3088:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3089:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3090:     $fname=&clean_filename($fname);
1.1090    raeburn  3091:     # See if there is anything left
1.257     www      3092:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3093:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3094:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3095:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3096:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3097:         my $now = time;
1.1090    raeburn  3098:         my $filepath;
1.1095    raeburn  3099:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3100:              $filepath = 'tmp/helprequests/'.$now;
                   3101:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3102:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3103:                          '_'.$env{'user.domain'}.'/pending';
                   3104:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3105:             my ($docuname,$docudom);
                   3106:             if ($destudom) {
                   3107:                 $docudom = $destudom;
                   3108:             } else {
                   3109:                 $docudom = $env{'user.domain'};
                   3110:             }
                   3111:             if ($destuname) {
                   3112:                 $docuname = $destuname;
                   3113:             } else {
                   3114:                 $docuname = $env{'user.name'};
                   3115:             }
                   3116:             if (exists($env{'form.group'})) {
                   3117:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3118:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3119:             }
                   3120:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3121:             if ($context eq 'canceloverwrite') {
                   3122:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3123:                 if (-e  $tempfile) {
                   3124:                     my @info = stat($tempfile);
                   3125:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3126:                         unlink($tempfile);
                   3127:                     }
                   3128:                 }
                   3129:                 return;
1.523     raeburn  3130:             }
                   3131:         }
1.1090    raeburn  3132:         # Create the directory if not present
1.741     raeburn  3133:         my @parts=split(/\//,$filepath);
                   3134:         my $fullpath = $perlvar{'lonDaemons'};
                   3135:         for (my $i=0;$i<@parts;$i++) {
                   3136:             $fullpath .= '/'.$parts[$i];
                   3137:             if ((-e $fullpath)!=1) {
                   3138:                 mkdir($fullpath,0777);
                   3139:             }
                   3140:         }
                   3141:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   3142:         print $fh $env{'form.'.$formname};
                   3143:         close($fh);
1.1090    raeburn  3144:         if ($context eq 'existingfile') {
                   3145:             my @info = stat($fullpath.'/'.$fname);
                   3146:             return ($fullpath.'/'.$fname,$info[9]);
                   3147:         } else {
                   3148:             return $fullpath.'/'.$fname;
                   3149:         }
1.523     raeburn  3150:     }
1.995     raeburn  3151:     if ($subdir eq 'scantron') {
                   3152:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3153:     } else {
1.995     raeburn  3154:         $fname="$subdir/$fname";
                   3155:     }
1.1090    raeburn  3156:     if ($context eq 'coursedoc') {
1.638     albertel 3157: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3158: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3159:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3160:             return &finishuserfileupload($docuname,$docudom,
                   3161: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3162: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3163:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3164:         } else {
1.620     albertel 3165:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 3166:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3167: 				       $fname,$formname,$parser,
1.1095    raeburn  3168: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3169:         }
1.719     banghart 3170:     } elsif (defined($destuname)) {
                   3171:         my $docuname=$destuname;
                   3172:         my $docudom=$destudom;
1.860     raeburn  3173: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3174: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3175:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3176:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3177:     } else {
1.638     albertel 3178:         my $docuname=$env{'user.name'};
                   3179:         my $docudom=$env{'user.domain'};
1.714     raeburn  3180:         if (exists($env{'form.group'})) {
                   3181:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3182:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3183:         }
1.860     raeburn  3184: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3185: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3186:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3187:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3188:     }
1.271     www      3189: }
                   3190: 
                   3191: sub finishuserfileupload {
1.860     raeburn  3192:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3193:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3194:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3195:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3196:   
1.860     raeburn  3197:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3198:     $file=$fname;
                   3199:     if ($fname=~m|/|) {
                   3200:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3201: 	$path.=$fnamepath.'/';
                   3202:     }
1.259     www      3203:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3204:     my $count;
                   3205:     for ($count=4;$count<=$#parts;$count++) {
                   3206:         $filepath.="/$parts[$count]";
                   3207:         if ((-e $filepath)!=1) {
                   3208: 	    mkdir($filepath,0777);
                   3209:         }
                   3210:     }
1.984     neumanie 3211: 
1.258     www      3212: # Save the file
                   3213:     {
1.701     albertel 3214: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   3215: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3216: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3217: 	    return '/adm/notfound.html';
                   3218: 	}
1.1090    raeburn  3219:         if ($context eq 'overwrite') {
1.1117    foxr     3220:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3221:             my $target = $filepath.'/'.$file;
                   3222:             if (-e $source) {
                   3223:                 my @info = stat($source);
                   3224:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3225:                     unless (&File::Copy::move($source,$target)) {
                   3226:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3227:                         return "Moving from $source failed";
                   3228:                     }
                   3229:                 } else {
                   3230:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3231:                 }
                   3232:             } else {
                   3233:                 return "Temporary file: $source missing";
                   3234:             }
                   3235:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3236: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3237: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3238: 	    return '/adm/notfound.html';
                   3239: 	}
1.570     albertel 3240: 	close(FH);
1.1051    raeburn  3241:         if ($resizewidth && $resizeheight) {
                   3242:             my $mm = new File::MMagic;
                   3243:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3244:             if ($mime_type =~ m{^image/}) {
                   3245: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3246:             }  
1.977     amueller 3247: 	}
1.258     www      3248:     }
1.1152    raeburn  3249:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3250:         if (ref($mimetype)) {
                   3251:             if ($$mimetype eq '') {
                   3252:                 my $mm = new File::MMagic;
                   3253:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3254:                 $$mimetype = $type;
                   3255:             }
                   3256:         }
                   3257:     }
1.637     raeburn  3258:     if ($parser eq 'parse') {
1.1152    raeburn  3259:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3260:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3261:                                                        $allfiles,$codebase);
                   3262:             unless ($parse_result eq 'ok') {
                   3263:                 &logthis('Failed to parse '.$filepath.$file.
                   3264: 	   	         ' for embedded media: '.$parse_result); 
                   3265:             }
1.637     raeburn  3266:         }
                   3267:     }
1.860     raeburn  3268:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3269:         my $input = $filepath.'/'.$file;
                   3270:         my $output = $filepath.'/'.'tn-'.$file;
                   3271:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3272:         system("convert -sample $thumbsize $input $output");
                   3273:         if (-e $filepath.'/'.'tn-'.$file) {
                   3274:             $fetchthumb  = 1; 
                   3275:         }
                   3276:     }
1.858     raeburn  3277:  
1.259     www      3278: # Notify homeserver to grep it
                   3279: #
1.984     neumanie 3280:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3281:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3282:     if ($fetchresult eq 'ok') {
1.860     raeburn  3283:         if ($fetchthumb) {
                   3284:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3285:             if ($thumbresult ne 'ok') {
                   3286:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3287:                          $docuhome.': '.$thumbresult);
                   3288:             }
                   3289:         }
1.259     www      3290: #
1.258     www      3291: # Return the URL to it
1.494     albertel 3292:         return '/uploaded/'.$path.$file;
1.263     www      3293:     } else {
1.494     albertel 3294:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3295: 		 ': '.$fetchresult);
1.263     www      3296:         return '/adm/notfound.html';
1.858     raeburn  3297:     }
1.493     albertel 3298: }
                   3299: 
1.637     raeburn  3300: sub extract_embedded_items {
1.961     raeburn  3301:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3302:     my @state = ();
1.1164    raeburn  3303:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3304:     my %javafiles = (
                   3305:                       codebase => '',
                   3306:                       code => '',
                   3307:                       archive => ''
                   3308:                     );
                   3309:     my %mediafiles = (
                   3310:                       src => '',
                   3311:                       movie => '',
                   3312:                      );
1.648     raeburn  3313:     my $p;
                   3314:     if ($content) {
                   3315:         $p = HTML::LCParser->new($content);
                   3316:     } else {
1.961     raeburn  3317:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3318:     }
1.641     albertel 3319:     while (my $t=$p->get_token()) {
1.640     albertel 3320: 	if ($t->[0] eq 'S') {
                   3321: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3322: 	    push(@state, $tagname);
1.648     raeburn  3323:             if (lc($tagname) eq 'allow') {
                   3324:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3325:             }
1.640     albertel 3326: 	    if (lc($tagname) eq 'img') {
                   3327: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3328: 	    }
1.886     albertel 3329: 	    if (lc($tagname) eq 'a') {
                   3330: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   3331: 	    }
1.645     raeburn  3332:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3333:                 my $src;
1.645     raeburn  3334:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3335:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3336:                 } else {
1.1164    raeburn  3337:                     if ($attr->{'src'} ne '') {
                   3338:                         $src = $attr->{'src'};
                   3339:                         &add_filetype($allfiles,$src,'src');
                   3340:                     }
                   3341:                 }
                   3342:                 my $text = $p->get_trimmed_text();
                   3343:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3344:                     my @swfargs = split(/,/,$1);
                   3345:                     foreach my $item (@swfargs) {
                   3346:                         $item =~ s/["']//g;
                   3347:                         $item =~ s/^\s+//;
                   3348:                         $item =~ s/\s+$//;
                   3349:                     }
                   3350:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3351:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3352:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3353:                         } else {
                   3354:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3355:                         }
                   3356:                     }
1.645     raeburn  3357:                 }
                   3358:             }
                   3359:             if (lc($tagname) eq 'link') {
                   3360:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3361:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3362:                 }
                   3363:             }
1.640     albertel 3364: 	    if (lc($tagname) eq 'object' ||
                   3365: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3366: 		foreach my $item (keys(%javafiles)) {
                   3367: 		    $javafiles{$item} = '';
                   3368: 		}
1.1164    raeburn  3369:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3370:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3371:                 }
1.640     albertel 3372: 	    }
                   3373: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3374: 		my $name = lc($attr->{'name'});
                   3375: 		foreach my $item (keys(%javafiles)) {
                   3376: 		    if ($name eq $item) {
                   3377: 			$javafiles{$item} = $attr->{'value'};
                   3378: 			last;
                   3379: 		    }
                   3380: 		}
1.1164    raeburn  3381:                 my $pathfrom;
1.640     albertel 3382: 		foreach my $item (keys(%mediafiles)) {
                   3383: 		    if ($name eq $item) {
1.1164    raeburn  3384:                         $pathfrom = $attr->{'value'};
                   3385:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3386: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3387: 			last;
                   3388: 		    }
                   3389: 		}
1.1164    raeburn  3390:                 if ($name eq 'flashvars') {
                   3391:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3392:                 }
                   3393:                 if ($pathfrom ne '') {
                   3394:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3395:                                          $pathfrom);
                   3396:                 }
1.640     albertel 3397: 	    }
                   3398: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3399: 		foreach my $item (keys(%javafiles)) {
                   3400: 		    if ($attr->{$item}) {
                   3401: 			$javafiles{$item} = $attr->{$item};
                   3402: 			last;
                   3403: 		    }
                   3404: 		}
                   3405: 		foreach my $item (keys(%mediafiles)) {
                   3406: 		    if ($attr->{$item}) {
                   3407: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3408: 			last;
                   3409: 		    }
                   3410: 		}
1.1164    raeburn  3411:                 if (lc($tagname) eq 'embed') {
                   3412:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3413:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3414:                                              $attr->{'src'});
                   3415:                     }
                   3416:                 }
1.640     albertel 3417: 	    }
1.1164    raeburn  3418:             if ($t->[4] =~ m{/>$}) {
                   3419:                 pop(@state);  
                   3420:             }
1.640     albertel 3421: 	} elsif ($t->[0] eq 'E') {
                   3422: 	    my ($tagname) = ($t->[1]);
                   3423: 	    if ($javafiles{'codebase'} ne '') {
                   3424: 		$javafiles{'codebase'} .= '/';
                   3425: 	    }  
                   3426: 	    if (lc($tagname) eq 'applet' ||
                   3427: 		lc($tagname) eq 'object' ||
                   3428: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3429: 		) {
                   3430: 		foreach my $item (keys(%javafiles)) {
                   3431: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3432: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3433: 			&add_filetype($allfiles,$file,$item);
                   3434: 		    }
                   3435: 		}
                   3436: 	    } 
                   3437: 	    pop @state;
                   3438: 	}
                   3439:     }
1.1164    raeburn  3440:     foreach my $id (sort(keys(%flashvars))) {
                   3441:         if ($shockwave{$id} ne '') {
                   3442:             my @pairs = split(/\&/,$flashvars{$id});
                   3443:             foreach my $pair (@pairs) {
                   3444:                 my ($key,$value) = split(/\=/,$pair);
                   3445:                 if ($key eq 'thumb') {
                   3446:                     &add_filetype($allfiles,$value,$key);
                   3447:                 } elsif ($key eq 'content') {
                   3448:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3449:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3450:                     if ($ext ne '') {
                   3451:                         &add_filetype($allfiles,$path.$value,$ext);
                   3452:                     }
                   3453:                 }
                   3454:             }
                   3455:         }
                   3456:     }
1.637     raeburn  3457:     return 'ok';
                   3458: }
                   3459: 
1.639     albertel 3460: sub add_filetype {
                   3461:     my ($allfiles,$file,$type)=@_;
                   3462:     if (exists($allfiles->{$file})) {
                   3463: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3464: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3465: 	}
                   3466:     } else {
                   3467: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3468:     }
                   3469: }
                   3470: 
1.1164    raeburn  3471: sub embedded_dependency {
                   3472:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3473:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3474:         if (($identifier ne '') &&
                   3475:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3476:             ($pathfrom ne '')) {
                   3477:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3478:             foreach my $dep (@{$related->{$identifier}}) {
                   3479:                 &add_filetype($allfiles,$path.$dep,'object');
                   3480:             }
                   3481:         }
                   3482:     }
                   3483:     return;
                   3484: }
                   3485: 
1.493     albertel 3486: sub removeuploadedurl {
1.984     neumanie 3487:     my ($url)=@_;	
                   3488:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3489:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3490: }
                   3491: 
                   3492: sub removeuserfile {
                   3493:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3494:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3495:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3496:     if ($result eq 'ok') {	
1.798     raeburn  3497:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3498:             my $metafile = $fname.'.meta';
                   3499:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3500: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3501:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3502:             my $sqlresult = 
1.823     albertel 3503:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3504:                                         'portfolio_metadata',$group,
                   3505:                                         'delete');
1.798     raeburn  3506:         }
                   3507:     }
                   3508:     return $result;
1.257     www      3509: }
1.15      www      3510: 
1.530     albertel 3511: sub mkdiruserfile {
                   3512:     my ($docuname,$docudom,$dir)=@_;
                   3513:     my $home=&homeserver($docuname,$docudom);
                   3514:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3515: }
                   3516: 
1.531     albertel 3517: sub renameuserfile {
                   3518:     my ($docuname,$docudom,$old,$new)=@_;
                   3519:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3520:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3521:                         &escape("$old").':'.&escape("$new"),$home);
                   3522:     if ($result eq 'ok') {
                   3523:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3524:             my $oldmeta = $old.'.meta';
                   3525:             my $newmeta = $new.'.meta';
                   3526:             my $metaresult = 
                   3527:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3528: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3529:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3530:             my $sqlresult = 
1.823     albertel 3531:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3532:                                         'portfolio_metadata',$group,
                   3533:                                         'delete');
1.798     raeburn  3534:         }
                   3535:     }
                   3536:     return $result;
1.531     albertel 3537: }
                   3538: 
1.14      www      3539: # ------------------------------------------------------------------------- Log
                   3540: 
                   3541: sub log {
                   3542:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3543:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3544: }
                   3545: 
                   3546: # ------------------------------------------------------------------ Course Log
1.352     www      3547: #
                   3548: # This routine flushes several buffers of non-mission-critical nature
                   3549: #
1.157     www      3550: 
                   3551: sub flushcourselogs {
1.352     www      3552:     &logthis('Flushing log buffers');
                   3553: #
                   3554: # course logs
                   3555: # This is a log of all transactions in a course, which can be used
                   3556: # for data mining purposes
                   3557: #
                   3558: # It also collects the courseid database, which lists last transaction
                   3559: # times and course titles for all courseids
                   3560: #
                   3561:     my %courseidbuffer=();
1.921     raeburn  3562:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3563:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3564: 		          &escape($courselogs{$crsid}),
                   3565: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3566: 	    delete $courselogs{$crsid};
                   3567:         } else {
                   3568:             &logthis('Failed to flush log buffer for '.$crsid);
                   3569:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3570:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3571:                         " exceeded maximum size, deleting.</font>");
                   3572:                delete $courselogs{$crsid};
                   3573:             }
1.352     www      3574:         }
1.920     raeburn  3575:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3576:             'description' => $coursedescrbuf{$crsid},
                   3577:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3578:             'type'        => $coursetypebuf{$crsid},
                   3579:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3580:         };
1.191     harris41 3581:     }
1.352     www      3582: #
                   3583: # Write course id database (reverse lookup) to homeserver of courses 
                   3584: # Is used in pickcourse
                   3585: #
1.840     albertel 3586:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3587:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3588:                                     $courseidbuffer{$crs_home},
                   3589:                                     $crs_home,'timeonly');
1.352     www      3590:     }
                   3591: #
                   3592: # File accesses
                   3593: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3594: #
1.449     matthew  3595:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3596:         if ($entry =~ /___count$/) {
                   3597:             my ($dom,$name);
1.807     albertel 3598:             ($dom,$name,undef)=
1.811     albertel 3599: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3600:             if (! defined($dom) || $dom eq '' || 
                   3601:                 ! defined($name) || $name eq '') {
1.620     albertel 3602:                 my $cid = $env{'request.course.id'};
                   3603:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3604:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3605:             }
1.450     matthew  3606:             my $value = $accesshash{$entry};
                   3607:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   3608:             my %temphash=($url => $value);
1.449     matthew  3609:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   3610:             if ($result eq 'ok') {
                   3611:                 delete $accesshash{$entry};
                   3612:             }
                   3613:         } else {
1.811     albertel 3614:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      3615:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  3616:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3617:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3618:                 delete $accesshash{$entry};
                   3619:             }
1.185     www      3620:         }
1.191     harris41 3621:     }
1.352     www      3622: #
                   3623: # Roles
                   3624: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   3625: #
1.800     albertel 3626:     foreach my $entry (keys(%userrolehash)) {
1.351     www      3627:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      3628: 	    split(/\:/,$entry);
                   3629:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      3630:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      3631:                 $rudom,$runame) eq 'ok') {
                   3632: 	    delete $userrolehash{$entry};
                   3633:         }
                   3634:     }
1.662     raeburn  3635: #
                   3636: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   3637: #
                   3638:     my %domrolebuffer = ();
1.1000    raeburn  3639:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 3640:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  3641:         if ($domrolebuffer{$rudom}) {
                   3642:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   3643:                       '='.&escape($domainrolehash{$entry});
                   3644:         } else {
                   3645:             $domrolebuffer{$rudom}.=&escape($entry).
                   3646:                       '='.&escape($domainrolehash{$entry});
                   3647:         }
                   3648:         delete $domainrolehash{$entry};
                   3649:     }
                   3650:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 3651: 	my %servers = &get_servers($dom,'library');
                   3652: 	foreach my $tryserver (keys(%servers)) {
                   3653: 	    unless (&reply('domroleput:'.$dom.':'.
                   3654: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   3655: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   3656: 	    }
1.662     raeburn  3657:         }
                   3658:     }
1.186     www      3659:     $dumpcount++;
1.157     www      3660: }
                   3661: 
                   3662: sub courselog {
                   3663:     my $what=shift;
1.158     www      3664:     $what=time.':'.$what;
1.620     albertel 3665:     unless ($env{'request.course.id'}) { return ''; }
                   3666:     $coursedombuf{$env{'request.course.id'}}=
                   3667:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3668:     $coursenumbuf{$env{'request.course.id'}}=
                   3669:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   3670:     $coursehombuf{$env{'request.course.id'}}=
                   3671:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   3672:     $coursedescrbuf{$env{'request.course.id'}}=
                   3673:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   3674:     $courseinstcodebuf{$env{'request.course.id'}}=
                   3675:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   3676:     $courseownerbuf{$env{'request.course.id'}}=
                   3677:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  3678:     $coursetypebuf{$env{'request.course.id'}}=
                   3679:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 3680:     if (defined $courselogs{$env{'request.course.id'}}) {
                   3681: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      3682:     } else {
1.620     albertel 3683: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      3684:     }
1.620     albertel 3685:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      3686: 	&flushcourselogs();
                   3687:     }
1.158     www      3688: }
                   3689: 
                   3690: sub courseacclog {
                   3691:     my $fnsymb=shift;
1.620     albertel 3692:     unless ($env{'request.course.id'}) { return ''; }
                   3693:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      3694:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      3695:         $what.=':POST';
1.583     matthew  3696:         # FIXME: Probably ought to escape things....
1.800     albertel 3697: 	foreach my $key (keys(%env)) {
                   3698:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  3699:                 my $formitem = $1;
                   3700:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   3701:                     $what.=':'.$formitem.'='.$env{$key};
                   3702:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   3703:                     $what.=':'.$formitem.'='.$env{$key};
                   3704:                 }
1.158     www      3705:             }
1.191     harris41 3706:         }
1.583     matthew  3707:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   3708:         # FIXME: We should not be depending on a form parameter that someone
                   3709:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 3710:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  3711:             $what.= ':POST';
                   3712:             # FIXME: Probably ought to escape things....
                   3713:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   3714:                                  'crsdiscuss') {
1.620     albertel 3715:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  3716:             }
                   3717:         }
1.158     www      3718:     }
                   3719:     &courselog($what);
1.149     www      3720: }
                   3721: 
1.185     www      3722: sub countacc {
                   3723:     my $url=&declutter(shift);
1.458     matthew  3724:     return if (! defined($url) || $url eq '');
1.620     albertel 3725:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      3726: #
                   3727: # Mark that this url was used in this course
                   3728: #
1.620     albertel 3729:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      3730: #
                   3731: # Increase the access count for this resource in this child process
                   3732: #
1.281     www      3733:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  3734:     $accesshash{$key}++;
1.185     www      3735: }
1.349     www      3736: 
1.361     www      3737: sub linklog {
                   3738:     my ($from,$to)=@_;
                   3739:     $from=&declutter($from);
                   3740:     $to=&declutter($to);
                   3741:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   3742:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   3743: }
1.1160    www      3744: 
                   3745: sub statslog {
                   3746:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   3747:     if ($users<2) { return; }
                   3748:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   3749:             'course'       => $env{'request.course.id'},
                   3750:             'sections'     => '"all"',
                   3751:             'num_students' => $users,
                   3752:             'part'         => $part,
                   3753:             'symb'         => $symb,
                   3754:             'mean_tries'   => $av_attempts,
                   3755:             'deg_of_diff'  => $degdiff});
                   3756:     foreach my $key (keys(%dynstore)) {
                   3757:         $accesshash{$key}=$dynstore{$key};
                   3758:     }
                   3759: }
1.361     www      3760:   
1.349     www      3761: sub userrolelog {
                   3762:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 3763:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      3764:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3765:        $userrolehash
                   3766:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      3767:                     =$tend.':'.$tstart;
1.662     raeburn  3768:     }
1.1169    droeschl 3769:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 3770:        $userrolehash
                   3771:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   3772:                     =$tend.':'.$tstart;
                   3773:     }
1.1169    droeschl 3774:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662     raeburn  3775:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3776:        $domainrolehash
                   3777:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3778:                     = $tend.':'.$tstart;
                   3779:     }
1.351     www      3780: }
                   3781: 
1.957     raeburn  3782: sub courserolelog {
                   3783:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  3784:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3785:         my $cdom = $1;
                   3786:         my $cnum = $2;
                   3787:         my $sec = $3;
                   3788:         my $namespace = 'rolelog';
                   3789:         my %storehash = (
                   3790:                            role    => $trole,
                   3791:                            start   => $tstart,
                   3792:                            end     => $tend,
                   3793:                            selfenroll => $selfenroll,
                   3794:                            context    => $context,
                   3795:                         );
                   3796:         if ($trole eq 'gr') {
                   3797:             $namespace = 'groupslog';
                   3798:             $storehash{'group'} = $sec;
                   3799:         } else {
                   3800:             $storehash{'section'} = $sec;
                   3801:         }
                   3802:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   3803:                    $domain,$cnum,$cdom);
                   3804:         if (($trole ne 'st') || ($sec ne '')) {
                   3805:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  3806:         }
                   3807:     }
                   3808:     return;
                   3809: }
                   3810: 
1.1172.2.9  raeburn  3811: sub domainrolelog {
                   3812:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   3813:     if ($area =~ m{^/($match_domain)/$}) {
                   3814:         my $cdom = $1;
                   3815:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   3816:         my $namespace = 'rolelog';
                   3817:         my %storehash = (
                   3818:                            role    => $trole,
                   3819:                            start   => $tstart,
                   3820:                            end     => $tend,
                   3821:                            context => $context,
                   3822:                         );
                   3823:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   3824:                    $domain,$domconfiguser,$cdom);
                   3825:     }
                   3826:     return;
                   3827: 
                   3828: }
                   3829: 
                   3830: sub coauthorrolelog {
                   3831:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   3832:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   3833:         my $audom = $1;
                   3834:         my $auname = $2;
                   3835:         my $namespace = 'rolelog';
                   3836:         my %storehash = (
                   3837:                            role    => $trole,
                   3838:                            start   => $tstart,
                   3839:                            end     => $tend,
                   3840:                            context => $context,
                   3841:                         );
                   3842:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   3843:                    $domain,$auname,$audom);
                   3844:     }
                   3845:     return;
                   3846: }
                   3847: 
1.351     www      3848: sub get_course_adv_roles {
1.948     raeburn  3849:     my ($cid,$codes) = @_;
1.620     albertel 3850:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      3851:     my %coursehash=&coursedescription($cid);
1.988     raeburn  3852:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      3853:     my %nothide=();
1.800     albertel 3854:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  3855:         if ($user !~ /:/) {
                   3856: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   3857:         } else {
                   3858:             $nothide{$user}=1;
                   3859:         }
1.470     www      3860:     }
1.351     www      3861:     my %returnhash=();
                   3862:     my %dumphash=
                   3863:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   3864:     my $now=time;
1.997     raeburn  3865:     my %privileged;
1.1000    raeburn  3866:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 3867: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      3868:         if (($tstart) && ($tstart<0)) { next; }
                   3869:         if (($tend) && ($tend<$now)) { next; }
                   3870:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 3871:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 3872: 	if ($username eq '' || $domain eq '') { next; }
1.997     raeburn  3873:         unless (ref($privileged{$domain}) eq 'HASH') {
                   3874:             my %dompersonnel =
1.998     raeburn  3875:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997     raeburn  3876:             $privileged{$domain} = {};
                   3877:             foreach my $server (keys(%dompersonnel)) {
1.999     raeburn  3878:                 if (ref($dompersonnel{$server}) eq 'HASH') {
1.997     raeburn  3879:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3880:                         my ($trole,$uname,$udom) = split(/:/,$user);
                   3881:                         $privileged{$udom}{$uname} = 1;
                   3882:                     }
                   3883:                 }
                   3884:             }
                   3885:         }
                   3886:         if ((exists($privileged{$domain}{$username})) && 
                   3887:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 3888: 	if ($role eq 'cr') { next; }
1.948     raeburn  3889:         if ($codes) {
                   3890:             if ($section) { $role .= ':'.$section; }
                   3891:             if ($returnhash{$role}) {
                   3892:                 $returnhash{$role}.=','.$username.':'.$domain;
                   3893:             } else {
                   3894:                 $returnhash{$role}=$username.':'.$domain;
                   3895:             }
1.351     www      3896:         } else {
1.988     raeburn  3897:             my $key=&plaintext($role,$crstype);
1.973     bisitz   3898:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  3899:             if ($returnhash{$key}) {
                   3900: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   3901:             } else {
                   3902:                 $returnhash{$key}=$username.':'.$domain;
                   3903:             }
1.351     www      3904:         }
1.948     raeburn  3905:     }
1.400     www      3906:     return %returnhash;
                   3907: }
                   3908: 
                   3909: sub get_my_roles {
1.937     raeburn  3910:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 3911:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   3912:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  3913:     my (%dumphash,%nothide);
1.1086    raeburn  3914:     if ($context eq 'userroles') {
1.1166    raeburn  3915:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  3916:     } else {
                   3917:         %dumphash=
1.400     www      3918:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  3919:         if ($hidepriv) {
                   3920:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   3921:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3922:                 if ($user !~ /:/) {
                   3923:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   3924:                 } else {
                   3925:                     $nothide{$user} = 1;
                   3926:                 }
                   3927:             }
                   3928:         }
1.858     raeburn  3929:     }
1.400     www      3930:     my %returnhash=();
                   3931:     my $now=time;
1.999     raeburn  3932:     my %privileged;
1.800     albertel 3933:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  3934:         my ($role,$tend,$tstart);
                   3935:         if ($context eq 'userroles') {
1.1149    raeburn  3936:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  3937: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   3938:         } else {
                   3939:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   3940:         }
1.400     www      3941:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  3942:         my $status = 'active';
1.939     raeburn  3943:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  3944:             $status = 'previous';
                   3945:         } 
                   3946:         if (($tstart) && ($now<$tstart)) {
                   3947:             $status = 'future';
                   3948:         }
                   3949:         if (ref($types) eq 'ARRAY') {
                   3950:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   3951:                 next;
                   3952:             } 
                   3953:         } else {
                   3954:             if ($status ne 'active') {
                   3955:                 next;
                   3956:             }
                   3957:         }
1.867     raeburn  3958:         my ($rolecode,$username,$domain,$section,$area);
                   3959:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  3960:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  3961:             (undef,$domain,$username,$section) = split(/\//,$area);
                   3962:         } else {
                   3963:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   3964:         }
1.832     raeburn  3965:         if (ref($roledoms) eq 'ARRAY') {
                   3966:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   3967:                 next;
                   3968:             }
                   3969:         }
                   3970:         if (ref($roles) eq 'ARRAY') {
                   3971:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  3972:                 if ($role =~ /^cr\//) {
                   3973:                     if (!grep(/^cr$/,@{$roles})) {
                   3974:                         next;
                   3975:                     }
1.1104    raeburn  3976:                 } elsif ($role =~ /^gr\//) {
                   3977:                     if (!grep(/^gr$/,@{$roles})) {
                   3978:                         next;
                   3979:                     }
1.922     raeburn  3980:                 } else {
                   3981:                     next;
                   3982:                 }
1.832     raeburn  3983:             }
1.867     raeburn  3984:         }
1.937     raeburn  3985:         if ($hidepriv) {
1.999     raeburn  3986:             if ($context eq 'userroles') {
                   3987:                 if ((&privileged($username,$domain)) &&
                   3988:                     (!$nothide{$username.':'.$domain})) {
                   3989:                     next;
                   3990:                 }
                   3991:             } else {
                   3992:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   3993:                     my %dompersonnel =
                   3994:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   3995:                     $privileged{$domain} = {};
                   3996:                     if (keys(%dompersonnel)) {
                   3997:                         foreach my $server (keys(%dompersonnel)) {
                   3998:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   3999:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   4000:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   4001:                                     $privileged{$udom}{$uname} = $trole;
                   4002:                                 }
                   4003:                             }
                   4004:                         }
                   4005:                     }
                   4006:                 }
                   4007:                 if (exists($privileged{$domain}{$username})) {
                   4008:                     if (!$nothide{$username.':'.$domain}) {
                   4009:                         next;
                   4010:                     }
                   4011:                 }
1.937     raeburn  4012:             }
                   4013:         }
1.933     raeburn  4014:         if ($withsec) {
                   4015:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4016:                 $tstart.':'.$tend;
                   4017:         } else {
                   4018:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4019:         }
1.832     raeburn  4020:     }
1.373     www      4021:     return %returnhash;
1.399     www      4022: }
                   4023: 
                   4024: # ----------------------------------------------------- Frontpage Announcements
                   4025: #
                   4026: #
                   4027: 
                   4028: sub postannounce {
                   4029:     my ($server,$text)=@_;
1.844     albertel 4030:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4031:     unless ($text=~/\w/) { $text=''; }
                   4032:     return &reply('setannounce:'.&escape($text),$server);
                   4033: }
                   4034: 
                   4035: sub getannounce {
1.448     albertel 4036: 
                   4037:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4038: 	my $announcement='';
1.800     albertel 4039: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4040: 	close($fh);
1.399     www      4041: 	if ($announcement=~/\w/) { 
                   4042: 	    return 
                   4043:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4044:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4045: 	} else {
                   4046: 	    return '';
                   4047: 	}
                   4048:     } else {
                   4049: 	return '';
                   4050:     }
1.351     www      4051: }
1.353     www      4052: 
                   4053: # ---------------------------------------------------------- Course ID routines
                   4054: # Deal with domain's nohist_courseid.db files
                   4055: #
                   4056: 
                   4057: sub courseidput {
1.921     raeburn  4058:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4059:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4060:     my $outcome;
                   4061:     if ($caller eq 'timeonly') {
                   4062:         my $cids = '';
                   4063:         foreach my $item (keys(%$storehash)) {
                   4064:             $cids.=&escape($item).'&';
                   4065:         }
                   4066:         $cids=~s/\&$//;
                   4067:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4068:                           $coursehome);       
                   4069:     } else {
                   4070:         my $items = '';
                   4071:         foreach my $item (keys(%$storehash)) {
                   4072:             $items.= &escape($item).'='.
                   4073:                      &freeze_escape($$storehash{$item}).'&';
                   4074:         }
                   4075:         $items=~s/\&$//;
                   4076:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4077:                           $coursehome);
1.918     raeburn  4078:     }
                   4079:     if ($outcome eq 'unknown_cmd') {
                   4080:         my $what;
                   4081:         foreach my $cid (keys(%$storehash)) {
                   4082:             $what .= &escape($cid).'=';
1.921     raeburn  4083:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4084:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4085:             }
                   4086:             $what =~ s/\:$/&/;
                   4087:         }
                   4088:         $what =~ s/\&$//;  
                   4089:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4090:     } else {
                   4091:         return $outcome;
                   4092:     }
1.353     www      4093: }
                   4094: 
                   4095: sub courseiddump {
1.921     raeburn  4096:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4097:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4098:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071    raeburn  4099:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  4100:     my $as_hash = 1;
                   4101:     my %returnhash;
                   4102:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4103:     my %libserv = &all_library();
                   4104:     foreach my $tryserver (keys(%libserv)) {
                   4105:         if ( (  $hostidflag == 1 
                   4106: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4107: 	     || (!defined($hostidflag)) ) {
                   4108: 
1.918     raeburn  4109: 	    if (($domfilter eq '') ||
                   4110: 		(&host_domain($tryserver) eq $domfilter)) {
                   4111:                 my $rep = 
                   4112:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4113:                          $sincefilter.':'.&escape($descfilter).':'.
                   4114:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   4115:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  4116:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  4117:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008    raeburn  4118:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029    raeburn  4119:                          &escape($cc_clone).':'.$cloneonly.':'.
                   4120:                          &escape($createdbefore).':'.&escape($createdafter).':'.
1.1071    raeburn  4121:                          &escape($creationcontext).':'.$domcloner,
                   4122:                          $tryserver);
1.918     raeburn  4123:                 my @pairs=split(/\&/,$rep);
                   4124:                 foreach my $item (@pairs) {
                   4125:                     my ($key,$value)=split(/\=/,$item,2);
                   4126:                     $key = &unescape($key);
                   4127:                     next if ($key =~ /^error: 2 /);
                   4128:                     my $result = &thaw_unescape($value);
                   4129:                     if (ref($result) eq 'HASH') {
                   4130:                         $returnhash{$key}=$result;
                   4131:                     } else {
1.921     raeburn  4132:                         my @responses = split(/:/,$value);
                   4133:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4134:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4135:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4136:                         }
1.1008    raeburn  4137:                     }
1.353     www      4138:                 }
                   4139:             }
                   4140:         }
                   4141:     }
                   4142:     return %returnhash;
                   4143: }
                   4144: 
1.1055    raeburn  4145: sub courselastaccess {
                   4146:     my ($cdom,$cnum,$hostidref) = @_;
                   4147:     my %returnhash;
                   4148:     if ($cdom && $cnum) {
                   4149:         my $chome = &homeserver($cnum,$cdom);
                   4150:         if ($chome ne 'no_host') {
                   4151:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4152:             &extract_lastaccess(\%returnhash,$rep);
                   4153:         }
                   4154:     } else {
                   4155:         if (!$cdom) { $cdom=''; }
                   4156:         my %libserv = &all_library();
                   4157:         foreach my $tryserver (keys(%libserv)) {
                   4158:             if (ref($hostidref) eq 'ARRAY') {
                   4159:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4160:             } 
                   4161:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4162:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4163:                 &extract_lastaccess(\%returnhash,$rep);
                   4164:             }
                   4165:         }
                   4166:     }
                   4167:     return %returnhash;
                   4168: }
                   4169: 
                   4170: sub extract_lastaccess {
                   4171:     my ($returnhash,$rep) = @_;
                   4172:     if (ref($returnhash) eq 'HASH') {
                   4173:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4174:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4175:                  $rep eq '') {
                   4176:             my @pairs=split(/\&/,$rep);
                   4177:             foreach my $item (@pairs) {
                   4178:                 my ($key,$value)=split(/\=/,$item,2);
                   4179:                 $key = &unescape($key);
                   4180:                 next if ($key =~ /^error: 2 /);
                   4181:                 $returnhash->{$key} = &thaw_unescape($value);
                   4182:             }
                   4183:         }
                   4184:     }
                   4185:     return;
                   4186: }
                   4187: 
1.658     raeburn  4188: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4189: 
                   4190: sub dcmailput {
1.685     raeburn  4191:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4192:     my $status = &Apache::lonnet::critical(
1.740     www      4193:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4194:        &escape($message),$server);
1.662     raeburn  4195:     return $status;
                   4196: }
                   4197: 
1.658     raeburn  4198: sub dcmaildump {
                   4199:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4200:     my %returnhash=();
1.846     albertel 4201: 
                   4202:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4203:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4204:                                                          &escape($enddate).':';
                   4205: 	my @esc_senders=map { &escape($_)} @$senders;
                   4206: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4207: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4208:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4209:             if (($key) && ($value)) {
                   4210:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4211:             }
                   4212:         }
                   4213:     }
                   4214:     return %returnhash;
                   4215: }
1.662     raeburn  4216: # ---------------------------------------------------------- Domain roles
                   4217: 
                   4218: sub get_domain_roles {
                   4219:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4220:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4221:         $startdate = '.';
                   4222:     }
1.1018    raeburn  4223:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4224:         $enddate = '.';
                   4225:     }
1.922     raeburn  4226:     my $rolelist;
                   4227:     if (ref($roles) eq 'ARRAY') {
                   4228:         $rolelist = join(':',@{$roles});
                   4229:     }
1.662     raeburn  4230:     my %personnel = ();
1.841     albertel 4231: 
                   4232:     my %servers = &get_servers($dom,'library');
                   4233:     foreach my $tryserver (keys(%servers)) {
                   4234: 	%{$personnel{$tryserver}}=();
                   4235: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4236: 					    &escape($startdate).':'.
                   4237: 					    &escape($enddate).':'.
                   4238: 					    &escape($rolelist), $tryserver))) {
                   4239: 	    my ($key,$value) = split(/\=/,$line,2);
                   4240: 	    if (($key) && ($value)) {
                   4241: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4242: 	    }
                   4243: 	}
1.662     raeburn  4244:     }
                   4245:     return %personnel;
                   4246: }
1.658     raeburn  4247: 
1.1057    www      4248: # ----------------------------------------------------------- Interval timing 
1.149     www      4249: 
1.1153    www      4250: {
                   4251: # Caches needed for speedup of navmaps
                   4252: # We don't want to cache this for very long at all (5 seconds at most)
                   4253: # 
                   4254: # The user for whom we cache
                   4255: my $cachedkey='';
                   4256: # The cached times for this user
                   4257: my %cachedtimes=();
                   4258: # When this was last done
                   4259: my $cachedtime=();
                   4260: 
                   4261: sub load_all_first_access {
1.1154    raeburn  4262:     my ($uname,$udom)=@_;
1.1156    www      4263:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2  raeburn  4264:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  4265:         return;
                   4266:     }
                   4267:     $cachedtime=time;
                   4268:     $cachedkey=$uname.':'.$udom;
                   4269:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4270: }
                   4271: 
1.504     albertel 4272: sub get_first_access {
1.1162    raeburn  4273:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 4274:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4275:     if ($argsymb) { $symb=$argsymb; }
                   4276:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4277:     if ($argmap) { $map = $argmap; }
1.926     albertel 4278:     if ($type eq 'course') {
                   4279: 	$res='course';
                   4280:     } elsif ($type eq 'map') {
1.588     albertel 4281: 	$res=&symbread($map);
                   4282:     } else {
                   4283: 	$res=$symb;
                   4284:     }
1.1153    www      4285:     &load_all_first_access($uname,$udom);
                   4286:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4287: }
                   4288: 
                   4289: sub set_first_access {
1.1162    raeburn  4290:     my ($type,$interval)=@_;
1.790     albertel 4291:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4292:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4293:     if ($type eq 'course') {
                   4294: 	$res='course';
                   4295:     } elsif ($type eq 'map') {
1.588     albertel 4296: 	$res=&symbread($map);
                   4297:     } else {
                   4298: 	$res=$symb;
                   4299:     }
1.1153    www      4300:     $cachedkey='';
1.1162    raeburn  4301:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4302:     if (!$firstaccess) {
1.1162    raeburn  4303:         my $start = time;
                   4304: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4305:                           $udom,$uname);
                   4306:         if ($putres eq 'ok') {
                   4307:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4308:                  $udom,$uname); 
                   4309:             &appenv(
                   4310:                      {
                   4311:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4312:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4313:                      }
                   4314:                   );
                   4315:         }
                   4316:         return $putres;
1.505     albertel 4317:     }
                   4318:     return 'already_set';
1.504     albertel 4319: }
1.1153    www      4320: }
1.110     www      4321: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4322: 
                   4323: sub expirespread {
                   4324:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4325:     my $cid=$env{'request.course.id'}; 
1.110     www      4326:     if ($cid) {
                   4327:        my $now=time;
                   4328:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4329:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4330:                             $env{'course.'.$cid.'.num'}.
1.110     www      4331: 	        	    ':nohist_expirationdates:'.
                   4332:                             &escape($key).'='.$now,
1.620     albertel 4333:                             $env{'course.'.$cid.'.home'})
1.110     www      4334:     }
                   4335:     return 'ok';
1.14      www      4336: }
                   4337: 
1.109     www      4338: # ----------------------------------------------------- Devalidate Spreadsheets
                   4339: 
                   4340: sub devalidate {
1.325     www      4341:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4342:     my $cid=$env{'request.course.id'}; 
1.109     www      4343:     if ($cid) {
1.391     matthew  4344:         # delete the stored spreadsheets for
                   4345:         # - the student level sheet of this user in course's homespace
                   4346:         # - the assessment level sheet for this resource 
                   4347:         #   for this user in user's homespace
1.553     albertel 4348: 	# - current conditional state info
1.325     www      4349: 	my $key=$uname.':'.$udom.':';
1.109     www      4350:         my $status=
1.299     matthew  4351: 	    &del('nohist_calculatedsheets',
1.391     matthew  4352: 		 [$key.'studentcalc:'],
1.620     albertel 4353: 		 $env{'course.'.$cid.'.domain'},
                   4354: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4355: 		.' '.
                   4356: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4357: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4358:         unless ($status eq 'ok ok') {
                   4359:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4360:                     $uname.' at '.$udom.' for '.
1.109     www      4361: 		    $symb.': '.$status);
1.133     albertel 4362:         }
1.553     albertel 4363: 	&delenv('user.state.'.$cid);
1.109     www      4364:     }
                   4365: }
                   4366: 
1.265     albertel 4367: sub get_scalar {
                   4368:     my ($string,$end) = @_;
                   4369:     my $value;
                   4370:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4371: 	$value = $1;
                   4372:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4373: 	$value = $1;
                   4374:     }
                   4375:     return &unescape($value);
                   4376: }
                   4377: 
                   4378: sub array2str {
                   4379:   my (@array) = @_;
                   4380:   my $result=&arrayref2str(\@array);
                   4381:   $result=~s/^__ARRAY_REF__//;
                   4382:   $result=~s/__END_ARRAY_REF__$//;
                   4383:   return $result;
                   4384: }
                   4385: 
1.204     albertel 4386: sub arrayref2str {
                   4387:   my ($arrayref) = @_;
1.265     albertel 4388:   my $result='__ARRAY_REF__';
1.204     albertel 4389:   foreach my $elem (@$arrayref) {
1.265     albertel 4390:     if(ref($elem) eq 'ARRAY') {
                   4391:       $result.=&arrayref2str($elem).'&';
                   4392:     } elsif(ref($elem) eq 'HASH') {
                   4393:       $result.=&hashref2str($elem).'&';
                   4394:     } elsif(ref($elem)) {
                   4395:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4396:     } else {
                   4397:       $result.=&escape($elem).'&';
                   4398:     }
                   4399:   }
                   4400:   $result=~s/\&$//;
1.265     albertel 4401:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4402:   return $result;
                   4403: }
                   4404: 
1.168     albertel 4405: sub hash2str {
1.204     albertel 4406:   my (%hash) = @_;
                   4407:   my $result=&hashref2str(\%hash);
1.265     albertel 4408:   $result=~s/^__HASH_REF__//;
                   4409:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4410:   return $result;
                   4411: }
                   4412: 
                   4413: sub hashref2str {
                   4414:   my ($hashref)=@_;
1.265     albertel 4415:   my $result='__HASH_REF__';
1.800     albertel 4416:   foreach my $key (sort(keys(%$hashref))) {
                   4417:     if (ref($key) eq 'ARRAY') {
                   4418:       $result.=&arrayref2str($key).'=';
                   4419:     } elsif (ref($key) eq 'HASH') {
                   4420:       $result.=&hashref2str($key).'=';
                   4421:     } elsif (ref($key)) {
1.265     albertel 4422:       $result.='=';
1.800     albertel 4423:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 4424:     } else {
1.1132    raeburn  4425: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 4426:     }
                   4427: 
1.800     albertel 4428:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   4429:       $result.=&arrayref2str($hashref->{$key}).'&';
                   4430:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   4431:       $result.=&hashref2str($hashref->{$key}).'&';
                   4432:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4433:        $result.='&';
1.800     albertel 4434:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4435:     } else {
1.800     albertel 4436:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4437:     }
                   4438:   }
1.168     albertel 4439:   $result=~s/\&$//;
1.265     albertel 4440:   $result .= '__END_HASH_REF__';
1.168     albertel 4441:   return $result;
                   4442: }
                   4443: 
                   4444: sub str2hash {
1.265     albertel 4445:     my ($string)=@_;
                   4446:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4447:     return %$hash;
                   4448: }
                   4449: 
                   4450: sub str2hashref {
1.168     albertel 4451:   my ($string) = @_;
1.265     albertel 4452: 
                   4453:   my %hash;
                   4454: 
                   4455:   if($string !~ /^__HASH_REF__/) {
                   4456:       if (! ($string eq '' || !defined($string))) {
                   4457: 	  $hash{'error'}='Not hash reference';
                   4458:       }
                   4459:       return (\%hash, $string);
                   4460:   }
                   4461: 
                   4462:   $string =~ s/^__HASH_REF__//;
                   4463: 
                   4464:   while($string !~ /^__END_HASH_REF__/) {
                   4465:       #key
                   4466:       my $key='';
                   4467:       if($string =~ /^__HASH_REF__/) {
                   4468:           ($key, $string)=&str2hashref($string);
                   4469:           if(defined($key->{'error'})) {
                   4470:               $hash{'error'}='Bad data';
                   4471:               return (\%hash, $string);
                   4472:           }
                   4473:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4474:           ($key, $string)=&str2arrayref($string);
                   4475:           if($key->[0] eq 'Array reference error') {
                   4476:               $hash{'error'}='Bad data';
                   4477:               return (\%hash, $string);
                   4478:           }
                   4479:       } else {
                   4480:           $string =~ s/^(.*?)=//;
1.267     albertel 4481: 	  $key=&unescape($1);
1.265     albertel 4482:       }
                   4483:       $string =~ s/^=//;
                   4484: 
                   4485:       #value
                   4486:       my $value='';
                   4487:       if($string =~ /^__HASH_REF__/) {
                   4488:           ($value, $string)=&str2hashref($string);
                   4489:           if(defined($value->{'error'})) {
                   4490:               $hash{'error'}='Bad data';
                   4491:               return (\%hash, $string);
                   4492:           }
                   4493:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4494:           ($value, $string)=&str2arrayref($string);
                   4495:           if($value->[0] eq 'Array reference error') {
                   4496:               $hash{'error'}='Bad data';
                   4497:               return (\%hash, $string);
                   4498:           }
                   4499:       } else {
                   4500: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4501:       }
                   4502:       $string =~ s/^&//;
                   4503: 
                   4504:       $hash{$key}=$value;
1.204     albertel 4505:   }
1.265     albertel 4506: 
                   4507:   $string =~ s/^__END_HASH_REF__//;
                   4508: 
                   4509:   return (\%hash, $string);
1.204     albertel 4510: }
                   4511: 
                   4512: sub str2array {
1.265     albertel 4513:     my ($string)=@_;
                   4514:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4515:     return @$array;
                   4516: }
                   4517: 
                   4518: sub str2arrayref {
1.204     albertel 4519:   my ($string) = @_;
1.265     albertel 4520:   my @array;
                   4521: 
                   4522:   if($string !~ /^__ARRAY_REF__/) {
                   4523:       if (! ($string eq '' || !defined($string))) {
                   4524: 	  $array[0]='Array reference error';
                   4525:       }
                   4526:       return (\@array, $string);
                   4527:   }
                   4528: 
                   4529:   $string =~ s/^__ARRAY_REF__//;
                   4530: 
                   4531:   while($string !~ /^__END_ARRAY_REF__/) {
                   4532:       my $value='';
                   4533:       if($string =~ /^__HASH_REF__/) {
                   4534:           ($value, $string)=&str2hashref($string);
                   4535:           if(defined($value->{'error'})) {
                   4536:               $array[0] ='Array reference error';
                   4537:               return (\@array, $string);
                   4538:           }
                   4539:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4540:           ($value, $string)=&str2arrayref($string);
                   4541:           if($value->[0] eq 'Array reference error') {
                   4542:               $array[0] ='Array reference error';
                   4543:               return (\@array, $string);
                   4544:           }
                   4545:       } else {
                   4546: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   4547:       }
                   4548:       $string =~ s/^&//;
                   4549: 
                   4550:       push(@array, $value);
1.191     harris41 4551:   }
1.265     albertel 4552: 
                   4553:   $string =~ s/^__END_ARRAY_REF__//;
                   4554: 
                   4555:   return (\@array, $string);
1.168     albertel 4556: }
                   4557: 
1.167     albertel 4558: # -------------------------------------------------------------------Temp Store
                   4559: 
1.168     albertel 4560: sub tmpreset {
                   4561:   my ($symb,$namespace,$domain,$stuname) = @_;
                   4562:   if (!$symb) {
                   4563:     $symb=&symbread();
1.620     albertel 4564:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4565:   }
                   4566:   $symb=escape($symb);
                   4567: 
1.620     albertel 4568:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 4569:   $namespace=~s/\//\_/g;
                   4570:   $namespace=~s/\W//g;
                   4571: 
1.620     albertel 4572:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4573:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4574:   if ($domain eq 'public' && $stuname eq 'public') {
                   4575:       $stuname=$ENV{'REMOTE_ADDR'};
                   4576:   }
1.1117    foxr     4577:   my $path=LONCAPA::tempdir();
1.168     albertel 4578:   my %hash;
                   4579:   if (tie(%hash,'GDBM_File',
                   4580: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4581: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  4582:     foreach my $key (keys(%hash)) {
1.180     albertel 4583:       if ($key=~ /:$symb/) {
1.168     albertel 4584: 	delete($hash{$key});
                   4585:       }
                   4586:     }
                   4587:   }
                   4588: }
                   4589: 
1.167     albertel 4590: sub tmpstore {
1.168     albertel 4591:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4592: 
                   4593:   if (!$symb) {
                   4594:     $symb=&symbread();
1.620     albertel 4595:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4596:   }
                   4597:   $symb=escape($symb);
                   4598: 
                   4599:   if (!$namespace) {
                   4600:     # I don't think we would ever want to store this for a course.
                   4601:     # it seems this will only be used if we don't have a course.
1.620     albertel 4602:     #$namespace=$env{'request.course.id'};
1.168     albertel 4603:     #if (!$namespace) {
1.620     albertel 4604:       $namespace=$env{'request.state'};
1.168     albertel 4605:     #}
                   4606:   }
                   4607:   $namespace=~s/\//\_/g;
                   4608:   $namespace=~s/\W//g;
1.620     albertel 4609:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4610:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4611:   if ($domain eq 'public' && $stuname eq 'public') {
                   4612:       $stuname=$ENV{'REMOTE_ADDR'};
                   4613:   }
1.168     albertel 4614:   my $now=time;
                   4615:   my %hash;
1.1117    foxr     4616:   my $path=LONCAPA::tempdir();
1.168     albertel 4617:   if (tie(%hash,'GDBM_File',
                   4618: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4619: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 4620:     $hash{"version:$symb"}++;
                   4621:     my $version=$hash{"version:$symb"};
                   4622:     my $allkeys=''; 
                   4623:     foreach my $key (keys(%$storehash)) {
                   4624:       $allkeys.=$key.':';
1.591     albertel 4625:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 4626:     }
                   4627:     $hash{"$version:$symb:timestamp"}=$now;
                   4628:     $allkeys.='timestamp';
                   4629:     $hash{"$version:keys:$symb"}=$allkeys;
                   4630:     if (untie(%hash)) {
                   4631:       return 'ok';
                   4632:     } else {
                   4633:       return "error:$!";
                   4634:     }
                   4635:   } else {
                   4636:     return "error:$!";
                   4637:   }
                   4638: }
1.167     albertel 4639: 
1.168     albertel 4640: # -----------------------------------------------------------------Temp Restore
1.167     albertel 4641: 
1.168     albertel 4642: sub tmprestore {
                   4643:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 4644: 
1.168     albertel 4645:   if (!$symb) {
                   4646:     $symb=&symbread();
1.620     albertel 4647:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4648:   }
                   4649:   $symb=escape($symb);
                   4650: 
1.620     albertel 4651:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 4652: 
1.620     albertel 4653:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4654:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4655:   if ($domain eq 'public' && $stuname eq 'public') {
                   4656:       $stuname=$ENV{'REMOTE_ADDR'};
                   4657:   }
1.168     albertel 4658:   my %returnhash;
                   4659:   $namespace=~s/\//\_/g;
                   4660:   $namespace=~s/\W//g;
                   4661:   my %hash;
1.1117    foxr     4662:   my $path=LONCAPA::tempdir();
1.168     albertel 4663:   if (tie(%hash,'GDBM_File',
                   4664: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4665: 	  &GDBM_READER(),0640)) {
1.168     albertel 4666:     my $version=$hash{"version:$symb"};
                   4667:     $returnhash{'version'}=$version;
                   4668:     my $scope;
                   4669:     for ($scope=1;$scope<=$version;$scope++) {
                   4670:       my $vkeys=$hash{"$scope:keys:$symb"};
                   4671:       my @keys=split(/:/,$vkeys);
                   4672:       my $key;
                   4673:       $returnhash{"$scope:keys"}=$vkeys;
                   4674:       foreach $key (@keys) {
1.591     albertel 4675: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   4676: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 4677:       }
                   4678:     }
1.168     albertel 4679:     if (!(untie(%hash))) {
                   4680:       return "error:$!";
                   4681:     }
                   4682:   } else {
                   4683:     return "error:$!";
                   4684:   }
                   4685:   return %returnhash;
1.167     albertel 4686: }
                   4687: 
1.9       www      4688: # ----------------------------------------------------------------------- Store
                   4689: 
                   4690: sub store {
1.124     www      4691:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4692:     my $home='';
                   4693: 
1.168     albertel 4694:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4695: 
1.213     www      4696:     $symb=&symbclean($symb);
1.122     albertel 4697:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4698: 
1.620     albertel 4699:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4700:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4701: 
                   4702:     &devalidate($symb,$stuname,$domain);
1.109     www      4703: 
                   4704:     $symb=escape($symb);
1.187     www      4705:     if (!$namespace) { 
1.620     albertel 4706:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4707:           return ''; 
                   4708:        } 
                   4709:     }
1.620     albertel 4710:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4711: 
                   4712:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4713:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   4714: 
1.12      www      4715:     my $namevalue='';
1.800     albertel 4716:     foreach my $key (keys(%$storehash)) {
                   4717:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4718:     }
1.12      www      4719:     $namevalue=~s/\&$//;
1.187     www      4720:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      4721:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      4722: }
                   4723: 
1.47      www      4724: # -------------------------------------------------------------- Critical Store
                   4725: 
                   4726: sub cstore {
1.124     www      4727:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4728:     my $home='';
                   4729: 
1.168     albertel 4730:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4731: 
1.213     www      4732:     $symb=&symbclean($symb);
1.122     albertel 4733:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4734: 
1.620     albertel 4735:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4736:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4737: 
                   4738:     &devalidate($symb,$stuname,$domain);
1.109     www      4739: 
                   4740:     $symb=escape($symb);
1.187     www      4741:     if (!$namespace) { 
1.620     albertel 4742:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4743:           return ''; 
                   4744:        } 
                   4745:     }
1.620     albertel 4746:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4747: 
                   4748:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4749:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 4750: 
1.47      www      4751:     my $namevalue='';
1.800     albertel 4752:     foreach my $key (keys(%$storehash)) {
                   4753:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4754:     }
1.47      www      4755:     $namevalue=~s/\&$//;
1.187     www      4756:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      4757:     return critical
                   4758:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      4759: }
                   4760: 
1.9       www      4761: # --------------------------------------------------------------------- Restore
                   4762: 
                   4763: sub restore {
1.124     www      4764:     my ($symb,$namespace,$domain,$stuname) = @_;
                   4765:     my $home='';
                   4766: 
1.168     albertel 4767:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4768: 
1.122     albertel 4769:     if (!$symb) {
                   4770:       unless ($symb=escape(&symbread())) { return ''; }
                   4771:     } else {
1.213     www      4772:       $symb=&escape(&symbclean($symb));
1.122     albertel 4773:     }
1.188     www      4774:     if (!$namespace) { 
1.620     albertel 4775:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      4776:           return ''; 
                   4777:        } 
                   4778:     }
1.620     albertel 4779:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4780:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   4781:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 4782:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   4783: 
1.12      www      4784:     my %returnhash=();
1.800     albertel 4785:     foreach my $line (split(/\&/,$answer)) {
                   4786: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 4787:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 4788:     }
1.75      www      4789:     my $version;
                   4790:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 4791:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   4792:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 4793:        }
1.75      www      4794:     }
1.13      www      4795:     return %returnhash;
1.34      www      4796: }
                   4797: 
                   4798: # ---------------------------------------------------------- Course Description
1.1118    foxr     4799: #
                   4800: #  
1.34      www      4801: 
                   4802: sub coursedescription {
1.731     albertel 4803:     my ($courseid,$args)=@_;
1.34      www      4804:     $courseid=~s/^\///;
1.49      www      4805:     $courseid=~s/\_/\//g;
1.34      www      4806:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 4807:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 4808:     my $normalid=$cdomain.'_'.$cnum;
                   4809:     # need to always cache even if we get errors otherwise we keep 
                   4810:     # trying and trying and trying to get the course description.
                   4811:     my %envhash=();
                   4812:     my %returnhash=();
1.731     albertel 4813:     
                   4814:     my $expiretime=600;
                   4815:     if ($env{'request.course.id'} eq $normalid) {
                   4816: 	$expiretime=120;
                   4817:     }
                   4818: 
                   4819:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   4820:     if (!$args->{'freshen_cache'}
                   4821: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   4822: 	foreach my $key (keys(%env)) {
                   4823: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   4824: 	    my ($setting) = $1;
                   4825: 	    $returnhash{$setting} = $env{$key};
                   4826: 	}
                   4827: 	return %returnhash;
                   4828:     }
                   4829: 
1.1118    foxr     4830:     # get the data again
                   4831: 
1.731     albertel 4832:     if (!$args->{'one_time'}) {
                   4833: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   4834:     }
1.811     albertel 4835: 
1.34      www      4836:     if ($chome ne 'no_host') {
1.302     albertel 4837:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 4838:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     4839: 	   my $username = $env{'user.name'}; # Defult username
                   4840: 	   if(defined $args->{'user'}) {
                   4841: 	       $username = $args->{'user'};
                   4842: 	   }
1.129     albertel 4843:            $returnhash{'home'}= $chome;
                   4844: 	   $returnhash{'domain'} = $cdomain;
                   4845: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  4846:            if (!defined($returnhash{'type'})) {
                   4847:                $returnhash{'type'} = 'Course';
                   4848:            }
1.130     albertel 4849:            while (my ($name,$value) = each %returnhash) {
1.53      www      4850:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 4851:            }
1.270     www      4852:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     4853:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     4854: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      4855:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   4856:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   4857:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      4858:        }
                   4859:     }
1.731     albertel 4860:     if (!$args->{'one_time'}) {
1.949     raeburn  4861: 	&appenv(\%envhash);
1.731     albertel 4862:     }
1.302     albertel 4863:     return %returnhash;
1.461     www      4864: }
                   4865: 
1.1080    raeburn  4866: sub update_released_required {
                   4867:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   4868:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   4869:         $cid = $env{'request.course.id'};
                   4870:         $cdom = $env{'course.'.$cid.'.domain'};
                   4871:         $cnum = $env{'course.'.$cid.'.num'};
                   4872:         $chome = $env{'course.'.$cid.'.home'};
                   4873:     }
                   4874:     if ($needsrelease) {
                   4875:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   4876:         my $needsupdate;
                   4877:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   4878:             $needsupdate = 1;
                   4879:         } else {
                   4880:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   4881:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   4882:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   4883:                 $needsupdate = 1;
                   4884:             }
                   4885:         }
                   4886:         if ($needsupdate) {
                   4887:             my %needshash = (
                   4888:                              'internal.releaserequired' => $needsrelease,
                   4889:                             );
                   4890:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   4891:             if ($putresult eq 'ok') {
                   4892:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   4893:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   4894:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   4895:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   4896:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   4897:                 }
                   4898:             }
                   4899:         }
                   4900:     }
                   4901:     return;
                   4902: }
                   4903: 
1.461     www      4904: # -------------------------------------------------See if a user is privileged
                   4905: 
                   4906: sub privileged {
                   4907:     my ($username,$domain)=@_;
1.1170    droeschl 4908: 
                   4909:     my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   4910:     my $now = time;
                   4911: 
                   4912:     for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
                   4913:             my ($trole, $tend, $tstart) = split(/_/, $role);
                   4914:             if (($trole eq 'dc') || ($trole eq 'su')) {
                   4915:                 return 1 unless ($tend && $tend < $now) 
                   4916:                     or ($tstart && $tstart > $now);
                   4917:             }
1.461     www      4918: 	}
1.1170    droeschl 4919: 
1.461     www      4920:     return 0;
1.9       www      4921: }
1.1       albertel 4922: 
1.103     harris41 4923: # -------------------------------------------------------- Get user privileges
1.11      www      4924: 
                   4925: sub rolesinit {
1.1169    droeschl 4926:     my ($domain, $username) = @_;
                   4927:     my %userroles = ('user.login.time' => time);
                   4928:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   4929: 
                   4930:     # firstaccess and timerinterval are related to timed maps/resources. 
                   4931:     # also, blocking can be triggered by an activating timer
                   4932:     # it's saved in the user's %env.
                   4933:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   4934:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   4935:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   4936:         %timerintchk, %timerintenv);
                   4937: 
1.1162    raeburn  4938:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 4939:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  4940:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   4941:     }
1.1169    droeschl 4942: 
1.1162    raeburn  4943:     foreach my $key (keys(%timerinterval)) {
                   4944:         my ($cid,$rest) = split(/\0/,$key);
                   4945:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   4946:     }
1.1169    droeschl 4947: 
1.11      www      4948:     my %allroles=();
1.1162    raeburn  4949:     my %allgroups=();
1.11      www      4950: 
1.1169    droeschl 4951:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
                   4952:         my $role = $rolesdump{$area};
                   4953:         $area =~ s/\_\w\w$//;
                   4954: 
                   4955:         my ($trole, $tend, $tstart, $group_privs);
                   4956: 
                   4957:         if ($role =~ /^cr/) {
                   4958:         # Custom role, defined by a user 
                   4959:         # e.g., user.role.cr/msu/smith/mynewrole
                   4960:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   4961:                 $trole = $1;
                   4962:                 ($tend, $tstart) = split('_', $2);
                   4963:             } else {
                   4964:                 $trole = $role;
                   4965:             }
                   4966:         } elsif ($role =~ m|^gr/|) {
                   4967:         # Role of member in a group, defined within a course/community
                   4968:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   4969:             ($trole, $tend, $tstart) = split(/_/, $role);
                   4970:             next if $tstart eq '-1';
                   4971:             ($trole, $group_privs) = split(/\//, $trole);
                   4972:             $group_privs = &unescape($group_privs);
                   4973:         } else {
                   4974:         # Just a normal role, defined in roles.tab
                   4975:             ($trole, $tend, $tstart) = split(/_/,$role);
                   4976:         }
                   4977: 
                   4978:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   4979:                  $username);
                   4980:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   4981: 
                   4982:         # role expired or not available yet?
                   4983:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   4984:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   4985: 
                   4986:         next if $area eq '' or $trole eq '';
                   4987: 
                   4988:         my $spec = "$trole.$area";
                   4989:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   4990: 
                   4991:         if ($trole =~ /^cr\//) {
                   4992:         # Custom role, defined by a user
                   4993:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   4994:         } elsif ($trole eq 'gr') {
                   4995:         # Role of a member in a group, defined within a course/community
                   4996:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   4997:             next;
                   4998:         } else {
                   4999:         # Normal role, defined in roles.tab
                   5000:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5001:         }
                   5002: 
                   5003:         my $cid = $tdomain.'_'.$trest;
                   5004:         unless ($firstaccchk{$cid}) {
                   5005:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5006:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5007:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5008:                         $coursetimerstarts{$cid}{$item}; 
                   5009:                 }
                   5010:             }
                   5011:             $firstaccchk{$cid} = 1;
                   5012:         }
                   5013:         unless ($timerintchk{$cid}) {
                   5014:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5015:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5016:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5017:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5018:                 }
1.12      www      5019:             }
1.1169    droeschl 5020:             $timerintchk{$cid} = 1;
1.191     harris41 5021:         }
1.11      www      5022:     }
1.1169    droeschl 5023: 
                   5024:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
                   5025:         \%allroles, \%allgroups);
                   5026:     $env{'user.adv'} = $userroles{'user.adv'};
                   5027: 
1.1162    raeburn  5028:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5029: }
                   5030: 
1.567     raeburn  5031: sub set_arearole {
                   5032:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   5033: # log the associated role with the area
                   5034:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 5035:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5036: }
                   5037: 
                   5038: sub custom_roleprivs {
                   5039:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5040:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   5041:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 5042:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5043:         my ($rdummy,$roledef)=
                   5044:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5045:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5046:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5047:             if (defined($syspriv)) {
1.1043    raeburn  5048:                 if ($trest =~ /^$match_community$/) {
                   5049:                     $syspriv =~ s/bre\&S//; 
                   5050:                 }
1.567     raeburn  5051:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5052:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5053:             }
                   5054:             if ($tdomain ne '') {
                   5055:                 if (defined($dompriv)) {
                   5056:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5057:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5058:                 }
                   5059:                 if (($trest ne '') && (defined($coursepriv))) {
                   5060:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5061:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5062:                 }
                   5063:             }
                   5064:         }
                   5065:     }
                   5066: }
                   5067: 
1.678     raeburn  5068: sub group_roleprivs {
                   5069:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   5070:     my $access = 1;
                   5071:     my $now = time;
                   5072:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   5073:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   5074:     if ($access) {
1.811     albertel 5075:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  5076:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   5077:     }
                   5078: }
1.567     raeburn  5079: 
                   5080: sub standard_roleprivs {
                   5081:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   5082:     if (defined($pr{$trole.':s'})) {
                   5083:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   5084:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   5085:     }
                   5086:     if ($tdomain ne '') {
                   5087:         if (defined($pr{$trole.':d'})) {
                   5088:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5089:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5090:         }
                   5091:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   5092:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   5093:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   5094:         }
                   5095:     }
                   5096: }
                   5097: 
                   5098: sub set_userprivs {
1.1064    raeburn  5099:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  5100:     my $author=0;
                   5101:     my $adv=0;
1.678     raeburn  5102:     my %grouproles = ();
                   5103:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  5104:         my @groupkeys; 
1.1000    raeburn  5105:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  5106:             push(@groupkeys,$role);
                   5107:         }
                   5108:         if (ref($groups_roles) eq 'HASH') {
                   5109:             foreach my $key (keys(%{$groups_roles})) {
                   5110:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   5111:                     push(@groupkeys,$key);
                   5112:                 }
                   5113:             }
                   5114:         }
                   5115:         if (@groupkeys > 0) {
                   5116:             foreach my $role (@groupkeys) {
                   5117:                 my ($trole,$area,$sec,$extendedarea);
                   5118:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   5119:                     $trole = $1;
                   5120:                     $area = $2;
                   5121:                     $sec = $3;
                   5122:                     $extendedarea = $area.$sec;
                   5123:                     if (exists($$allgroups{$area})) {
                   5124:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   5125:                             my $spec = $trole.'.'.$extendedarea;
                   5126:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  5127:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  5128:                         }
1.678     raeburn  5129:                     }
                   5130:                 }
                   5131:             }
                   5132:         }
                   5133:     }
1.800     albertel 5134:     foreach my $group (keys(%grouproles)) {
                   5135:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  5136:     }
1.800     albertel 5137:     foreach my $role (keys(%{$allroles})) {
                   5138:         my %thesepriv;
1.941     raeburn  5139:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 5140:         foreach my $item (split(/:/,$$allroles{$role})) {
                   5141:             if ($item ne '') {
                   5142:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  5143:                 if ($restrictions eq '') {
                   5144:                     $thesepriv{$privilege}='F';
                   5145:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   5146:                     $thesepriv{$privilege}.=$restrictions;
                   5147:                 }
                   5148:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   5149:             }
                   5150:         }
                   5151:         my $thesestr='';
1.1104    raeburn  5152:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 5153: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   5154: 	}
                   5155:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  5156:     }
                   5157:     return ($author,$adv);
                   5158: }
                   5159: 
1.994     raeburn  5160: sub role_status {
1.1104    raeburn  5161:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  5162:     my @pwhere = ();
                   5163:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   5164:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   5165:         unless (!defined($$role) || $$role eq '') {
                   5166:             $$where=join('.',@pwhere);
                   5167:             $$trolecode=$$role.'.'.$$where;
                   5168:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   5169:             $$tstatus='is';
1.1104    raeburn  5170:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  5171:                 $$tstatus='future';
1.1034    raeburn  5172:                 if ($$tstart<$now) {
                   5173:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  5174:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  5175:                             my (%allroles,%allgroups,$group_privs,
                   5176:                                 %groups_roles,@rolecodes);
1.1002    raeburn  5177:                             my %userroles = (
                   5178:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   5179:                             );
1.1064    raeburn  5180:                             @rolecodes = ('cm'); 
1.1002    raeburn  5181:                             my $spec=$$role.'.'.$$where;
                   5182:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   5183:                             if ($$role =~ /^cr\//) {
                   5184:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  5185:                                 push(@rolecodes,'cr');
1.1002    raeburn  5186:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  5187:                                 push(@rolecodes,$$role);
1.1002    raeburn  5188:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   5189:                                                     $env{'user.name'});
1.1064    raeburn  5190:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  5191:                                 (undef,my $group_privs) = split(/\//,$trole);
                   5192:                                 $group_privs = &unescape($group_privs);
                   5193:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  5194:                                 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  5195:                                 &get_groups_roles($tdomain,$trest,
                   5196:                                                   \%course_roles,\@rolecodes,
                   5197:                                                   \%groups_roles);
1.1002    raeburn  5198:                             } else {
1.1064    raeburn  5199:                                 push(@rolecodes,$$role);
1.1002    raeburn  5200:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   5201:                             }
1.1064    raeburn  5202:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   5203:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  5204:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   5205:                         }
                   5206:                     }
1.1034    raeburn  5207:                     $$tstatus = 'is';
1.1002    raeburn  5208:                 }
1.994     raeburn  5209:             }
                   5210:             if ($$tend) {
1.1104    raeburn  5211:                 if ($$tend<$update) {
1.994     raeburn  5212:                     $$tstatus='expired';
                   5213:                 } elsif ($$tend<$now) {
                   5214:                     $$tstatus='will_not';
                   5215:                 }
                   5216:             }
                   5217:         }
                   5218:     }
                   5219: }
                   5220: 
1.1104    raeburn  5221: sub get_groups_roles {
                   5222:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   5223:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   5224:                   (ref($rolecodes) eq 'ARRAY') && 
                   5225:                   (ref($groups_roles) eq 'HASH')); 
                   5226:     if (keys(%{$cdom_courseroles}) > 0) {
                   5227:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   5228:         if ($cdom ne '' && $cnum ne '') {
                   5229:             foreach my $key (keys(%{$cdom_courseroles})) {
                   5230:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   5231:                     my $crsrole = $1;
                   5232:                     my $crssec = $2;
                   5233:                     if ($crsrole =~ /^cr/) {
                   5234:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   5235:                             push(@{$rolecodes},'cr');
                   5236:                         }
                   5237:                     } else {
                   5238:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   5239:                             push(@{$rolecodes},$crsrole);
                   5240:                         }
                   5241:                     }
                   5242:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   5243:                     if ($crssec ne '') {
                   5244:                         $rolekey .= "/$crssec";
                   5245:                     }
                   5246:                     $rolekey .= './';
                   5247:                     $groups_roles->{$rolekey} = $rolecodes;
                   5248:                 }
                   5249:             }
                   5250:         }
                   5251:     }
                   5252:     return;
                   5253: }
                   5254: 
                   5255: sub delete_env_groupprivs {
                   5256:     my ($where,$courseroles,$possroles) = @_;
                   5257:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   5258:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   5259:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   5260:         %{$courseroles->{$udom}} =
                   5261:             &get_my_roles('','','userroles',['active'],
                   5262:                           $possroles,[$udom],1);
                   5263:     }
                   5264:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   5265:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   5266:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   5267:             my $area = '/'.$cdom.'/'.$cnum;
                   5268:             my $privkey = "user.priv.$crsrole.$area";
                   5269:             if ($crssec ne '') {
                   5270:                 $privkey .= '/'.$crssec;
                   5271:             }
                   5272:             $privkey .= ".$area/$group";
                   5273:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   5274:         }
                   5275:     }
                   5276:     return;
                   5277: }
                   5278: 
1.994     raeburn  5279: sub check_adhoc_privs {
1.1104    raeburn  5280:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  5281:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.9  raeburn  5282:     my $setprivs;
1.994     raeburn  5283:     if ($env{$cckey}) {
                   5284:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  5285:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  5286:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  5287:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9  raeburn  5288:             $setprivs = 1;
1.994     raeburn  5289:         }
                   5290:     } else {
1.1088    raeburn  5291:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9  raeburn  5292:         $setprivs = 1;
1.994     raeburn  5293:     }
1.1172.2.9  raeburn  5294:     return $setprivs;
1.994     raeburn  5295: }
                   5296: 
                   5297: sub set_adhoc_privileges {
                   5298: # role can be cc or ca
1.1088    raeburn  5299:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  5300:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   5301:     my $spec = $role.'.'.$area;
                   5302:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
                   5303:                                   $env{'user.name'});
                   5304:     my %ccrole = ();
                   5305:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   5306:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   5307:     &appenv(\%userroles,[$role,'cm']);
                   5308:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  5309:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   5310:         &appenv( {'request.role'        => $spec,
                   5311:                   'request.role.domain' => $dcdom,
                   5312:                   'request.course.sec'  => ''
                   5313:                  }
                   5314:                );
                   5315:         my $tadv=0;
                   5316:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   5317:         &appenv({'request.role.adv'    => $tadv});
                   5318:     }
1.994     raeburn  5319: }
                   5320: 
1.12      www      5321: # --------------------------------------------------------------- get interface
                   5322: 
                   5323: sub get {
1.131     albertel 5324:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5325:    my $items='';
1.800     albertel 5326:    foreach my $item (@$storearr) {
                   5327:        $items.=&escape($item).'&';
1.191     harris41 5328:    }
1.12      www      5329:    $items=~s/\&$//;
1.620     albertel 5330:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5331:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 5332:    my $uhome=&homeserver($uname,$udomain);
                   5333: 
1.133     albertel 5334:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5335:    my @pairs=split(/\&/,$rep);
1.273     albertel 5336:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   5337:      return @pairs;
                   5338:    }
1.15      www      5339:    my %returnhash=();
1.42      www      5340:    my $i=0;
1.800     albertel 5341:    foreach my $item (@$storearr) {
                   5342:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5343:       $i++;
1.191     harris41 5344:    }
1.15      www      5345:    return %returnhash;
1.27      www      5346: }
                   5347: 
                   5348: # --------------------------------------------------------------- del interface
                   5349: 
                   5350: sub del {
1.133     albertel 5351:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      5352:    my $items='';
1.800     albertel 5353:    foreach my $item (@$storearr) {
                   5354:        $items.=&escape($item).'&';
1.191     harris41 5355:    }
1.984     neumanie 5356: 
1.27      www      5357:    $items=~s/\&$//;
1.620     albertel 5358:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5359:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5360:    my $uhome=&homeserver($uname,$udomain);
                   5361:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5362: }
                   5363: 
                   5364: # -------------------------------------------------------------- dump interface
                   5365: 
                   5366: sub dump {
1.1166    raeburn  5367:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.755     albertel 5368:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5369:     if (!$uname) { $uname=$env{'user.name'}; }
                   5370:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 5371: 
1.755     albertel 5372:     if ($regexp) {
                   5373: 	$regexp=&escape($regexp);
                   5374:     } else {
                   5375: 	$regexp='.';
                   5376:     }
1.1166    raeburn  5377:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 5378:     my @pairs=split(/\&/,$rep);
                   5379:     my %returnhash=();
1.1098    foxr     5380:     if (!($rep =~ /^error/ )) {
                   5381: 	foreach my $item (@pairs) {
                   5382: 	    my ($key,$value)=split(/=/,$item,2);
                   5383: 	    $key = &unescape($key);
                   5384: 	    next if ($key =~ /^error: 2 /);
                   5385: 	    $returnhash{$key}=&thaw_unescape($value);
                   5386: 	}
1.755     albertel 5387:     }
                   5388:     return %returnhash;
1.407     www      5389: }
                   5390: 
1.1098    foxr     5391: 
1.717     albertel 5392: # --------------------------------------------------------- dumpstore interface
                   5393: 
                   5394: sub dumpstore {
                   5395:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 5396:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5397:    if (!$uname) { $uname=$env{'user.name'}; }
                   5398:    my $uhome=&homeserver($uname,$udomain);
                   5399:    if ($regexp) {
                   5400:        $regexp=&escape($regexp);
                   5401:    } else {
                   5402:        $regexp='.';
                   5403:    }
                   5404:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   5405:    my @pairs=split(/\&/,$rep);
                   5406:    my %returnhash=();
                   5407:    foreach my $item (@pairs) {
                   5408:        my ($key,$value)=split(/=/,$item,2);
                   5409:        next if ($key =~ /^error: 2 /);
                   5410:        $returnhash{$key}=&thaw_unescape($value);
                   5411:    }
                   5412:    return %returnhash;
1.717     albertel 5413: }
                   5414: 
1.407     www      5415: # -------------------------------------------------------------- keys interface
                   5416: 
                   5417: sub getkeys {
                   5418:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 5419:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5420:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      5421:    my $uhome=&homeserver($uname,$udomain);
                   5422:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   5423:    my @keyarray=();
1.800     albertel 5424:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  5425:       next if ($key =~ /^error: 2 /);
1.800     albertel 5426:       push(@keyarray,&unescape($key));
1.407     www      5427:    }
                   5428:    return @keyarray;
1.318     matthew  5429: }
                   5430: 
1.319     matthew  5431: # --------------------------------------------------------------- currentdump
                   5432: sub currentdump {
1.328     matthew  5433:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 5434:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   5435:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   5436:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  5437:    my $uhome = &homeserver($sname,$sdom);
                   5438:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  5439:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  5440:    #
1.318     matthew  5441:    my %returnhash=();
1.319     matthew  5442:    #
                   5443:    if ($rep eq "unknown_cmd") { 
                   5444:        # an old lond will not know currentdump
                   5445:        # Do a dump and make it look like a currentdump
1.822     albertel 5446:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  5447:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   5448:        my %hash = @tmp;
                   5449:        @tmp=();
1.424     matthew  5450:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  5451:    } else {
                   5452:        my @pairs=split(/\&/,$rep);
1.800     albertel 5453:        foreach my $pair (@pairs) {
                   5454:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  5455:            my ($symb,$param) = split(/:/,$key);
                   5456:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 5457:                                                         &thaw_unescape($value);
1.319     matthew  5458:        }
1.191     harris41 5459:    }
1.12      www      5460:    return %returnhash;
1.424     matthew  5461: }
                   5462: 
                   5463: sub convert_dump_to_currentdump{
                   5464:     my %hash = %{shift()};
                   5465:     my %returnhash;
                   5466:     # Code ripped from lond, essentially.  The only difference
                   5467:     # here is the unescaping done by lonnet::dump().  Conceivably
                   5468:     # we might run in to problems with parameter names =~ /^v\./
                   5469:     while (my ($key,$value) = each(%hash)) {
                   5470:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 5471: 	$symb  = &unescape($symb);
                   5472: 	$param = &unescape($param);
1.424     matthew  5473:         next if ($v eq 'version' || $symb eq 'keys');
                   5474:         next if (exists($returnhash{$symb}) &&
                   5475:                  exists($returnhash{$symb}->{$param}) &&
                   5476:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   5477:         $returnhash{$symb}->{$param}=$value;
                   5478:         $returnhash{$symb}->{'v.'.$param}=$v;
                   5479:     }
                   5480:     #
                   5481:     # Remove all of the keys in the hashes which keep track of
                   5482:     # the version of the parameter.
                   5483:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   5484:         # use a foreach because we are going to delete from the hash.
                   5485:         foreach my $key (keys(%$param_hash)) {
                   5486:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   5487:         }
                   5488:     }
                   5489:     return \%returnhash;
1.12      www      5490: }
                   5491: 
1.627     albertel 5492: # ------------------------------------------------------ critical inc interface
                   5493: 
                   5494: sub cinc {
                   5495:     return &inc(@_,'critical');
                   5496: }
                   5497: 
1.449     matthew  5498: # --------------------------------------------------------------- inc interface
                   5499: 
                   5500: sub inc {
1.627     albertel 5501:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 5502:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5503:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  5504:     my $uhome=&homeserver($uname,$udomain);
                   5505:     my $items='';
                   5506:     if (! ref($store)) {
                   5507:         # got a single value, so use that instead
                   5508:         $items = &escape($store).'=&';
                   5509:     } elsif (ref($store) eq 'SCALAR') {
                   5510:         $items = &escape($$store).'=&';        
                   5511:     } elsif (ref($store) eq 'ARRAY') {
                   5512:         $items = join('=&',map {&escape($_);} @{$store});
                   5513:     } elsif (ref($store) eq 'HASH') {
                   5514:         while (my($key,$value) = each(%{$store})) {
                   5515:             $items.= &escape($key).'='.&escape($value).'&';
                   5516:         }
                   5517:     }
                   5518:     $items=~s/\&$//;
1.627     albertel 5519:     if ($critical) {
                   5520: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5521:     } else {
                   5522: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5523:     }
1.449     matthew  5524: }
                   5525: 
1.12      www      5526: # --------------------------------------------------------------- put interface
                   5527: 
                   5528: sub put {
1.134     albertel 5529:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5530:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5531:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5532:    my $uhome=&homeserver($uname,$udomain);
1.12      www      5533:    my $items='';
1.800     albertel 5534:    foreach my $item (keys(%$storehash)) {
                   5535:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5536:    }
1.12      www      5537:    $items=~s/\&$//;
1.134     albertel 5538:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      5539: }
                   5540: 
1.631     albertel 5541: # ------------------------------------------------------------ newput interface
                   5542: 
                   5543: sub newput {
                   5544:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   5545:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5546:    if (!$uname) { $uname=$env{'user.name'}; }
                   5547:    my $uhome=&homeserver($uname,$udomain);
                   5548:    my $items='';
                   5549:    foreach my $key (keys(%$storehash)) {
                   5550:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   5551:    }
                   5552:    $items=~s/\&$//;
                   5553:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   5554: }
                   5555: 
                   5556: # ---------------------------------------------------------  putstore interface
                   5557: 
1.524     raeburn  5558: sub putstore {
1.715     albertel 5559:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 5560:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5561:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  5562:    my $uhome=&homeserver($uname,$udomain);
                   5563:    my $items='';
1.715     albertel 5564:    foreach my $key (keys(%$storehash)) {
                   5565:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  5566:    }
1.715     albertel 5567:    $items=~s/\&$//;
1.716     albertel 5568:    my $esc_symb=&escape($symb);
                   5569:    my $esc_v=&escape($version);
1.715     albertel 5570:    my $reply =
1.716     albertel 5571:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 5572: 	      $uhome);
                   5573:    if ($reply eq 'unknown_cmd') {
1.716     albertel 5574:        # gfall back to way things use to be done
1.715     albertel 5575:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   5576: 			    $uname);
1.524     raeburn  5577:    }
1.715     albertel 5578:    return $reply;
                   5579: }
                   5580: 
                   5581: sub old_putstore {
1.716     albertel 5582:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   5583:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5584:     if (!$uname) { $uname=$env{'user.name'}; }
                   5585:     my $uhome=&homeserver($uname,$udomain);
                   5586:     my %newstorehash;
1.800     albertel 5587:     foreach my $item (keys(%$storehash)) {
                   5588: 	my $key = $version.':'.&escape($symb).':'.$item;
                   5589: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 5590:     }
                   5591:     my $items='';
                   5592:     my %allitems = ();
1.800     albertel 5593:     foreach my $item (keys(%newstorehash)) {
                   5594: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 5595: 	    my $key = $1.':keys:'.$2;
                   5596: 	    $allitems{$key} .= $3.':';
                   5597: 	}
1.800     albertel 5598: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 5599:     }
1.800     albertel 5600:     foreach my $item (keys(%allitems)) {
                   5601: 	$allitems{$item} =~ s/\:$//;
                   5602: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 5603:     }
                   5604:     $items=~s/\&$//;
                   5605:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  5606: }
                   5607: 
1.47      www      5608: # ------------------------------------------------------ critical put interface
                   5609: 
                   5610: sub cput {
1.134     albertel 5611:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5612:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5613:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5614:    my $uhome=&homeserver($uname,$udomain);
1.47      www      5615:    my $items='';
1.800     albertel 5616:    foreach my $item (keys(%$storehash)) {
                   5617:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5618:    }
1.47      www      5619:    $items=~s/\&$//;
1.134     albertel 5620:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5621: }
                   5622: 
                   5623: # -------------------------------------------------------------- eget interface
                   5624: 
                   5625: sub eget {
1.133     albertel 5626:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5627:    my $items='';
1.800     albertel 5628:    foreach my $item (@$storearr) {
                   5629:        $items.=&escape($item).'&';
1.191     harris41 5630:    }
1.12      www      5631:    $items=~s/\&$//;
1.620     albertel 5632:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5633:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5634:    my $uhome=&homeserver($uname,$udomain);
                   5635:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5636:    my @pairs=split(/\&/,$rep);
                   5637:    my %returnhash=();
1.42      www      5638:    my $i=0;
1.800     albertel 5639:    foreach my $item (@$storearr) {
                   5640:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5641:       $i++;
1.191     harris41 5642:    }
1.12      www      5643:    return %returnhash;
                   5644: }
                   5645: 
1.667     albertel 5646: # ------------------------------------------------------------ tmpput interface
                   5647: sub tmpput {
1.802     raeburn  5648:     my ($storehash,$server,$context)=@_;
1.667     albertel 5649:     my $items='';
1.800     albertel 5650:     foreach my $item (keys(%$storehash)) {
                   5651: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 5652:     }
                   5653:     $items=~s/\&$//;
1.802     raeburn  5654:     if (defined($context)) {
                   5655:         $items .= ':'.&escape($context);
                   5656:     }
1.667     albertel 5657:     return &reply("tmpput:$items",$server);
                   5658: }
                   5659: 
                   5660: # ------------------------------------------------------------ tmpget interface
                   5661: sub tmpget {
1.688     albertel 5662:     my ($token,$server)=@_;
                   5663:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5664:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 5665:     my %returnhash;
                   5666:     foreach my $item (split(/\&/,$rep)) {
                   5667: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  5668:         next if ($key =~ /^error: 2 /);
1.667     albertel 5669: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   5670:     }
                   5671:     return %returnhash;
                   5672: }
                   5673: 
1.1113    raeburn  5674: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 5675: sub tmpdel {
                   5676:     my ($token,$server)=@_;
                   5677:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5678:     return &reply("tmpdel:$token",$server);
                   5679: }
                   5680: 
1.1172.2.13! raeburn  5681: # ------------------------------------------------------------ get_timebased_id
        !          5682: 
        !          5683: sub get_timebased_id {
        !          5684:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
        !          5685:         $maxtries) = @_;
        !          5686:     my ($newid,$error,$dellock);
        !          5687:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
        !          5688:         return ('','ok','invalid call to get suffix');
        !          5689:     }
        !          5690: 
        !          5691: # set defaults for any optional args for which values were not supplied
        !          5692:     if ($who eq '') {
        !          5693:         $who = $env{'user.name'}.':'.$env{'user.domain'};
        !          5694:     }
        !          5695:     if (!$locktries) {
        !          5696:         $locktries = 3;
        !          5697:     }
        !          5698:     if (!$maxtries) {
        !          5699:         $maxtries = 10;
        !          5700:     }
        !          5701: 
        !          5702:     if (($cdom eq '') || ($cnum eq '')) {
        !          5703:         if ($env{'request.course.id'}) {
        !          5704:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
        !          5705:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
        !          5706:         }
        !          5707:         if (($cdom eq '') || ($cnum eq '')) {
        !          5708:             return ('','ok','call to get suffix not in course context');
        !          5709:         }
        !          5710:     }
        !          5711: 
        !          5712: # construct locking item
        !          5713:     my $lockhash = {
        !          5714:                       $prefix."\0".'locked_'.$keyid => $who,
        !          5715:                    };
        !          5716:     my $tries = 0;
        !          5717: 
        !          5718: # attempt to get lock on nohist_$namespace file
        !          5719:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
        !          5720:     while (($gotlock ne 'ok') && $tries <$locktries) {
        !          5721:         $tries ++;
        !          5722:         sleep 1;
        !          5723:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
        !          5724:     }
        !          5725: 
        !          5726: # attempt to get unique identifier, based on current timestamp
        !          5727:     if ($gotlock eq 'ok') {
        !          5728:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
        !          5729:         my $id = time;
        !          5730:         $newid = $id;
        !          5731:         my $idtries = 0;
        !          5732:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
        !          5733:             if ($idtype eq 'concat') {
        !          5734:                 $newid = $id.$idtries;
        !          5735:             } else {
        !          5736:                 $newid ++;
        !          5737:             }
        !          5738:             $idtries ++;
        !          5739:         }
        !          5740:         if (!exists($inuse{$prefix."\0".$newid})) {
        !          5741:             my %new_item =  (
        !          5742:                               $prefix."\0".$newid => $who,
        !          5743:                             );
        !          5744:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
        !          5745:                                                  $cdom,$cnum);
        !          5746:             if ($putresult ne 'ok') {
        !          5747:                 undef($newid);
        !          5748:                 $error = 'error saving new item: '.$putresult;
        !          5749:             }
        !          5750:         } else {
        !          5751:              $error = ('error: no unique suffix available for the new item ');
        !          5752:         }
        !          5753: #  remove lock
        !          5754:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
        !          5755:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
        !          5756:     } else {
        !          5757:         $error = "error: could not obtain lockfile\n";
        !          5758:         $dellock = 'ok';
        !          5759:     }
        !          5760:     return ($newid,$dellock,$error);
        !          5761: }
        !          5762: 
1.765     albertel 5763: # -------------------------------------------------- portfolio access checking
                   5764: 
                   5765: sub portfolio_access {
1.766     albertel 5766:     my ($requrl) = @_;
1.765     albertel 5767:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   5768:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  5769:     if ($result) {
                   5770:         my %setters;
                   5771:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5772:             my ($startblock,$endblock) =
                   5773:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   5774:             if ($startblock && $endblock) {
                   5775:                 return 'B';
                   5776:             }
                   5777:         } else {
                   5778:             my ($startblock,$endblock) =
                   5779:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   5780:             if ($startblock && $endblock) {
                   5781:                 return 'B';
                   5782:             }
                   5783:         }
                   5784:     }
1.765     albertel 5785:     if ($result eq 'ok') {
1.766     albertel 5786:        return 'F';
1.765     albertel 5787:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 5788:        return 'A';
1.765     albertel 5789:     }
1.766     albertel 5790:     return '';
1.765     albertel 5791: }
                   5792: 
                   5793: sub get_portfolio_access {
1.767     albertel 5794:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   5795: 
                   5796:     if (!ref($access_hash)) {
                   5797: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   5798: 	my %access_controls = &get_access_controls($current_perms,$group,
                   5799: 						   $file_name);
                   5800: 	$access_hash = $access_controls{$file_name};
                   5801:     }
                   5802: 
1.765     albertel 5803:     my ($public,$guest,@domains,@users,@courses,@groups);
                   5804:     my $now = time;
                   5805:     if (ref($access_hash) eq 'HASH') {
                   5806:         foreach my $key (keys(%{$access_hash})) {
                   5807:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5808:             if ($start > $now) {
                   5809:                 next;
                   5810:             }
                   5811:             if ($end && $end<$now) {
                   5812:                 next;
                   5813:             }
                   5814:             if ($scope eq 'public') {
                   5815:                 $public = $key;
                   5816:                 last;
                   5817:             } elsif ($scope eq 'guest') {
                   5818:                 $guest = $key;
                   5819:             } elsif ($scope eq 'domains') {
                   5820:                 push(@domains,$key);
                   5821:             } elsif ($scope eq 'users') {
                   5822:                 push(@users,$key);
                   5823:             } elsif ($scope eq 'course') {
                   5824:                 push(@courses,$key);
                   5825:             } elsif ($scope eq 'group') {
                   5826:                 push(@groups,$key);
                   5827:             }
                   5828:         }
                   5829:         if ($public) {
                   5830:             return 'ok';
                   5831:         }
                   5832:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5833:             if ($guest) {
                   5834:                 return $guest;
                   5835:             }
                   5836:         } else {
                   5837:             if (@domains > 0) {
                   5838:                 foreach my $domkey (@domains) {
                   5839:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   5840:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   5841:                             return 'ok';
                   5842:                         }
                   5843:                     }
                   5844:                 }
                   5845:             }
                   5846:             if (@users > 0) {
                   5847:                 foreach my $userkey (@users) {
1.865     raeburn  5848:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   5849:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   5850:                             if (ref($item) eq 'HASH') {
                   5851:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   5852:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   5853:                                     return 'ok';
                   5854:                                 }
                   5855:                             }
                   5856:                         }
                   5857:                     } 
1.765     albertel 5858:                 }
                   5859:             }
                   5860:             my %roleshash;
                   5861:             my @courses_and_groups = @courses;
                   5862:             push(@courses_and_groups,@groups); 
                   5863:             if (@courses_and_groups > 0) {
                   5864:                 my (%allgroups,%allroles); 
                   5865:                 my ($start,$end,$role,$sec,$group);
                   5866:                 foreach my $envkey (%env) {
1.1060    raeburn  5867:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5868:                         my $cid = $2.'_'.$3; 
                   5869:                         if ($1 eq 'gr') {
                   5870:                             $group = $4;
                   5871:                             $allgroups{$cid}{$group} = $env{$envkey};
                   5872:                         } else {
                   5873:                             if ($4 eq '') {
                   5874:                                 $sec = 'none';
                   5875:                             } else {
                   5876:                                 $sec = $4;
                   5877:                             }
                   5878:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5879:                         }
1.811     albertel 5880:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5881:                         my $cid = $2.'_'.$3;
                   5882:                         if ($4 eq '') {
                   5883:                             $sec = 'none';
                   5884:                         } else {
                   5885:                             $sec = $4;
                   5886:                         }
                   5887:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5888:                     }
                   5889:                 }
                   5890:                 if (keys(%allroles) == 0) {
                   5891:                     return;
                   5892:                 }
                   5893:                 foreach my $key (@courses_and_groups) {
                   5894:                     my %content = %{$$access_hash{$key}};
                   5895:                     my $cnum = $content{'number'};
                   5896:                     my $cdom = $content{'domain'};
                   5897:                     my $cid = $cdom.'_'.$cnum;
                   5898:                     if (!exists($allroles{$cid})) {
                   5899:                         next;
                   5900:                     }    
                   5901:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   5902:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   5903:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   5904:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   5905:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   5906:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   5907:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   5908:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   5909:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   5910:                                         if (grep/^all$/,@sections) {
                   5911:                                             return 'ok';
                   5912:                                         } else {
                   5913:                                             if (grep/^$sec$/,@sections) {
                   5914:                                                 return 'ok';
                   5915:                                             }
                   5916:                                         }
                   5917:                                     }
                   5918:                                 }
                   5919:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   5920:                                     if (grep/^none$/,@groups) {
                   5921:                                         return 'ok';
                   5922:                                     }
                   5923:                                 } else {
                   5924:                                     if (grep/^all$/,@groups) {
                   5925:                                         return 'ok';
                   5926:                                     } 
                   5927:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   5928:                                         if (grep/^$group$/,@groups) {
                   5929:                                             return 'ok';
                   5930:                                         }
                   5931:                                     }
                   5932:                                 } 
                   5933:                             }
                   5934:                         }
                   5935:                     }
                   5936:                 }
                   5937:             }
                   5938:             if ($guest) {
                   5939:                 return $guest;
                   5940:             }
                   5941:         }
                   5942:     }
                   5943:     return;
                   5944: }
                   5945: 
                   5946: sub course_group_datechecker {
                   5947:     my ($dates,$now,$status) = @_;
                   5948:     my ($start,$end) = split(/\./,$dates);
                   5949:     if (!$start && !$end) {
                   5950:         return 'ok';
                   5951:     }
                   5952:     if (grep/^active$/,@{$status}) {
                   5953:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   5954:             return 'ok';
                   5955:         }
                   5956:     }
                   5957:     if (grep/^previous$/,@{$status}) {
                   5958:         if ($end > $now ) {
                   5959:             return 'ok';
                   5960:         }
                   5961:     }
                   5962:     if (grep/^future$/,@{$status}) {
                   5963:         if ($start > $now) {
                   5964:             return 'ok';
                   5965:         }
                   5966:     }
                   5967:     return; 
                   5968: }
                   5969: 
                   5970: sub parse_portfolio_url {
                   5971:     my ($url) = @_;
                   5972: 
                   5973:     my ($type,$udom,$unum,$group,$file_name);
                   5974:     
1.823     albertel 5975:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 5976: 	$type = 1;
                   5977:         $udom = $1;
                   5978:         $unum = $2;
                   5979:         $file_name = $3;
1.823     albertel 5980:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 5981: 	$type = 2;
                   5982:         $udom = $1;
                   5983:         $unum = $2;
                   5984:         $group = $3;
                   5985:         $file_name = $3.'/'.$4;
                   5986:     }
                   5987:     if (wantarray) {
                   5988: 	return ($type,$udom,$unum,$file_name,$group);
                   5989:     }
                   5990:     return $type;
                   5991: }
                   5992: 
                   5993: sub is_portfolio_url {
                   5994:     my ($url) = @_;
                   5995:     return scalar(&parse_portfolio_url($url));
                   5996: }
                   5997: 
1.798     raeburn  5998: sub is_portfolio_file {
                   5999:     my ($file) = @_;
1.820     raeburn  6000:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  6001:         return 1;
                   6002:     }
                   6003:     return;
                   6004: }
                   6005: 
1.976     raeburn  6006: sub usertools_access {
1.1084    raeburn  6007:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  6008:     my ($access,%tools);
                   6009:     if ($context eq '') {
                   6010:         $context = 'tools';
                   6011:     }
                   6012:     if ($context eq 'requestcourses') {
                   6013:         %tools = (
                   6014:                       official   => 1,
                   6015:                       unofficial => 1,
1.1006    raeburn  6016:                       community  => 1,
1.985     raeburn  6017:                  );
1.1172.2.9  raeburn  6018:     } elsif ($context eq 'requestauthor') {
                   6019:         %tools = (
                   6020:                       requestauthor => 1,
                   6021:                  );
1.985     raeburn  6022:     } else {
                   6023:         %tools = (
                   6024:                       aboutme   => 1,
                   6025:                       blog      => 1,
1.1172.2.6  raeburn  6026:                       webdav    => 1,
1.985     raeburn  6027:                       portfolio => 1,
                   6028:                  );
                   6029:     }
1.976     raeburn  6030:     return if (!defined($tools{$tool}));
                   6031: 
                   6032:     if ((!defined($udom)) || (!defined($uname))) {
                   6033:         $udom = $env{'user.domain'};
                   6034:         $uname = $env{'user.name'};
                   6035:     }
                   6036: 
1.978     raeburn  6037:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6038:         if ($action ne 'reload') {
1.985     raeburn  6039:             if ($context eq 'requestcourses') {
                   6040:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  6041:             } elsif ($context eq 'requestauthor') {
                   6042:                 return $env{'environment.canrequest.author'};
1.985     raeburn  6043:             } else {
                   6044:                 return $env{'environment.availabletools.'.$tool};
                   6045:             }
                   6046:         }
1.976     raeburn  6047:     }
                   6048: 
1.1172.2.9  raeburn  6049:     my ($toolstatus,$inststatus,$envkey);
                   6050:     if ($context eq 'requestauthor') {
                   6051:         $envkey = $context;
                   6052:     } else {
                   6053:         $envkey = $context.'.'.$tool;
                   6054:     }
1.976     raeburn  6055: 
1.985     raeburn  6056:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   6057:          ($action ne 'reload')) {
1.1172.2.9  raeburn  6058:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  6059:         $inststatus = $env{'environment.inststatus'};
                   6060:     } else {
1.1084    raeburn  6061:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  6062:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  6063:             $inststatus = $userenvref->{'inststatus'};
                   6064:         } else {
1.1172.2.9  raeburn  6065:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   6066:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  6067:             $inststatus = $userenv{'inststatus'};
                   6068:         }
1.976     raeburn  6069:     }
                   6070: 
                   6071:     if ($toolstatus ne '') {
                   6072:         if ($toolstatus) {
                   6073:             $access = 1;
                   6074:         } else {
                   6075:             $access = 0;
                   6076:         }
                   6077:         return $access;
                   6078:     }
                   6079: 
1.1084    raeburn  6080:     my ($is_adv,%domdef);
                   6081:     if (ref($is_advref) eq 'HASH') {
                   6082:         $is_adv = $is_advref->{'is_adv'};
                   6083:     } else {
                   6084:         $is_adv = &is_advanced_user($udom,$uname);
                   6085:     }
                   6086:     if (ref($domdefref) eq 'HASH') {
                   6087:         %domdef = %{$domdefref};
                   6088:     } else {
                   6089:         %domdef = &get_domain_defaults($udom);
                   6090:     }
1.976     raeburn  6091:     if (ref($domdef{$tool}) eq 'HASH') {
                   6092:         if ($is_adv) {
                   6093:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   6094:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   6095:                     $access = 1;
                   6096:                 } else {
                   6097:                     $access = 0;
                   6098:                 }
                   6099:                 return $access;
                   6100:             }
                   6101:         }
                   6102:         if ($inststatus ne '') {
                   6103:             my ($hasaccess,$hasnoaccess);
                   6104:             foreach my $affiliation (split(/:/,$inststatus)) {
                   6105:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   6106:                     if ($domdef{$tool}{$affiliation}) {
                   6107:                         $hasaccess = 1;
                   6108:                     } else {
                   6109:                         $hasnoaccess = 1;
                   6110:                     }
                   6111:                 }
                   6112:             }
                   6113:             if ($hasaccess || $hasnoaccess) {
                   6114:                 if ($hasaccess) {
                   6115:                     $access = 1;
                   6116:                 } elsif ($hasnoaccess) {
                   6117:                     $access = 0; 
                   6118:                 }
                   6119:                 return $access;
                   6120:             }
                   6121:         } else {
                   6122:             if ($domdef{$tool}{'default'} ne '') {
                   6123:                 if ($domdef{$tool}{'default'}) {
                   6124:                     $access = 1;
                   6125:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   6126:                     $access = 0;
                   6127:                 }
                   6128:                 return $access;
                   6129:             }
                   6130:         }
                   6131:     } else {
1.1172.2.6  raeburn  6132:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  6133:             $access = 1;
                   6134:         } else {
                   6135:             $access = 0;
                   6136:         }
1.976     raeburn  6137:         return $access;
                   6138:     }
                   6139: }
                   6140: 
1.1050    raeburn  6141: sub is_course_owner {
                   6142:     my ($cdom,$cnum,$udom,$uname) = @_;
                   6143:     if (($udom eq '') || ($uname eq '')) {
                   6144:         $udom = $env{'user.domain'};
                   6145:         $uname = $env{'user.name'};
                   6146:     }
                   6147:     unless (($udom eq '') || ($uname eq '')) {
                   6148:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   6149:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   6150:                 return 1;
                   6151:             } else {
                   6152:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   6153:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   6154:                     return 1;
                   6155:                 }
                   6156:             }
                   6157:         }
                   6158:     }
                   6159:     return;
                   6160: }
                   6161: 
1.976     raeburn  6162: sub is_advanced_user {
                   6163:     my ($udom,$uname) = @_;
1.1085    raeburn  6164:     if ($udom ne '' && $uname ne '') {
                   6165:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  6166:             if (wantarray) {
                   6167:                 return ($env{'user.adv'},$env{'user.author'});
                   6168:             } else {
                   6169:                 return $env{'user.adv'};
                   6170:             }
1.1085    raeburn  6171:         }
                   6172:     }
1.976     raeburn  6173:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   6174:     my %allroles;
1.1128    raeburn  6175:     my ($is_adv,$is_author);
1.976     raeburn  6176:     foreach my $role (keys(%roleshash)) {
                   6177:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   6178:         my $area = '/'.$tdomain.'/'.$trest;
                   6179:         if ($sec ne '') {
                   6180:             $area .= '/'.$sec;
                   6181:         }
                   6182:         if (($area ne '') && ($trole ne '')) {
                   6183:             my $spec=$trole.'.'.$area;
                   6184:             if ($trole =~ /^cr\//) {
                   6185:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6186:             } elsif ($trole ne 'gr') {
                   6187:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6188:             }
1.1128    raeburn  6189:             if ($trole eq 'au') {
                   6190:                 $is_author = 1;
                   6191:             }
1.976     raeburn  6192:         }
                   6193:     }
                   6194:     foreach my $role (keys(%allroles)) {
                   6195:         last if ($is_adv);
                   6196:         foreach my $item (split(/:/,$allroles{$role})) {
                   6197:             if ($item ne '') {
                   6198:                 my ($privilege,$restrictions)=split(/&/,$item);
                   6199:                 if ($privilege eq 'adv') {
                   6200:                     $is_adv = 1;
                   6201:                     last;
                   6202:                 }
                   6203:             }
                   6204:         }
                   6205:     }
1.1128    raeburn  6206:     if (wantarray) {
                   6207:         return ($is_adv,$is_author);
                   6208:     }
1.976     raeburn  6209:     return $is_adv;
                   6210: }
1.798     raeburn  6211: 
1.1035    raeburn  6212: sub check_can_request {
1.1036    raeburn  6213:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  6214:     my $canreq = 0;
                   6215:     my ($types,$typename) = &Apache::loncommon::course_types();
                   6216:     my @options = ('approval','validate','autolimit');
                   6217:     my $optregex = join('|',@options);
                   6218:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   6219:         foreach my $type (@{$types}) {
                   6220:             if (&usertools_access($env{'user.name'},
                   6221:                                   $env{'user.domain'},
                   6222:                                   $type,undef,'requestcourses')) {
                   6223:                 $canreq ++;
1.1036    raeburn  6224:                 if (ref($request_domains) eq 'HASH') {
                   6225:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   6226:                 }
1.1035    raeburn  6227:                 if ($dom eq $env{'user.domain'}) {
                   6228:                     $can_request->{$type} = 1;
                   6229:                 }
                   6230:             }
                   6231:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   6232:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   6233:                 if (@curr > 0) {
1.1036    raeburn  6234:                     foreach my $item (@curr) {
                   6235:                         if (ref($request_domains) eq 'HASH') {
                   6236:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   6237:                             if ($otherdom ne '') {
                   6238:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   6239:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   6240:                                         push(@{$request_domains->{$type}},$otherdom);
                   6241:                                     }
                   6242:                                 } else {
                   6243:                                     push(@{$request_domains->{$type}},$otherdom);
                   6244:                                 }
                   6245:                             }
                   6246:                         }
                   6247:                     }
                   6248:                     unless($dom eq $env{'user.domain'}) {
                   6249:                         $canreq ++;
1.1035    raeburn  6250:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   6251:                             $can_request->{$type} = 1;
                   6252:                         }
                   6253:                     }
                   6254:                 }
                   6255:             }
                   6256:         }
                   6257:     }
                   6258:     return $canreq;
                   6259: }
                   6260: 
1.341     www      6261: # ---------------------------------------------- Custom access rule evaluation
                   6262: 
                   6263: sub customaccess {
                   6264:     my ($priv,$uri)=@_;
1.807     albertel 6265:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      6266:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 6267:     $udom = &LONCAPA::clean_domain($udom);
                   6268:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      6269:     my $access=0;
1.800     albertel 6270:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 6271: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   6272: 	if ($type eq 'user') {
                   6273: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 6274: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 6275: 		if ($tdom) {
                   6276: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   6277: 		}
1.896     albertel 6278: 		if ($tuname) {
                   6279: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 6280: 		}
                   6281: 		$access=($effect eq 'allow');
                   6282: 		last;
                   6283: 	    }
                   6284: 	} else {
                   6285: 	    if ($role) {
                   6286: 		if ($role ne $urole) { next; }
                   6287: 	    }
                   6288: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   6289: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   6290: 		if ($tdom) {
                   6291: 		    if ($tdom ne $udom) { next; }
                   6292: 		}
                   6293: 		if ($tcrs) {
                   6294: 		    if ($tcrs ne $ucrs) { next; }
                   6295: 		}
                   6296: 		if ($tsec) {
                   6297: 		    if ($tsec ne $usec) { next; }
                   6298: 		}
                   6299: 		$access=($effect eq 'allow');
                   6300: 		last;
                   6301: 	    }
                   6302: 	    if ($realm eq '' && $role eq '') {
                   6303: 		$access=($effect eq 'allow');
                   6304: 	    }
1.402     bowersj2 6305: 	}
1.341     www      6306:     }
                   6307:     return $access;
                   6308: }
                   6309: 
1.103     harris41 6310: # ------------------------------------------------- Check for a user privilege
1.12      www      6311: 
                   6312: sub allowed {
1.810     raeburn  6313:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 6314:     my $ver_orguri=$uri;
1.439     www      6315:     $uri=&deversion($uri);
1.152     www      6316:     my $orguri=$uri;
1.52      www      6317:     $uri=&declutter($uri);
1.809     raeburn  6318: 
1.810     raeburn  6319:     if ($priv eq 'evb') {
                   6320: # Evade communication block restrictions for specified role in a course
                   6321:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   6322:             return $1;
                   6323:         } else {
                   6324:             return;
                   6325:         }
                   6326:     }
                   6327: 
1.620     albertel 6328:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      6329: # Free bre access to adm and meta resources
1.775     albertel 6330:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 6331: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   6332: 	&& ($priv eq 'bre')) {
1.14      www      6333: 	return 'F';
1.159     www      6334:     }
                   6335: 
1.545     banghart 6336: # Free bre access to user's own portfolio contents
1.714     raeburn  6337:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  6338:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  6339: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  6340:         my %setters;
                   6341:         my ($startblock,$endblock) = 
                   6342:             &Apache::loncommon::blockcheck(\%setters,'port');
                   6343:         if ($startblock && $endblock) {
                   6344:             return 'B';
                   6345:         } else {
                   6346:             return 'F';
                   6347:         }
1.545     banghart 6348:     }
                   6349: 
1.762     raeburn  6350: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  6351:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   6352:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   6353:         if (exists($env{'request.course.id'})) {
                   6354:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6355:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6356:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   6357:                 my $courseprivid=$env{'request.course.id'};
                   6358:                 $courseprivid=~s/\_/\//;
                   6359:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   6360:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   6361:                     return $1; 
1.762     raeburn  6362:                 } else {
                   6363:                     if ($env{'request.course.sec'}) {
                   6364:                         $courseprivid.='/'.$env{'request.course.sec'};
                   6365:                     }
                   6366:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   6367:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   6368:                         return $2;
                   6369:                     }
1.714     raeburn  6370:                 }
                   6371:             }
                   6372:         }
                   6373:     }
                   6374: 
1.159     www      6375: # Free bre to public access
                   6376: 
                   6377:     if ($priv eq 'bre') {
1.238     www      6378:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 6379: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      6380:            return 'F'; 
                   6381:         }
1.238     www      6382:         if ($copyright eq 'priv') {
                   6383:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6384: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      6385: 		return '';
                   6386:             }
                   6387:         }
                   6388:         if ($copyright eq 'domain') {
                   6389:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6390: 	    unless (($env{'user.domain'} eq $1) ||
                   6391:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      6392: 		return '';
                   6393:             }
1.262     matthew  6394:         }
1.620     albertel 6395:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  6396:             # Library role, so allow browsing of resources in this domain.
                   6397:             return 'F';
1.238     www      6398:         }
1.341     www      6399:         if ($copyright eq 'custom') {
                   6400: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   6401:         }
1.14      www      6402:     }
1.264     matthew  6403:     # Domain coordinator is trying to create a course
1.620     albertel 6404:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  6405:         # uri is the requested domain in this case.
                   6406:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  6407:         # a role of dc for the domain in question.
1.620     albertel 6408:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  6409:     }
1.29      www      6410: 
1.52      www      6411:     my $thisallowed='';
                   6412:     my $statecond=0;
                   6413:     my $courseprivid='';
                   6414: 
1.1039    raeburn  6415:     my $ownaccess;
1.1043    raeburn  6416:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  6417:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   6418:         if ($uri eq '') {
                   6419:             $ownaccess = 1;
                   6420:         } else {
                   6421:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   6422:                 my $udom = $env{'user.domain'};
                   6423:                 my $uname = $env{'user.name'};
                   6424:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   6425:                     $ownaccess = 1;
1.1040    raeburn  6426:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  6427:                     unless ($uri =~ m{\.\./}) {
                   6428:                         $ownaccess = 1;
                   6429:                     }
                   6430:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   6431:                     my $now = time;
                   6432:                     if ($uri =~ m{^([^/]+)/?$}) {
                   6433:                         my $adom = $1;
                   6434:                         foreach my $key (keys(%env)) {
1.1042    raeburn  6435:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  6436:                                 my ($start,$end) = split('.',$env{$key});
                   6437:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6438:                                     $ownaccess = 1;
                   6439:                                     last;
                   6440:                                 }
                   6441:                             }
                   6442:                         }
                   6443:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   6444:                         my $adom = $1;
                   6445:                         my $aname = $2;
1.1042    raeburn  6446:                         foreach my $role ('ca','aa') { 
                   6447:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   6448:                                 my ($start,$end) =
                   6449:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   6450:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6451:                                     $ownaccess = 1;
                   6452:                                     last;
                   6453:                                 }
1.1039    raeburn  6454:                             }
                   6455:                         }
                   6456:                     }
                   6457:                 }
                   6458:             }
                   6459:         }
                   6460:     }
                   6461: 
1.52      www      6462: # Course
                   6463: 
1.620     albertel 6464:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6465:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6466:             $thisallowed.=$1;
                   6467:         }
1.52      www      6468:     }
1.29      www      6469: 
1.52      www      6470: # Domain
                   6471: 
1.620     albertel 6472:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 6473:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6474:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6475:             $thisallowed.=$1;
                   6476:         }
1.12      www      6477:     }
1.52      www      6478: 
1.1141    raeburn  6479: # User who is not author or co-author might still be able to edit
                   6480: # resource of an author in the domain (e.g., if Domain Coordinator).
                   6481:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   6482:         (&allowed('mdc',$env{'request.course.id'}))) {
                   6483:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   6484:             $thisallowed.=$1;
                   6485:         }
                   6486:     }
                   6487: 
1.52      www      6488: # Course: uri itself is a course
1.66      www      6489:     my $courseuri=$uri;
                   6490:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      6491:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      6492: 
1.620     albertel 6493:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 6494:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6495:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6496:             $thisallowed.=$1;
                   6497:         }
1.12      www      6498:     }
1.29      www      6499: 
1.665     albertel 6500: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 6501: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 6502:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 6503: 	$thisallowed='';
1.671     raeburn  6504:         my ($match)=&is_on_map($uri);
                   6505:         if ($match) {
                   6506:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   6507:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6508:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6509:                 if (@blockers > 0) {
                   6510:                     $thisallowed = 'B';
                   6511:                 } else {
                   6512:                     $thisallowed.=$1;
                   6513:                 }
1.671     raeburn  6514:             }
                   6515:         } else {
1.705     albertel 6516:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  6517:             if ($refuri) {
                   6518:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  6519:                     $thisallowed='F';
1.671     raeburn  6520:                 } else {
                   6521:                     $refuri=&declutter($refuri);
                   6522:                     my ($match) = &is_on_map($refuri);
                   6523:                     if ($match) {
1.1162    raeburn  6524:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6525:                         if (@blockers > 0) {
                   6526:                             $thisallowed = 'B';
                   6527:                         } else {
                   6528:                             $thisallowed='F';
                   6529:                         }
1.671     raeburn  6530:                     }
1.669     raeburn  6531:                 }
1.671     raeburn  6532:             }
                   6533:         }
1.314     www      6534:     }
1.492     albertel 6535: 
1.766     albertel 6536:     if ($priv eq 'bre'
                   6537: 	&& $thisallowed ne 'F' 
                   6538: 	&& $thisallowed ne '2'
                   6539: 	&& &is_portfolio_url($uri)) {
                   6540: 	$thisallowed = &portfolio_access($uri);
                   6541:     }
                   6542:     
1.52      www      6543: # Full access at system, domain or course-wide level? Exit.
1.29      www      6544:     if ($thisallowed=~/F/) {
                   6545: 	return 'F';
                   6546:     }
                   6547: 
1.52      www      6548: # If this is generating or modifying users, exit with special codes
1.29      www      6549: 
1.643     www      6550:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   6551: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 6552: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      6553: # no author name given, so this just checks on the general right to make a co-author in this domain
                   6554: 	    unless ($auname) { return $thisallowed; }
                   6555: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 6556: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   6557: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   6558: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   6559: 	}
1.52      www      6560: 	return $thisallowed;
                   6561:     }
                   6562: #
1.103     harris41 6563: # Gathered so far: system, domain and course wide privileges
1.52      www      6564: #
                   6565: # Course: See if uri or referer is an individual resource that is part of 
                   6566: # the course
                   6567: 
1.620     albertel 6568:     if ($env{'request.course.id'}) {
1.232     www      6569: 
1.620     albertel 6570:        $courseprivid=$env{'request.course.id'};
                   6571:        if ($env{'request.course.sec'}) {
                   6572:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      6573:        }
                   6574:        $courseprivid=~s/\_/\//;
                   6575:        my $checkreferer=1;
1.232     www      6576:        my ($match,$cond)=&is_on_map($uri);
                   6577:        if ($match) {
                   6578:            $statecond=$cond;
1.620     albertel 6579:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6580:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6581:                my $value = $1;
                   6582:                if ($priv eq 'bre') {
                   6583:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6584:                    if (@blockers > 0) {
                   6585:                        $thisallowed = 'B';
                   6586:                    } else {
                   6587:                        $thisallowed.=$value;
                   6588:                    }
                   6589:                } else {
                   6590:                    $thisallowed.=$value;
                   6591:                }
1.52      www      6592:                $checkreferer=0;
                   6593:            }
1.29      www      6594:        }
1.83      www      6595:        
1.148     www      6596:        if ($checkreferer) {
1.620     albertel 6597: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      6598:             unless ($refuri) {
1.800     albertel 6599:                 foreach my $key (keys(%env)) {
                   6600: 		    if ($key=~/^httpref\..*\*/) {
                   6601: 			my $pattern=$key;
1.156     www      6602:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      6603:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   6604:                         $pattern=~s/\//\\\//g;
1.152     www      6605:                         if ($orguri=~/$pattern/) {
1.800     albertel 6606: 			    $refuri=$env{$key};
1.148     www      6607:                         }
                   6608:                     }
1.191     harris41 6609:                 }
1.148     www      6610:             }
1.232     www      6611: 
1.148     www      6612:          if ($refuri) { 
1.152     www      6613: 	  $refuri=&declutter($refuri);
1.232     www      6614:           my ($match,$cond)=&is_on_map($refuri);
                   6615:             if ($match) {
                   6616:               my $refstatecond=$cond;
1.620     albertel 6617:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6618:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6619:                   my $value = $1;
                   6620:                   if ($priv eq 'bre') {
                   6621:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6622:                       if (@blockers > 0) {
                   6623:                           $thisallowed = 'B';
                   6624:                       } else {
                   6625:                           $thisallowed.=$value;
                   6626:                       }
                   6627:                   } else {
                   6628:                       $thisallowed.=$value;
                   6629:                   }
1.53      www      6630:                   $uri=$refuri;
                   6631:                   $statecond=$refstatecond;
1.52      www      6632:               }
                   6633:           }
1.148     www      6634:         }
1.29      www      6635:        }
1.52      www      6636:    }
1.29      www      6637: 
1.52      www      6638: #
1.103     harris41 6639: # Gathered now: all privileges that could apply, and condition number
1.52      www      6640: # 
                   6641: #
                   6642: # Full or no access?
                   6643: #
1.29      www      6644: 
1.52      www      6645:     if ($thisallowed=~/F/) {
                   6646: 	return 'F';
                   6647:     }
1.29      www      6648: 
1.52      www      6649:     unless ($thisallowed) {
                   6650:         return '';
                   6651:     }
1.29      www      6652: 
1.52      www      6653: # Restrictions exist, deal with them
                   6654: #
                   6655: #   C:according to course preferences
                   6656: #   R:according to resource settings
                   6657: #   L:unless locked
                   6658: #   X:according to user session state
                   6659: #
                   6660: 
                   6661: # Possibly locked functionality, check all courses
1.54      www      6662: # Locks might take effect only after 10 minutes cache expiration for other
                   6663: # courses, and 2 minutes for current course
1.52      www      6664: 
                   6665:     my $envkey;
                   6666:     if ($thisallowed=~/L/) {
1.1000    raeburn  6667:         foreach $envkey (keys(%env)) {
1.54      www      6668:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   6669:                my $courseid=$2;
                   6670:                my $roleid=$1.'.'.$2;
1.92      www      6671:                $courseid=~s/^\///;
1.54      www      6672:                my $expiretime=600;
1.620     albertel 6673:                if ($env{'request.role'} eq $roleid) {
1.54      www      6674: 		  $expiretime=120;
                   6675:                }
                   6676: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   6677:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 6678:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 6679: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      6680:                }
1.620     albertel 6681:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6682:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   6683: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   6684:                        &log($env{'user.domain'},$env{'user.name'},
                   6685:                             $env{'user.home'},
1.57      www      6686:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      6687:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6688:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6689: 		       return '';
                   6690:                    }
                   6691:                }
1.620     albertel 6692:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6693:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   6694: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   6695:                        &log($env{'user.domain'},$env{'user.name'},
                   6696:                             $env{'user.home'},
1.57      www      6697:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      6698:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6699:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6700: 		       return '';
                   6701:                    }
                   6702:                }
                   6703: 	   }
1.29      www      6704:        }
1.52      www      6705:     }
                   6706:    
                   6707: #
                   6708: # Rest of the restrictions depend on selected course
                   6709: #
                   6710: 
1.620     albertel 6711:     unless ($env{'request.course.id'}) {
1.766     albertel 6712: 	if ($thisallowed eq 'A') {
                   6713: 	    return 'A';
1.814     raeburn  6714:         } elsif ($thisallowed eq 'B') {
                   6715:             return 'B';
1.766     albertel 6716: 	} else {
                   6717: 	    return '1';
                   6718: 	}
1.52      www      6719:     }
1.29      www      6720: 
1.52      www      6721: #
                   6722: # Now user is definitely in a course
                   6723: #
1.53      www      6724: 
                   6725: 
                   6726: # Course preferences
                   6727: 
                   6728:    if ($thisallowed=~/C/) {
1.620     albertel 6729:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   6730:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   6731:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 6732: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  6733: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6734: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6735: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   6736: 			$env{'request.course.id'});
                   6737: 	   }
1.237     www      6738:            return '';
                   6739:        }
                   6740: 
1.620     albertel 6741:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 6742: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  6743: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6744: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   6745: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   6746: 			$env{'request.course.id'});
                   6747: 	   }
1.54      www      6748:            return '';
                   6749:        }
1.53      www      6750:    }
                   6751: 
                   6752: # Resource preferences
                   6753: 
                   6754:    if ($thisallowed=~/R/) {
1.620     albertel 6755:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 6756:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  6757: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6758: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6759: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   6760: 	   }
                   6761: 	   return '';
1.54      www      6762:        }
1.53      www      6763:    }
1.30      www      6764: 
1.246     www      6765: # Restricted by state or randomout?
1.30      www      6766: 
1.52      www      6767:    if ($thisallowed=~/X/) {
1.620     albertel 6768:       if ($env{'acc.randomout'}) {
1.579     albertel 6769: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 6770:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      6771:             return ''; 
                   6772:          }
1.247     www      6773:       }
                   6774:       if (&condval($statecond)) {
1.52      www      6775: 	 return '2';
                   6776:       } else {
                   6777:          return '';
                   6778:       }
                   6779:    }
1.30      www      6780: 
1.766     albertel 6781:     if ($thisallowed eq 'A') {
                   6782: 	return 'A';
1.814     raeburn  6783:     } elsif ($thisallowed eq 'B') {
                   6784:         return 'B';
1.766     albertel 6785:     }
1.52      www      6786:    return 'F';
1.232     www      6787: }
1.1162    raeburn  6788: 
1.1172.2.13! raeburn  6789: # ------------------------------------------- Check construction space access
        !          6790: 
        !          6791: sub constructaccess {
        !          6792:     my ($url,$setpriv)=@_;
        !          6793: 
        !          6794: # We do not allow editing of previous versions of files
        !          6795:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
        !          6796: 
        !          6797: # Get username and domain from URL
        !          6798:     my ($ownername,$ownerdomain,$ownerhome);
        !          6799: 
        !          6800:     ($ownerdomain,$ownername) =
        !          6801:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
        !          6802: 
        !          6803: # The URL does not really point to any authorspace, forget it
        !          6804:     unless (($ownername) && ($ownerdomain)) { return ''; }
        !          6805: 
        !          6806: # Now we need to see if the user has access to the authorspace of
        !          6807: # $ownername at $ownerdomain
        !          6808: 
        !          6809:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
        !          6810: # Real author for this?
        !          6811:        $ownerhome = $env{'user.home'};
        !          6812:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
        !          6813:           return ($ownername,$ownerdomain,$ownerhome);
        !          6814:        }
        !          6815:     } else {
        !          6816: # Co-author for this?
        !          6817:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
        !          6818:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
        !          6819:             $ownerhome = &homeserver($ownername,$ownerdomain);
        !          6820:             return ($ownername,$ownerdomain,$ownerhome);
        !          6821:         }
        !          6822:     }
        !          6823: 
        !          6824: # We don't have any access right now. If we are not possibly going to do anything about this,
        !          6825: # we might as well leave
        !          6826:    unless ($setpriv) { return ''; }
        !          6827: 
        !          6828: # Backdoor access?
        !          6829:     my $allowed=&allowed('eco',$ownerdomain);
        !          6830: # Nope
        !          6831:     unless ($allowed) { return ''; }
        !          6832: # Looks like we may have access, but could be locked by the owner of the construction space
        !          6833:     if ($allowed eq 'U') {
        !          6834:         my %blocked=&get('environment',['domcoord.author'],
        !          6835:                          $ownerdomain,$ownername);
        !          6836: # Is blocked by owner
        !          6837:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
        !          6838:     }
        !          6839:     if (($allowed eq 'F') || ($allowed eq 'U')) {
        !          6840: # Grant temporary access
        !          6841:         my $then=$env{'user.login.time'};
        !          6842:         my $update==$env{'user.update.time'};
        !          6843:         if (!$update) { $update = $then; }
        !          6844:         my $refresh=$env{'user.refresh.time'};
        !          6845:         if (!$refresh) { $refresh = $update; }
        !          6846:         my $now = time;
        !          6847:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
        !          6848:                            $now,'ca','constructaccess');
        !          6849:         $ownerhome = &homeserver($ownername,$ownerdomain);
        !          6850:         return($ownername,$ownerdomain,$ownerhome);
        !          6851:     }
        !          6852: # No business here
        !          6853:     return '';
        !          6854: }
        !          6855: 
1.1162    raeburn  6856: sub get_comm_blocks {
                   6857:     my ($cdom,$cnum) = @_;
                   6858:     if ($cdom eq '' || $cnum eq '') {
                   6859:         return unless ($env{'request.course.id'});
                   6860:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6861:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6862:     }
                   6863:     my %commblocks;
                   6864:     my $hashid=$cdom.'_'.$cnum;
                   6865:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   6866:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   6867:         %commblocks = %{$blocksref};
                   6868:     } else {
                   6869:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   6870:         my $cachetime = 600;
                   6871:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   6872:     }
                   6873:     return %commblocks;
                   6874: }
                   6875: 
                   6876: sub has_comm_blocking {
                   6877:     my ($priv,$symb,$uri,$blocks) = @_;
                   6878:     return unless ($env{'request.course.id'});
                   6879:     return unless ($priv eq 'bre');
                   6880:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   6881:     my %commblocks;
                   6882:     if (ref($blocks) eq 'HASH') {
                   6883:         %commblocks = %{$blocks};
                   6884:     } else {
                   6885:         %commblocks = &get_comm_blocks();
                   6886:     }
                   6887:     return unless (keys(%commblocks) > 0);
                   6888:     if (!$symb) { $symb=&symbread($uri,1); }
                   6889:     my ($map,$resid,undef)=&decode_symb($symb);
                   6890:     my %tocheck = (
                   6891:                     maps      => $map,
                   6892:                     resources => $symb,
                   6893:                   );
                   6894:     my @blockers;
                   6895:     my $now = time;
1.1163    raeburn  6896:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1162    raeburn  6897:     foreach my $block (keys(%commblocks)) {
                   6898:         if ($block =~ /^(\d+)____(\d+)$/) {
                   6899:             my ($start,$end) = ($1,$2);
                   6900:             if ($start <= $now && $end >= $now) {
                   6901:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   6902:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   6903:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   6904:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
                   6905:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   6906:                                     push(@blockers,$block);
                   6907:                                 }
                   6908:                             }
                   6909:                         }
                   6910:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   6911:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
                   6912:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
                   6913:                                     push(@blockers,$block);
                   6914:                                 }
                   6915:                             }
                   6916:                         }
                   6917:                     }
                   6918:                 }
                   6919:             }
                   6920:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   6921:             my $item = $1;
1.1163    raeburn  6922:             my @to_test;
1.1162    raeburn  6923:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   6924:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   6925:                     my $check_interval;
                   6926:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
                   6927:                         my @interval;
                   6928:                         my $type = 'map';
                   6929:                         if ($item eq 'course') {
                   6930:                             $type = 'course';
                   6931:                             @interval=&EXT("resource.0.interval");
                   6932:                         } else {
                   6933:                             if ($item =~ /___\d+___/) {
                   6934:                                 $type = 'resource';
                   6935:                                 @interval=&EXT("resource.0.interval",$item);
1.1163    raeburn  6936:                                 if (ref($navmap)) {                        
                   6937:                                     my $res = $navmap->getBySymb($item); 
                   6938:                                     push(@to_test,$res);
                   6939:                                 }
1.1162    raeburn  6940:                             } else {
                   6941:                                 my $mapsymb = &symbread($item,1);
                   6942:                                 if ($mapsymb) {
                   6943:                                     if (ref($navmap)) {
                   6944:                                         my $mapres = $navmap->getBySymb($mapsymb);
1.1163    raeburn  6945:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
                   6946:                                         foreach my $res (@to_test) {
1.1162    raeburn  6947:                                             my $symb = $res->symb();
                   6948:                                             next if ($symb eq $mapsymb);
                   6949:                                             if ($symb ne '') {
                   6950:                                                 @interval=&EXT("resource.0.interval",$symb);
                   6951:                                                 last;
                   6952:                                             }
                   6953:                                         }
                   6954:                                     }
                   6955:                                 }
                   6956:                             }
                   6957:                         }
                   6958:                         if ($interval[0] =~ /\d+/) {
                   6959:                             my $first_access;
                   6960:                             if ($type eq 'resource') {
                   6961:                                 $first_access=&get_first_access($interval[1],$item);
                   6962:                             } elsif ($type eq 'map') {
                   6963:                                 $first_access=&get_first_access($interval[1],undef,$item);
                   6964:                             } else {
                   6965:                                 $first_access=&get_first_access($interval[1]);
                   6966:                             }
                   6967:                             if ($first_access) {
                   6968:                                 my $timesup = $first_access+$interval[0];
                   6969:                                 if ($timesup > $now) {
1.1163    raeburn  6970:                                     foreach my $res (@to_test) {
                   6971:                                         if ($res->is_problem()) {
                   6972:                                             if ($res->completable()) {
                   6973:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   6974:                                                     push(@blockers,$block);
                   6975:                                                 }
                   6976:                                                 last;
                   6977:                                             }
                   6978:                                         }
1.1162    raeburn  6979:                                     }
                   6980:                                 }
                   6981:                             }
                   6982:                         }
                   6983:                     }
                   6984:                 }
                   6985:             }
                   6986:         }
                   6987:     }
                   6988:     return @blockers;
                   6989: }
                   6990: 
                   6991: sub check_docs_block {
                   6992:     my ($docsblock,$tocheck) =@_;
                   6993:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
                   6994:         return;
                   6995:     }
                   6996:     if (ref($docsblock->{'maps'}) eq 'HASH') {
                   6997:         if ($tocheck->{'maps'}) {
                   6998:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
                   6999:                 return 1;
                   7000:             }
                   7001:         }
                   7002:     }
                   7003:     if (ref($docsblock->{'resources'}) eq 'HASH') {
                   7004:         if ($tocheck->{'resources'}) {
                   7005:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
                   7006:                 return 1;
                   7007:             }
                   7008:         }
                   7009:     }
                   7010:     return;
                   7011: }
                   7012: 
1.1133    foxr     7013: #
                   7014: #   Removes the versino from a URI and
                   7015: #   splits it in to its filename and path to the filename.
                   7016: #   Seems like File::Basename could have done this more clearly.
                   7017: #   Parameters:
                   7018: #      $uri   - input URI
                   7019: #   Returns:
                   7020: #     Two element list consisting of 
                   7021: #     $pathname  - the URI up to and excluding the trailing /
                   7022: #     $filename  - The part of the URI following the last /
                   7023: #  NOTE:
                   7024: #    Another realization of this is simply:
                   7025: #    use File::Basename;
                   7026: #    ...
                   7027: #    $uri = shift;
                   7028: #    $filename = basename($uri);
                   7029: #    $path     = dirname($uri);
                   7030: #    return ($filename, $path);
                   7031: #
                   7032: #     The implementation below is probably faster however.
                   7033: #
1.710     albertel 7034: sub split_uri_for_cond {
                   7035:     my $uri=&deversion(&declutter(shift));
                   7036:     my @uriparts=split(/\//,$uri);
                   7037:     my $filename=pop(@uriparts);
                   7038:     my $pathname=join('/',@uriparts);
                   7039:     return ($pathname,$filename);
                   7040: }
1.232     www      7041: # --------------------------------------------------- Is a resource on the map?
                   7042: 
                   7043: sub is_on_map {
1.710     albertel 7044:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 7045:     #Trying to find the conditional for the file
1.620     albertel 7046:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 7047: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      7048:     if ($match) {
1.289     bowersj2 7049: 	return (1,$1);
                   7050:     } else {
1.434     www      7051: 	return (0,0);
1.289     bowersj2 7052:     }
1.12      www      7053: }
                   7054: 
1.427     www      7055: # --------------------------------------------------------- Get symb from alias
                   7056: 
                   7057: sub get_symb_from_alias {
                   7058:     my $symb=shift;
                   7059:     my ($map,$resid,$url)=&decode_symb($symb);
                   7060: # Already is a symb
                   7061:     if ($url) { return $symb; }
                   7062: # Must be an alias
                   7063:     my $aliassymb='';
                   7064:     my %bighash;
1.620     albertel 7065:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      7066:                             &GDBM_READER(),0640)) {
                   7067:         my $rid=$bighash{'mapalias_'.$symb};
                   7068: 	if ($rid) {
                   7069: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 7070: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   7071: 				    $resid,$bighash{'src_'.$rid});
1.427     www      7072: 	}
                   7073:         untie %bighash;
                   7074:     }
                   7075:     return $aliassymb;
                   7076: }
                   7077: 
1.12      www      7078: # ----------------------------------------------------------------- Define Role
                   7079: 
                   7080: sub definerole {
                   7081:   if (allowed('mcr','/')) {
                   7082:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 7083:     foreach my $role (split(':',$sysrole)) {
                   7084: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7085:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   7086:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   7087: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7088:                return "refused:s:$crole&$cqual"; 
                   7089:             }
                   7090:         }
1.191     harris41 7091:     }
1.800     albertel 7092:     foreach my $role (split(':',$domrole)) {
                   7093: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7094:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   7095:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   7096: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      7097:                return "refused:d:$crole&$cqual"; 
                   7098:             }
                   7099:         }
1.191     harris41 7100:     }
1.800     albertel 7101:     foreach my $role (split(':',$courole)) {
                   7102: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7103:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   7104:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   7105: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7106:                return "refused:c:$crole&$cqual"; 
                   7107:             }
                   7108:         }
1.191     harris41 7109:     }
1.620     albertel 7110:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   7111:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7112: 	        "rolesdef_$rolename=".
                   7113:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 7114:     return reply($command,$env{'user.home'});
1.12      www      7115:   } else {
                   7116:     return 'refused';
                   7117:   }
1.105     harris41 7118: }
                   7119: 
                   7120: # ---------------- Make a metadata query against the network of library servers
                   7121: 
                   7122: sub metadata_query {
1.244     matthew  7123:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 7124:     my %rhash;
1.845     albertel 7125:     my %libserv = &all_library();
1.244     matthew  7126:     my @server_list = (defined($server_array) ? @$server_array
                   7127:                                               : keys(%libserv) );
                   7128:     for my $server (@server_list) {
1.118     harris41 7129: 	unless ($custom or $customshow) {
                   7130: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   7131: 	    $rhash{$server}=$reply;
                   7132: 	}
                   7133: 	else {
                   7134: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   7135: 			     &escape($custom).':'.&escape($customshow),
                   7136: 			     $server);
                   7137: 	    $rhash{$server}=$reply;
                   7138: 	}
1.112     harris41 7139:     }
1.118     harris41 7140:     return \%rhash;
1.240     www      7141: }
                   7142: 
                   7143: # ----------------------------------------- Send log queries and wait for reply
                   7144: 
                   7145: sub log_query {
                   7146:     my ($uname,$udom,$query,%filters)=@_;
                   7147:     my $uhome=&homeserver($uname,$udom);
                   7148:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 7149:     my $uhost=&hostname($uhome);
1.800     albertel 7150:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      7151:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   7152:                        $uhome);
1.479     albertel 7153:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      7154:     return get_query_reply($queryid);
                   7155: }
                   7156: 
1.818     raeburn  7157: # -------------------------- Update MySQL table for portfolio file
                   7158: 
                   7159: sub update_portfolio_table {
1.821     raeburn  7160:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  7161:     if ($group ne '') {
                   7162:         $file_name =~s /^\Q$group\E//;
                   7163:     }
1.818     raeburn  7164:     my $homeserver = &homeserver($uname,$udom);
                   7165:     my $queryid=
1.821     raeburn  7166:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   7167:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  7168:     my $reply = &get_query_reply($queryid);
                   7169:     return $reply;
                   7170: }
                   7171: 
1.899     raeburn  7172: # -------------------------- Update MySQL allusers table
                   7173: 
                   7174: sub update_allusers_table {
                   7175:     my ($uname,$udom,$names) = @_;
                   7176:     my $homeserver = &homeserver($uname,$udom);
                   7177:     my $queryid=
                   7178:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   7179:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   7180:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   7181:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   7182:                'generation='.&escape($names->{'generation'}).'%%'.
                   7183:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   7184:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  7185:     return;
1.899     raeburn  7186: }
                   7187: 
1.508     raeburn  7188: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  7189: 
                   7190: sub fetch_enrollment_query {
1.511     raeburn  7191:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  7192:     my $homeserver;
1.547     raeburn  7193:     my $maxtries = 1;
1.508     raeburn  7194:     if ($context eq 'automated') {
                   7195:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  7196:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  7197:     } else {
                   7198:         $homeserver = &homeserver($cnum,$dom);
                   7199:     }
1.838     albertel 7200:     my $host=&hostname($homeserver);
1.506     raeburn  7201:     my $cmd = '';
1.1000    raeburn  7202:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 7203:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  7204:     }
                   7205:     $cmd =~ s/%%$//;
                   7206:     $cmd = &escape($cmd);
                   7207:     my $query = 'fetchenrollment';
1.620     albertel 7208:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  7209:     unless ($queryid=~/^\Q$host\E\_/) { 
                   7210:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   7211:         return 'error: '.$queryid;
                   7212:     }
1.506     raeburn  7213:     my $reply = &get_query_reply($queryid);
1.547     raeburn  7214:     my $tries = 1;
                   7215:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7216:         $reply = &get_query_reply($queryid);
                   7217:         $tries ++;
                   7218:     }
1.526     raeburn  7219:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 7220:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  7221:     } else {
1.901     albertel 7222:         my @responses = split(/:/,$reply);
1.515     raeburn  7223:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 7224:             foreach my $line (@responses) {
                   7225:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  7226:                 $$replyref{$key} = $value;
                   7227:             }
                   7228:         } else {
1.1117    foxr     7229:             my $pathname = LONCAPA::tempdir();
1.800     albertel 7230:             foreach my $line (@responses) {
                   7231:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  7232:                 $$replyref{$key} = $value;
                   7233:                 if ($value > 0) {
1.800     albertel 7234:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   7235:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  7236:                         my $destname = $pathname.'/'.$filename;
                   7237:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  7238:                         if ($xml_classlist =~ /^error/) {
                   7239:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   7240:                         } else {
1.506     raeburn  7241:                             if ( open(FILE,">$destname") ) {
                   7242:                                 print FILE &unescape($xml_classlist);
                   7243:                                 close(FILE);
1.526     raeburn  7244:                             } else {
                   7245:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  7246:                             }
                   7247:                         }
                   7248:                     }
                   7249:                 }
                   7250:             }
                   7251:         }
                   7252:         return 'ok';
                   7253:     }
                   7254:     return 'error';
                   7255: }
                   7256: 
1.242     www      7257: sub get_query_reply {
                   7258:     my $queryid=shift;
1.1117    foxr     7259:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      7260:     my $reply='';
                   7261:     for (1..100) {
                   7262: 	sleep 2;
                   7263:         if (-e $replyfile.'.end') {
1.448     albertel 7264: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 7265: 		$reply = join('',<$fh>);
                   7266: 		close($fh);
1.240     www      7267: 	   } else { return 'error: reply_file_error'; }
1.242     www      7268:            return &unescape($reply);
                   7269: 	}
1.240     www      7270:     }
1.242     www      7271:     return 'timeout:'.$queryid;
1.240     www      7272: }
                   7273: 
                   7274: sub courselog_query {
1.241     www      7275: #
                   7276: # possible filters:
                   7277: # url: url or symb
                   7278: # username
                   7279: # domain
                   7280: # action: view, submit, grade
                   7281: # start: timestamp
                   7282: # end: timestamp
                   7283: #
1.240     www      7284:     my (%filters)=@_;
1.620     albertel 7285:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      7286:     if ($filters{'url'}) {
                   7287: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   7288:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   7289:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   7290:     }
1.620     albertel 7291:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7292:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      7293:     return &log_query($cname,$cdom,'courselog',%filters);
                   7294: }
                   7295: 
                   7296: sub userlog_query {
1.858     raeburn  7297: #
                   7298: # possible filters:
                   7299: # action: log check role
                   7300: # start: timestamp
                   7301: # end: timestamp
                   7302: #
1.240     www      7303:     my ($uname,$udom,%filters)=@_;
                   7304:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      7305: }
                   7306: 
1.506     raeburn  7307: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   7308: 
                   7309: sub auto_run {
1.508     raeburn  7310:     my ($cnum,$cdom) = @_;
1.876     raeburn  7311:     my $response = 0;
                   7312:     my $settings;
                   7313:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   7314:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   7315:         $settings = $domconfig{'autoenroll'};
                   7316:         if ($settings->{'run'} eq '1') {
                   7317:             $response = 1;
                   7318:         }
                   7319:     } else {
1.934     raeburn  7320:         my $homeserver;
                   7321:         if (&is_course($cdom,$cnum)) {
                   7322:             $homeserver = &homeserver($cnum,$cdom);
                   7323:         } else {
                   7324:             $homeserver = &domain($cdom,'primary');
                   7325:         }
                   7326:         if ($homeserver ne 'no_host') {
                   7327:             $response = &reply('autorun:'.$cdom,$homeserver);
                   7328:         }
1.876     raeburn  7329:     }
1.506     raeburn  7330:     return $response;
                   7331: }
1.776     albertel 7332: 
1.506     raeburn  7333: sub auto_get_sections {
1.508     raeburn  7334:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  7335:     my $homeserver;
                   7336:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   7337:         $homeserver = &homeserver($cnum,$cdom);
                   7338:     }
                   7339:     if (!defined($homeserver)) { 
                   7340:         if ($cdom =~ /^$match_domain$/) {
                   7341:             $homeserver = &domain($cdom,'primary');
                   7342:         }
                   7343:     }
                   7344:     my @secs;
                   7345:     if (defined($homeserver)) {
                   7346:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   7347:         unless ($response eq 'refused') {
                   7348:             @secs = split(/:/,$response);
                   7349:         }
1.506     raeburn  7350:     }
                   7351:     return @secs;
                   7352: }
1.776     albertel 7353: 
1.506     raeburn  7354: sub auto_new_course {
1.1099    raeburn  7355:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  7356:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  7357:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  7358:     return $response;
                   7359: }
1.776     albertel 7360: 
1.506     raeburn  7361: sub auto_validate_courseID {
1.508     raeburn  7362:     my ($cnum,$cdom,$inst_course_id) = @_;
                   7363:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  7364:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  7365:     return $response;
                   7366: }
1.776     albertel 7367: 
1.1007    raeburn  7368: sub auto_validate_instcode {
1.1020    raeburn  7369:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  7370:     my ($homeserver,$response);
                   7371:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7372:         $homeserver = &homeserver($cnum,$cdom);
                   7373:     }
                   7374:     if (!defined($homeserver)) {
                   7375:         if ($cdom =~ /^$match_domain$/) {
                   7376:             $homeserver = &domain($cdom,'primary');
                   7377:         }
                   7378:     }
1.1065    raeburn  7379:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   7380:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1027    raeburn  7381:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
                   7382:     return ($outcome,$description);
1.1007    raeburn  7383: }
                   7384: 
1.506     raeburn  7385: sub auto_create_password {
1.873     raeburn  7386:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   7387:     my ($homeserver,$response);
1.506     raeburn  7388:     my $create_passwd = 0;
                   7389:     my $authchk = '';
1.873     raeburn  7390:     if ($udom =~ /^$match_domain$/) {
                   7391:         $homeserver = &domain($udom,'primary');
                   7392:     }
                   7393:     if ($homeserver eq '') {
                   7394:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7395:             $homeserver = &homeserver($cnum,$cdom);
                   7396:         }
                   7397:     }
                   7398:     if ($homeserver eq '') {
                   7399:         $authchk = 'nodomain';
1.506     raeburn  7400:     } else {
1.873     raeburn  7401:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   7402:         if ($response eq 'refused') {
                   7403:             $authchk = 'refused';
                   7404:         } else {
1.901     albertel 7405:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  7406:         }
1.506     raeburn  7407:     }
                   7408:     return ($authparam,$create_passwd,$authchk);
                   7409: }
                   7410: 
1.706     raeburn  7411: sub auto_photo_permission {
                   7412:     my ($cnum,$cdom,$students) = @_;
                   7413:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 7414:     my ($outcome,$perm_reqd,$conditions) = 
                   7415: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 7416:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7417: 	return (undef,undef);
                   7418:     }
1.706     raeburn  7419:     return ($outcome,$perm_reqd,$conditions);
                   7420: }
                   7421: 
                   7422: sub auto_checkphotos {
                   7423:     my ($uname,$udom,$pid) = @_;
                   7424:     my $homeserver = &homeserver($uname,$udom);
                   7425:     my ($result,$resulttype);
                   7426:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 7427: 				   &escape($uname).':'.&escape($pid),
                   7428: 				   $homeserver));
1.709     albertel 7429:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7430: 	return (undef,undef);
                   7431:     }
1.706     raeburn  7432:     if ($outcome) {
                   7433:         ($result,$resulttype) = split(/:/,$outcome);
                   7434:     } 
                   7435:     return ($result,$resulttype);
                   7436: }
                   7437: 
                   7438: sub auto_photochoice {
                   7439:     my ($cnum,$cdom) = @_;
                   7440:     my $homeserver = &homeserver($cnum,$cdom);
                   7441:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 7442: 						       &escape($cdom),
                   7443: 						       $homeserver)));
1.709     albertel 7444:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7445: 	return (undef,undef);
                   7446:     }
1.706     raeburn  7447:     return ($update,$comment);
                   7448: }
                   7449: 
                   7450: sub auto_photoupdate {
                   7451:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   7452:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 7453:     my $host=&hostname($homeserver);
1.706     raeburn  7454:     my $cmd = '';
                   7455:     my $maxtries = 1;
1.800     albertel 7456:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   7457:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  7458:     }
                   7459:     $cmd =~ s/%%$//;
                   7460:     $cmd = &escape($cmd);
                   7461:     my $query = 'institutionalphotos';
                   7462:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   7463:     unless ($queryid=~/^\Q$host\E\_/) {
                   7464:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   7465:         return 'error: '.$queryid;
                   7466:     }
                   7467:     my $reply = &get_query_reply($queryid);
                   7468:     my $tries = 1;
                   7469:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7470:         $reply = &get_query_reply($queryid);
                   7471:         $tries ++;
                   7472:     }
                   7473:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   7474:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   7475:     } else {
                   7476:         my @responses = split(/:/,$reply);
                   7477:         my $outcome = shift(@responses); 
                   7478:         foreach my $item (@responses) {
                   7479:             my ($key,$value) = split(/=/,$item);
                   7480:             $$photo{$key} = $value;
                   7481:         }
                   7482:         return $outcome;
                   7483:     }
                   7484:     return 'error';
                   7485: }
                   7486: 
1.521     raeburn  7487: sub auto_instcode_format {
1.793     albertel 7488:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   7489: 	$cat_order) = @_;
1.521     raeburn  7490:     my $courses = '';
1.772     raeburn  7491:     my @homeservers;
1.521     raeburn  7492:     if ($caller eq 'global') {
1.841     albertel 7493: 	my %servers = &get_servers($codedom,'library');
                   7494: 	foreach my $tryserver (keys(%servers)) {
                   7495: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7496: 		push(@homeservers,$tryserver);
                   7497: 	    }
1.584     raeburn  7498:         }
1.1022    raeburn  7499:     } elsif ($caller eq 'requests') {
                   7500:         if ($codedom =~ /^$match_domain$/) {
                   7501:             my $chome = &domain($codedom,'primary');
                   7502:             unless ($chome eq 'no_host') {
                   7503:                 push(@homeservers,$chome);
                   7504:             }
                   7505:         }
1.521     raeburn  7506:     } else {
1.772     raeburn  7507:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  7508:     }
1.793     albertel 7509:     foreach my $code (keys(%{$instcodes})) {
                   7510:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  7511:     }
                   7512:     chop($courses);
1.772     raeburn  7513:     my $ok_response = 0;
                   7514:     my $response;
                   7515:     while (@homeservers > 0 && $ok_response == 0) {
                   7516:         my $server = shift(@homeservers); 
                   7517:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   7518:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   7519:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 7520: 		split(/:/,$response);
1.772     raeburn  7521:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   7522:             push(@{$codetitles},&str2array($codetitles_str));
                   7523:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   7524:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   7525:             $ok_response = 1;
                   7526:         }
                   7527:     }
                   7528:     if ($ok_response) {
1.521     raeburn  7529:         return 'ok';
1.772     raeburn  7530:     } else {
                   7531:         return $response;
1.521     raeburn  7532:     }
                   7533: }
                   7534: 
1.792     raeburn  7535: sub auto_instcode_defaults {
                   7536:     my ($domain,$returnhash,$code_order) = @_;
                   7537:     my @homeservers;
1.841     albertel 7538: 
                   7539:     my %servers = &get_servers($domain,'library');
                   7540:     foreach my $tryserver (keys(%servers)) {
                   7541: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7542: 	    push(@homeservers,$tryserver);
                   7543: 	}
1.792     raeburn  7544:     }
1.841     albertel 7545: 
1.792     raeburn  7546:     my $response;
1.841     albertel 7547:     foreach my $server (@homeservers) {
1.792     raeburn  7548:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 7549:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   7550: 	
                   7551: 	foreach my $pair (split(/\&/,$response)) {
                   7552: 	    my ($name,$value)=split(/\=/,$pair);
                   7553: 	    if ($name eq 'code_order') {
                   7554: 		@{$code_order} = split(/\&/,&unescape($value));
                   7555: 	    } else {
                   7556: 		$returnhash->{&unescape($name)}=&unescape($value);
                   7557: 	    }
                   7558: 	}
                   7559: 	return 'ok';
1.792     raeburn  7560:     }
1.841     albertel 7561: 
                   7562:     return $response;
1.1003    raeburn  7563: }
                   7564: 
                   7565: sub auto_possible_instcodes {
1.1007    raeburn  7566:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   7567:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   7568:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   7569:         return;
                   7570:     }
1.1003    raeburn  7571:     my (@homeservers,$uhome);
                   7572:     if (defined(&domain($domain,'primary'))) {
                   7573:         $uhome=&domain($domain,'primary');
                   7574:         push(@homeservers,&domain($domain,'primary'));
                   7575:     } else {
                   7576:         my %servers = &get_servers($domain,'library');
                   7577:         foreach my $tryserver (keys(%servers)) {
                   7578:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7579:                 push(@homeservers,$tryserver);
                   7580:             }
                   7581:         }
                   7582:     }
                   7583:     my $response;
                   7584:     foreach my $server (@homeservers) {
                   7585:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   7586:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  7587:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   7588:             split(':',$response);
                   7589:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   7590:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  7591:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  7592:             my ($name,$value)=split('=',$item);
                   7593:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7594:         }
                   7595:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  7596:             my ($name,$value)=split('=',$item);
                   7597:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7598:         }
                   7599:         return 'ok';
                   7600:     }
                   7601:     return $response;
                   7602: }
1.792     raeburn  7603: 
1.1010    raeburn  7604: sub auto_courserequest_checks {
                   7605:     my ($dom) = @_;
1.1020    raeburn  7606:     my ($homeserver,%validations);
                   7607:     if ($dom =~ /^$match_domain$/) {
                   7608:         $homeserver = &domain($dom,'primary');
                   7609:     }
                   7610:     unless ($homeserver eq 'no_host') {
                   7611:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   7612:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   7613:             my @items = split(/&/,$response);
                   7614:             foreach my $item (@items) {
                   7615:                 my ($key,$value) = split('=',$item);
                   7616:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   7617:             }
                   7618:         }
                   7619:     }
1.1010    raeburn  7620:     return %validations; 
                   7621: }
                   7622: 
1.1020    raeburn  7623: sub auto_courserequest_validation {
                   7624:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   7625:     my ($homeserver,$response);
                   7626:     if ($dom =~ /^$match_domain$/) {
                   7627:         $homeserver = &domain($dom,'primary');
                   7628:     }
                   7629:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  7630:           
1.1020    raeburn  7631:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  7632:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  7633:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   7634:                                     $homeserver));
                   7635:     }
                   7636:     return $response;
                   7637: }
                   7638: 
1.777     albertel 7639: sub auto_validate_class_sec {
1.918     raeburn  7640:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  7641:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  7642:     my $ownerlist;
                   7643:     if (ref($owners) eq 'ARRAY') {
                   7644:         $ownerlist = join(',',@{$owners});
                   7645:     } else {
                   7646:         $ownerlist = $owners;
                   7647:     }
1.773     raeburn  7648:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  7649:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  7650:     return $response;
                   7651: }
                   7652: 
1.679     raeburn  7653: # ------------------------------------------------------- Course Group routines
                   7654: 
                   7655: sub get_coursegroups {
1.809     raeburn  7656:     my ($cdom,$cnum,$group,$namespace) = @_;
                   7657:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  7658: }
                   7659: 
1.679     raeburn  7660: sub modify_coursegroup {
                   7661:     my ($cdom,$cnum,$groupsettings) = @_;
                   7662:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   7663: }
                   7664: 
1.809     raeburn  7665: sub toggle_coursegroup_status {
                   7666:     my ($cdom,$cnum,$group,$action) = @_;
                   7667:     my ($from_namespace,$to_namespace);
                   7668:     if ($action eq 'delete') {
                   7669:         $from_namespace = 'coursegroups';
                   7670:         $to_namespace = 'deleted_groups';
                   7671:     } else {
                   7672:         $from_namespace = 'deleted_groups';
                   7673:         $to_namespace = 'coursegroups';
                   7674:     }
                   7675:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  7676:     if (my $tmp = &error(%curr_group)) {
                   7677:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   7678:         return ('read error',$tmp);
                   7679:     } else {
                   7680:         my %savedsettings = %curr_group; 
1.809     raeburn  7681:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  7682:         my $deloutcome;
                   7683:         if ($result eq 'ok') {
1.809     raeburn  7684:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  7685:         } else {
                   7686:             return ('write error',$result);
                   7687:         }
                   7688:         if ($deloutcome eq 'ok') {
                   7689:             return 'ok';
                   7690:         } else {
                   7691:             return ('delete error',$deloutcome);
                   7692:         }
                   7693:     }
                   7694: }
                   7695: 
1.679     raeburn  7696: sub modify_group_roles {
1.957     raeburn  7697:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  7698:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   7699:     my $role = 'gr/'.&escape($userprivs);
                   7700:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  7701:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  7702:     if ($result eq 'ok') {
                   7703:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   7704:     }
1.679     raeburn  7705:     return $result;
                   7706: }
                   7707: 
                   7708: sub modify_coursegroup_membership {
                   7709:     my ($cdom,$cnum,$membership) = @_;
                   7710:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   7711:     return $result;
                   7712: }
                   7713: 
1.682     raeburn  7714: sub get_active_groups {
                   7715:     my ($udom,$uname,$cdom,$cnum) = @_;
                   7716:     my $now = time;
                   7717:     my %groups = ();
                   7718:     foreach my $key (keys(%env)) {
1.811     albertel 7719:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  7720:             my ($start,$end) = split(/\./,$env{$key});
                   7721:             if (($end!=0) && ($end<$now)) { next; }
                   7722:             if (($start!=0) && ($start>$now)) { next; }
                   7723:             if ($1 eq $cdom && $2 eq $cnum) {
                   7724:                 $groups{$3} = $env{$key} ;
                   7725:             }
                   7726:         }
                   7727:     }
                   7728:     return %groups;
                   7729: }
                   7730: 
1.683     raeburn  7731: sub get_group_membership {
                   7732:     my ($cdom,$cnum,$group) = @_;
                   7733:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   7734: }
                   7735: 
                   7736: sub get_users_groups {
                   7737:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  7738:     my @usersgroups;
1.683     raeburn  7739:     my $cachetime=1800;
                   7740: 
                   7741:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  7742:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   7743:     if (defined($cached)) {
1.734     albertel 7744:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  7745:     } else {  
                   7746:         $grouplist = '';
1.816     raeburn  7747:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  7748:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  7749:         my $access_end = $env{'course.'.$courseid.
                   7750:                               '.default_enrollment_end_date'};
                   7751:         my $now = time;
                   7752:         foreach my $key (keys(%roleshash)) {
                   7753:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   7754:                 my $group = $1;
                   7755:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   7756:                     my $start = $2;
                   7757:                     my $end = $1;
                   7758:                     if ($start == -1) { next; } # deleted from group
                   7759:                     if (($start!=0) && ($start>$now)) { next; }
                   7760:                     if (($end!=0) && ($end<$now)) {
                   7761:                         if ($access_end && $access_end < $now) {
                   7762:                             if ($access_end - $end < 86400) {
                   7763:                                 push(@usersgroups,$group);
1.733     raeburn  7764:                             }
                   7765:                         }
1.817     raeburn  7766:                         next;
1.733     raeburn  7767:                     }
1.817     raeburn  7768:                     push(@usersgroups,$group);
1.683     raeburn  7769:                 }
                   7770:             }
                   7771:         }
1.817     raeburn  7772:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   7773:         $grouplist = join(':',@usersgroups);
                   7774:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  7775:     }
1.733     raeburn  7776:     return @usersgroups;
1.683     raeburn  7777: }
                   7778: 
                   7779: sub devalidate_getgroups_cache {
                   7780:     my ($udom,$uname,$cdom,$cnum)=@_;
                   7781:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 7782: 
1.683     raeburn  7783:     my $hashid="$udom:$uname:$courseid";
                   7784:     &devalidate_cache_new('getgroups',$hashid);
                   7785: }
                   7786: 
1.12      www      7787: # ------------------------------------------------------------------ Plain Text
                   7788: 
                   7789: sub plaintext {
1.988     raeburn  7790:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  7791:     if ($short =~ m{^cr/}) {
1.758     albertel 7792: 	return (split('/',$short))[-1];
                   7793:     }
1.742     raeburn  7794:     if (!defined($cid)) {
                   7795:         $cid = $env{'request.course.id'};
                   7796:     }
                   7797:     my %rolenames = (
1.1008    raeburn  7798:                       Course    => 'std',
                   7799:                       Community => 'alt1',
1.742     raeburn  7800:                     );
1.1037    raeburn  7801:     if ($cid ne '') {
                   7802:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   7803:             unless ($forcedefault) {
                   7804:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   7805:                 &Apache::lonlocal::mt_escape(\$roletext);
                   7806:                 return &Apache::lonlocal::mt($roletext);
                   7807:             }
                   7808:         }
                   7809:     }
                   7810:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   7811:         (defined($rolenames{$type})) && 
                   7812:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  7813:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  7814:     } elsif ($cid ne '') {
                   7815:         my $crstype = $env{'course.'.$cid.'.type'};
                   7816:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   7817:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   7818:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   7819:         }
1.742     raeburn  7820:     }
1.1037    raeburn  7821:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      7822: }
                   7823: 
                   7824: # ----------------------------------------------------------------- Assign Role
                   7825: 
                   7826: sub assignrole {
1.957     raeburn  7827:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   7828:         $context)=@_;
1.21      www      7829:     my $mrole;
                   7830:     if ($role =~ /^cr\//) {
1.393     www      7831:         my $cwosec=$url;
1.811     albertel 7832:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      7833: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  7834:            my $refused = 1;
                   7835:            if ($context eq 'requestcourses') {
                   7836:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   7837:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   7838:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   7839:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   7840:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7841:                            if ($crsenv{'internal.courseowner'} eq
                   7842:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   7843:                                $refused = '';
                   7844:                            }
                   7845:                        }
                   7846:                    }
                   7847:                }
                   7848:            }
                   7849:            if ($refused) {
                   7850:                &logthis('Refused custom assignrole: '.
                   7851:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   7852:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   7853:                return 'refused';
                   7854:            }
1.104     www      7855:         }
1.21      www      7856:         $mrole='cr';
1.678     raeburn  7857:     } elsif ($role =~ /^gr\//) {
                   7858:         my $cwogrp=$url;
1.811     albertel 7859:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  7860:         unless (&allowed('mdg',$cwogrp)) {
                   7861:             &logthis('Refused group assignrole: '.
                   7862:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   7863:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   7864:             return 'refused';
                   7865:         }
                   7866:         $mrole='gr';
1.21      www      7867:     } else {
1.82      www      7868:         my $cwosec=$url;
1.811     albertel 7869:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  7870:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   7871:             my $refused;
                   7872:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   7873:                 if (!(&allowed('c'.$role,$url))) {
                   7874:                     $refused = 1;
                   7875:                 }
                   7876:             } else {
                   7877:                 $refused = 1;
                   7878:             }
1.947     raeburn  7879:             if ($refused) {
1.1045    raeburn  7880:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   7881:                 if (!$selfenroll && $context eq 'course') {
                   7882:                     my %crsenv;
                   7883:                     if ($role eq 'cc' || $role eq 'co') {
                   7884:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7885:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   7886:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   7887:                                 if ($crsenv{'internal.courseowner'} eq 
                   7888:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   7889:                                     $refused = '';
                   7890:                                 }
                   7891:                             }
                   7892:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   7893:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   7894:                                 if ($crsenv{'internal.courseowner'} eq 
                   7895:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   7896:                                     $refused = '';
                   7897:                                 }
                   7898:                             }
                   7899:                         }
                   7900:                     }
                   7901:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  7902:                     $refused = '';
1.1017    raeburn  7903:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  7904:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  7905:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  7906:                         my $wrongcc;
                   7907:                         if ($cnum =~ /^$match_community$/) {
                   7908:                             $wrongcc = 1 if ($role eq 'cc');
                   7909:                         } else {
                   7910:                             $wrongcc = 1 if ($role eq 'co');
                   7911:                         }
                   7912:                         unless ($wrongcc) {
                   7913:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7914:                             if ($crsenv{'internal.courseowner'} eq 
                   7915:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   7916:                                 $refused = '';
                   7917:                             }
1.1017    raeburn  7918:                         }
                   7919:                     }
1.1172.2.9  raeburn  7920:                 } elsif ($context eq 'requestauthor') {
                   7921:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7922:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   7923:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   7924:                             $refused = '';
                   7925:                         } else {
                   7926:                             my %domdefaults = &get_domain_defaults($udom);
                   7927:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   7928:                                 my $checkbystatus;
                   7929:                                 if ($env{'user.adv'}) {
                   7930:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   7931:                                     if ($disposition eq 'automatic') {
                   7932:                                         $refused = '';
                   7933:                                     } elsif ($disposition eq '') {
                   7934:                                         $checkbystatus = 1;
                   7935:                                     }
                   7936:                                 } else {
                   7937:                                     $checkbystatus = 1;
                   7938:                                 }
                   7939:                                 if ($checkbystatus) {
                   7940:                                     if ($env{'environment.inststatus'}) {
                   7941:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   7942:                                         foreach my $type (@inststatuses) {
                   7943:                                             if (($type ne '') &&
                   7944:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   7945:                                                 $refused = '';
                   7946:                                             }
                   7947:                                         }
                   7948:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   7949:                                         $refused = '';
                   7950:                                     }
                   7951:                                 }
                   7952:                             }
                   7953:                         }
                   7954:                     }
1.1017    raeburn  7955:                 }
                   7956:                 if ($refused) {
1.947     raeburn  7957:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   7958:                              ' '.$role.' '.$end.' '.$start.' by '.
                   7959: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   7960:                     return 'refused';
                   7961:                 }
1.932     raeburn  7962:             }
1.1131    raeburn  7963:         } elsif ($role eq 'au') {
                   7964:             if ($url ne '/'.$udom.'/') {
                   7965:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   7966:                          ' to assign author role for '.$uname.':'.$udom.
                   7967:                          ' in domain: '.$url.' refused (wrong domain).');
                   7968:                 return 'refused';
                   7969:             }
1.104     www      7970:         }
1.21      www      7971:         $mrole=$role;
                   7972:     }
1.620     albertel 7973:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7974:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      7975:     if ($end) { $command.='_'.$end; }
1.21      www      7976:     if ($start) {
                   7977: 	if ($end) { 
1.81      www      7978:            $command.='_'.$start; 
1.21      www      7979:         } else {
1.81      www      7980:            $command.='_0_'.$start;
1.21      www      7981:         }
                   7982:     }
1.739     raeburn  7983:     my $origstart = $start;
                   7984:     my $origend = $end;
1.957     raeburn  7985:     my $delflag;
1.357     www      7986: # actually delete
                   7987:     if ($deleteflag) {
1.373     www      7988: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      7989: # modify command to delete the role
1.620     albertel 7990:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      7991:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 7992: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      7993: # set start and finish to negative values for userrolelog
                   7994:            $start=-1;
                   7995:            $end=-1;
1.957     raeburn  7996:            $delflag = 1;
1.357     www      7997:         }
                   7998:     }
                   7999: # send command
1.349     www      8000:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      8001: # log new user role if status is ok
1.349     www      8002:     if ($answer eq 'ok') {
1.663     raeburn  8003: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  8004:         if (($role eq 'cc') || ($role eq 'in') ||
                   8005:             ($role eq 'ep') || ($role eq 'ad') ||
                   8006:             ($role eq 'ta') || ($role eq 'st') ||
                   8007:             ($role=~/^cr/) || ($role eq 'gr') ||
                   8008:             ($role eq 'co')) {
1.1172.2.13! raeburn  8009: # for course roles, perform group memberships changes triggered by role change.
        !          8010:             unless ($role =~ /^gr/) {
        !          8011:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
        !          8012:                                                  $origstart,$selfenroll,$context);
        !          8013:             }
1.1172.2.9  raeburn  8014:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8015:                            $selfenroll,$context);
                   8016:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
                   8017:                  ($role eq 'au') || ($role eq 'dc')) {
                   8018:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8019:                            $context);
                   8020:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   8021:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8022:                              $context);
                   8023:         }
1.1053    raeburn  8024:         if ($role eq 'cc') {
                   8025:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   8026:         }
1.349     www      8027:     }
                   8028:     return $answer;
1.169     harris41 8029: }
                   8030: 
1.1053    raeburn  8031: sub autoupdate_coowners {
                   8032:     my ($url,$end,$start,$uname,$udom) = @_;
                   8033:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   8034:     if (($cdom ne '') && ($cnum ne '')) {
                   8035:         my $now = time;
                   8036:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   8037:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   8038:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   8039:             my $instcode = $coursehash{'internal.coursecode'};
                   8040:             if ($instcode ne '') {
1.1056    raeburn  8041:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   8042:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  8043:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  8044:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   8045:                         if ($result eq 'valid') {
                   8046:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  8047:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8048:                                     push(@newcoowners,$coowner);
                   8049:                                 }
                   8050:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   8051:                                     push(@newcoowners,$uname.':'.$udom);
                   8052:                                 }
                   8053:                                 @newcoowners = sort(@newcoowners);
                   8054:                             } else {
                   8055:                                 push(@newcoowners,$uname.':'.$udom);
                   8056:                             }
                   8057:                         } else {
                   8058:                             if ($coursehash{'internal.co-owners'}) {
                   8059:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8060:                                     unless ($coowner eq $uname.':'.$udom) {
                   8061:                                         push(@newcoowners,$coowner);
                   8062:                                     }
                   8063:                                 }
                   8064:                                 unless (@newcoowners > 0) {
                   8065:                                     $delcoowners = 1;
                   8066:                                     $coowners = '';
                   8067:                                 }
                   8068:                             }
                   8069:                         }
                   8070:                         if (@newcoowners || $delcoowners) {
                   8071:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   8072:                                             $delcoowners,@newcoowners);
                   8073:                         }
                   8074:                     }
                   8075:                 }
                   8076:             }
                   8077:         }
                   8078:     }
                   8079: }
                   8080: 
                   8081: sub store_coowners {
                   8082:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   8083:     my $cid = $cdom.'_'.$cnum;
                   8084:     my ($coowners,$delresult,$putresult);
                   8085:     if (@newcoowners) {
                   8086:         $coowners = join(',',@newcoowners);
                   8087:         my %coownershash = (
                   8088:                             'internal.co-owners' => $coowners,
                   8089:                            );
                   8090:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   8091:         if ($putresult eq 'ok') {
                   8092:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   8093:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   8094:             }
                   8095:         }
                   8096:     }
                   8097:     if ($delcoowners) {
                   8098:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   8099:         if ($delresult eq 'ok') {
                   8100:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   8101:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   8102:             }
                   8103:         }
                   8104:     }
                   8105:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   8106:         my %crsinfo =
                   8107:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   8108:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   8109:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   8110:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   8111:         }
                   8112:     }
                   8113: }
                   8114: 
1.169     harris41 8115: # -------------------------------------------------- Modify user authentication
1.197     www      8116: # Overrides without validation
                   8117: 
1.169     harris41 8118: sub modifyuserauth {
                   8119:     my ($udom,$uname,$umode,$upass)=@_;
                   8120:     my $uhome=&homeserver($uname,$udom);
1.197     www      8121:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   8122:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 8123:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8124:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 8125:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   8126: 		     &escape($upass),$uhome);
1.620     albertel 8127:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      8128:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   8129:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   8130:     &log($udom,,$uname,$uhome,
1.620     albertel 8131:         'Authentication changed by '.$env{'user.domain'}.', '.
                   8132:                                      $env{'user.name'}.', '.$umode.
1.197     www      8133:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 8134:     unless ($reply eq 'ok') {
1.197     www      8135:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 8136: 	return 'error: '.$reply;
                   8137:     }   
1.170     harris41 8138:     return 'ok';
1.80      www      8139: }
                   8140: 
1.81      www      8141: # --------------------------------------------------------------- Modify a user
1.80      www      8142: 
1.81      www      8143: sub modifyuser {
1.206     matthew  8144:     my ($udom,    $uname, $uid,
                   8145:         $umode,   $upass, $first,
                   8146:         $middle,  $last,  $gene,
1.1058    raeburn  8147:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 8148:     $udom= &LONCAPA::clean_domain($udom);
                   8149:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  8150:     my $showcandelete = 'none';
                   8151:     if (ref($candelete) eq 'ARRAY') {
                   8152:         if (@{$candelete} > 0) {
                   8153:             $showcandelete = join(', ',@{$candelete});
                   8154:         }
                   8155:     }
1.81      www      8156:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      8157:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  8158: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  8159:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   8160:                                      ' desiredhome not specified'). 
1.620     albertel 8161:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8162:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 8163:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  8164:     my $newuser;
                   8165:     if ($uhome eq 'no_host') {
                   8166:         $newuser = 1;
                   8167:     }
1.80      www      8168: # ----------------------------------------------------------------- Create User
1.406     albertel 8169:     if (($uhome eq 'no_host') && 
                   8170: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      8171:         my $unhome='';
1.844     albertel 8172:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  8173:             $unhome = $desiredhome;
1.620     albertel 8174: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   8175: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  8176:         } else { # load balancing routine for determining $unhome
1.81      www      8177:             my $loadm=10000000;
1.841     albertel 8178: 	    my %servers = &get_servers($udom,'library');
                   8179: 	    foreach my $tryserver (keys(%servers)) {
                   8180: 		my $answer=reply('load',$tryserver);
                   8181: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   8182: 		    $loadm=$answer;
                   8183: 		    $unhome=$tryserver;
                   8184: 		}
1.80      www      8185: 	    }
                   8186:         }
                   8187:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  8188: 	    return 'error: unable to find a home server for '.$uname.
                   8189:                    ' in domain '.$udom;
1.80      www      8190:         }
                   8191:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   8192:                          &escape($upass),$unhome);
                   8193: 	unless ($reply eq 'ok') {
                   8194:             return 'error: '.$reply;
                   8195:         }   
1.230     stredwic 8196:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      8197:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  8198: 	    return 'error: unable verify users home machine.';
1.80      www      8199:         }
1.209     matthew  8200:     }   # End of creation of new user
1.80      www      8201: # ---------------------------------------------------------------------- Add ID
                   8202:     if ($uid) {
                   8203:        $uid=~tr/A-Z/a-z/;
                   8204:        my %uidhash=&idrget($udom,$uname);
1.196     www      8205:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   8206:          && (!$forceid)) {
1.80      www      8207: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  8208: 	      return 'error: user id "'.$uid.'" does not match '.
                   8209:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      8210:           }
                   8211:        } else {
                   8212: 	  &idput($udom,($uname => $uid));
                   8213:        }
                   8214:     }
                   8215: # -------------------------------------------------------------- Add names, etc
1.313     matthew  8216:     my @tmp=&get('environment',
1.899     raeburn  8217: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  8218:                     'permanentemail','inststatus'],
1.134     albertel 8219: 		   $udom,$uname);
1.1075    raeburn  8220:     my (%names,%oldnames);
1.313     matthew  8221:     if ($tmp[0] =~ m/^error:.*/) { 
                   8222:         %names=(); 
                   8223:     } else {
                   8224:         %names = @tmp;
1.1075    raeburn  8225:         %oldnames = %names;
1.313     matthew  8226:     }
1.388     www      8227: #
1.1058    raeburn  8228: # If name, email and/or uid are blank (e.g., because an uploaded file
                   8229: # of users did not contain them), do not overwrite existing values
                   8230: # unless field is in $candelete array ref.  
                   8231: #
                   8232: 
                   8233:     my @fields = ('firstname','middlename','lastname','generation',
                   8234:                   'permanentemail','id');
                   8235:     my %newvalues;
                   8236:     if (ref($candelete) eq 'ARRAY') {
                   8237:         foreach my $field (@fields) {
                   8238:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   8239:                 if ($field eq 'firstname') {
                   8240:                     $names{$field} = $first;
                   8241:                 } elsif ($field eq 'middlename') {
                   8242:                     $names{$field} = $middle;
                   8243:                 } elsif ($field eq 'lastname') {
                   8244:                     $names{$field} = $last;
                   8245:                 } elsif ($field eq 'generation') { 
                   8246:                     $names{$field} = $gene;
                   8247:                 } elsif ($field eq 'permanentemail') {
                   8248:                     $names{$field} = $email;
                   8249:                 } elsif ($field eq 'id') {
                   8250:                     $names{$field}  = $uid;
                   8251:                 }
                   8252:             }
                   8253:         }
                   8254:     }
1.388     www      8255:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  8256:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      8257:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  8258:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      8259:     if ($email) {
                   8260:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  8261:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      8262:     }
1.899     raeburn  8263:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  8264:     if (defined($inststatus)) {
                   8265:         $names{'inststatus'} = '';
                   8266:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   8267:         if (ref($usertypes) eq 'HASH') {
                   8268:             my @okstatuses; 
                   8269:             foreach my $item (split(/:/,$inststatus)) {
                   8270:                 if (defined($usertypes->{$item})) {
                   8271:                     push(@okstatuses,$item);  
                   8272:                 }
                   8273:             }
                   8274:             if (@okstatuses) {
                   8275:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   8276:             }
                   8277:         }
                   8278:     }
1.1075    raeburn  8279:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  8280:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  8281:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  8282:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   8283:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   8284:     } else {
                   8285:         $logmsg .= ' during self creation';
                   8286:     }
1.1075    raeburn  8287:     my $changed;
                   8288:     if ($newuser) {
                   8289:         $changed = 1;
                   8290:     } else {
                   8291:         foreach my $field (@fields) {
                   8292:             if ($names{$field} ne $oldnames{$field}) {
                   8293:                 $changed = 1;
                   8294:                 last;
                   8295:             }
                   8296:         }
                   8297:     }
                   8298:     unless ($changed) {
                   8299:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   8300:         &logthis($logmsg);
                   8301:         return 'ok';
                   8302:     }
                   8303:     my $reply = &put('environment', \%names, $udom,$uname);
                   8304:     if ($reply ne 'ok') { 
                   8305:         return 'error: '.$reply;
                   8306:     }
1.1087    raeburn  8307:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   8308:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   8309:     }
1.1075    raeburn  8310:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   8311:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   8312:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  8313:     &logthis($logmsg);
1.134     albertel 8314:     return 'ok';
1.80      www      8315: }
                   8316: 
1.81      www      8317: # -------------------------------------------------------------- Modify student
1.80      www      8318: 
1.81      www      8319: sub modifystudent {
                   8320:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  8321:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990     raeburn  8322:         $selfenroll,$context,$inststatus)=@_;
1.455     albertel 8323:     if (!$cid) {
1.620     albertel 8324: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8325: 	    return 'not_in_class';
                   8326: 	}
1.80      www      8327:     }
                   8328: # --------------------------------------------------------------- Make the user
1.81      www      8329:     my $reply=&modifyuser
1.209     matthew  8330: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  8331:          $desiredhome,$email,$inststatus);
1.80      www      8332:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  8333:     # This will cause &modify_student_enrollment to get the uid from the
                   8334:     # students environment
                   8335:     $uid = undef if (!$forceid);
1.455     albertel 8336:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  8337: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  8338:     return $reply;
                   8339: }
                   8340: 
                   8341: sub modify_student_enrollment {
1.957     raeburn  8342:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 8343:     my ($cdom,$cnum,$chome);
                   8344:     if (!$cid) {
1.620     albertel 8345: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8346: 	    return 'not_in_class';
                   8347: 	}
1.620     albertel 8348: 	$cdom=$env{'course.'.$cid.'.domain'};
                   8349: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 8350:     } else {
                   8351: 	($cdom,$cnum)=split(/_/,$cid);
                   8352:     }
1.620     albertel 8353:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 8354:     if (!$chome) {
1.457     raeburn  8355: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  8356:     }
1.455     albertel 8357:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  8358:     # Make sure the user exists
1.81      www      8359:     my $uhome=&homeserver($uname,$udom);
                   8360:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8361: 	return 'error: no such user';
                   8362:     }
1.297     matthew  8363:     # Get student data if we were not given enough information
                   8364:     if (!defined($first)  || $first  eq '' || 
                   8365:         !defined($last)   || $last   eq '' || 
                   8366:         !defined($uid)    || $uid    eq '' || 
                   8367:         !defined($middle) || $middle eq '' || 
                   8368:         !defined($gene)   || $gene   eq '') {
1.294     matthew  8369:         # They did not supply us with enough data to enroll the student, so
                   8370:         # we need to pick up more information.
1.297     matthew  8371:         my %tmp = &get('environment',
1.294     matthew  8372:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  8373:                        ,$udom,$uname);
                   8374: 
1.800     albertel 8375:         #foreach my $key (keys(%tmp)) {
                   8376:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 8377:         #}
1.294     matthew  8378:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   8379:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   8380:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  8381:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  8382:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   8383:     }
1.556     albertel 8384:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  8385:     my $user = "$uname:$udom";
                   8386:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 8387:     my $reply=cput('classlist',
1.1148    raeburn  8388: 		   {$user => 
1.515     raeburn  8389: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 8390: 		   $cdom,$cnum);
1.1148    raeburn  8391:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   8392:         &devalidate_getsection_cache($udom,$uname,$cid);
                   8393:     } else { 
1.81      www      8394: 	return 'error: '.$reply;
                   8395:     }
1.297     matthew  8396:     # Add student role to user
1.83      www      8397:     my $uurl='/'.$cid;
1.81      www      8398:     $uurl=~s/\_/\//g;
                   8399:     if ($usec) {
                   8400: 	$uurl.='/'.$usec;
                   8401:     }
1.1148    raeburn  8402:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   8403:                              $selfenroll,$context);
                   8404:     if ($result ne 'ok') {
                   8405:         if ($old_entry{$user} ne '') {
                   8406:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   8407:         } else {
                   8408:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   8409:         }
                   8410:     }
                   8411:     return $result; 
1.21      www      8412: }
                   8413: 
1.556     albertel 8414: sub format_name {
                   8415:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   8416:     my $name;
                   8417:     if ($first ne 'lastname') {
                   8418: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   8419:     } else {
                   8420: 	if ($lastname=~/\S/) {
                   8421: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   8422: 	    $name=~s/\s+,/,/;
                   8423: 	} else {
                   8424: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   8425: 	}
                   8426:     }
                   8427:     $name=~s/^\s+//;
                   8428:     $name=~s/\s+$//;
                   8429:     $name=~s/\s+/ /g;
                   8430:     return $name;
                   8431: }
                   8432: 
1.84      www      8433: # ------------------------------------------------- Write to course preferences
                   8434: 
                   8435: sub writecoursepref {
                   8436:     my ($courseid,%prefs)=@_;
                   8437:     $courseid=~s/^\///;
                   8438:     $courseid=~s/\_/\//g;
                   8439:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   8440:     my $chome=homeserver($cnum,$cdomain);
                   8441:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   8442: 	return 'error: no such course';
                   8443:     }
                   8444:     my $cstring='';
1.800     albertel 8445:     foreach my $pref (keys(%prefs)) {
                   8446: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 8447:     }
1.84      www      8448:     $cstring=~s/\&$//;
                   8449:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   8450: }
                   8451: 
                   8452: # ---------------------------------------------------------- Make/modify course
                   8453: 
                   8454: sub createcourse {
1.741     raeburn  8455:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  8456:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      8457:     $url=&declutter($url);
                   8458:     my $cid='';
1.1028    raeburn  8459:     if ($context eq 'requestcourses') {
                   8460:         my $can_create = 0;
                   8461:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   8462:         if ($udom eq $ownerdom) {
                   8463:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   8464:                                   $context)) {
                   8465:                 $can_create = 1;
                   8466:             }
                   8467:         } else {
                   8468:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   8469:                                            $category);
                   8470:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   8471:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   8472:                 if (@curr > 0) {
                   8473:                     my @options = qw(approval validate autolimit);
                   8474:                     my $optregex = join('|',@options);
                   8475:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   8476:                         $can_create = 1;
                   8477:                     }
                   8478:                 }
                   8479:             }
                   8480:         }
                   8481:         if ($can_create) {
                   8482:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   8483:                 unless (&allowed('ccc',$udom)) {
                   8484:                     return 'refused'; 
                   8485:                 }
1.1017    raeburn  8486:             }
                   8487:         } else {
                   8488:             return 'refused';
                   8489:         }
1.1028    raeburn  8490:     } elsif (!&allowed('ccc',$udom)) {
                   8491:         return 'refused';
1.84      www      8492:     }
1.1011    raeburn  8493: # --------------------------------------------------------------- Get Unique ID
                   8494:     my $uname;
                   8495:     if ($cnum =~ /^$match_courseid$/) {
                   8496:         my $chome=&homeserver($cnum,$udom,'true');
                   8497:         if (($chome eq '') || ($chome eq 'no_host')) {
                   8498:             $uname = $cnum;
                   8499:         } else {
1.1038    raeburn  8500:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8501:         }
                   8502:     } else {
1.1038    raeburn  8503:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8504:     }
                   8505:     return $uname if ($uname =~ /^error/);
                   8506: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  8507:     if (!defined($course_server)) {
                   8508:         if (defined(&domain($udom,'primary'))) {
                   8509:             $course_server = &domain($udom,'primary');
                   8510:         } else {
                   8511:             $course_server = $env{'user.home'}; 
                   8512:         }
                   8513:     }
                   8514:     my %host_servers =
                   8515:         &Apache::lonnet::get_servers($udom,'library');
                   8516:     unless ($host_servers{$course_server}) {
                   8517:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  8518:     }
1.84      www      8519: # ------------------------------------------------------------- Make the course
                   8520:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  8521:                       $course_server);
1.84      www      8522:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  8523:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      8524:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8525: 	return 'error: no such course';
                   8526:     }
1.271     www      8527: # ----------------------------------------------------------------- Course made
1.516     raeburn  8528: # log existence
1.1029    raeburn  8529:     my $now = time;
1.918     raeburn  8530:     my $newcourse = {
                   8531:                     $udom.'_'.$uname => {
1.921     raeburn  8532:                                      description => $description,
                   8533:                                      inst_code   => $inst_code,
                   8534:                                      owner       => $course_owner,
                   8535:                                      type        => $crstype,
1.1029    raeburn  8536:                                      creator     => $env{'user.name'}.':'.
                   8537:                                                     $env{'user.domain'},
                   8538:                                      created     => $now,
                   8539:                                      context     => $context,
1.918     raeburn  8540:                                                 },
                   8541:                     };
1.921     raeburn  8542:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      8543: # set toplevel url
1.271     www      8544:     my $topurl=$url;
                   8545:     unless ($nonstandard) {
                   8546: # ------------------------------------------ For standard courses, make top url
                   8547:         my $mapurl=&clutter($url);
1.278     www      8548:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 8549:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      8550: <map>
                   8551: <resource id="1" type="start"></resource>
                   8552: <resource id="2" src="$mapurl"></resource>
                   8553: <resource id="3" type="finish"></resource>
                   8554: <link index="1" from="1" to="2"></link>
                   8555: <link index="2" from="2" to="3"></link>
                   8556: </map>
                   8557: ENDINITMAP
                   8558:         $topurl=&declutter(
1.638     albertel 8559:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      8560:                           );
                   8561:     }
                   8562: # ----------------------------------------------------------- Write preferences
1.84      www      8563:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  8564:                      ('description'              => $description,
                   8565:                       'url'                      => $topurl,
                   8566:                       'internal.creator'         => $env{'user.name'}.':'.
                   8567:                                                     $env{'user.domain'},
                   8568:                       'internal.created'         => $now,
                   8569:                       'internal.creationcontext' => $context)
                   8570:                     );
1.84      www      8571:     return '/'.$udom.'/'.$uname;
                   8572: }
                   8573: 
1.1011    raeburn  8574: # ------------------------------------------------------------------- Create ID
                   8575: sub generate_coursenum {
1.1038    raeburn  8576:     my ($udom,$crstype) = @_;
1.1011    raeburn  8577:     my $domdesc = &domain($udom);
                   8578:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  8579:     my $first;
                   8580:     if ($crstype eq 'Community') {
                   8581:         $first = '0';
                   8582:     } else {
                   8583:         $first = int(1+rand(9)); 
                   8584:     } 
                   8585:     my $uname=$first.
1.1011    raeburn  8586:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8587:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8588:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8589: # ----------------------------------------------- Make sure that does not exist
                   8590:     my $uhome=&homeserver($uname,$udom,'true');
                   8591:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  8592:         if ($crstype eq 'Community') {
                   8593:             $first = '0';
                   8594:         } else {
                   8595:             $first = int(1+rand(9));
                   8596:         }
                   8597:         $uname=$first.
1.1011    raeburn  8598:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8599:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8600:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8601:         $uhome=&homeserver($uname,$udom,'true');
                   8602:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   8603:             return 'error: unable to generate unique course-ID';
                   8604:         }
                   8605:     }
                   8606:     return $uname;
                   8607: }
                   8608: 
1.813     albertel 8609: sub is_course {
1.1167    droeschl 8610:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   8611:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   8612: 
                   8613:     return unless $cdom and $cnum;
                   8614: 
                   8615:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   8616:         '.');
                   8617: 
                   8618:     return unless exists($courses{$cdom.'_'.$cnum});
                   8619:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 8620: }
                   8621: 
1.1015    raeburn  8622: sub store_userdata {
                   8623:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  8624:     my $result;
1.1016    raeburn  8625:     if ($datakey ne '') {
1.1013    raeburn  8626:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  8627:             if ($udom eq '' || $uname eq '') {
                   8628:                 $udom = $env{'user.domain'};
                   8629:                 $uname = $env{'user.name'};
                   8630:             }
                   8631:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  8632:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   8633:                 $result = 'error: no_host';
                   8634:             } else {
                   8635:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   8636:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   8637: 
                   8638:                 my $namevalue='';
                   8639:                 foreach my $key (keys(%{$storehash})) {
                   8640:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   8641:                 }
                   8642:                 $namevalue=~s/\&$//;
1.1105    raeburn  8643:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   8644:                                   $namevalue,$uhome);
1.1013    raeburn  8645:             }
                   8646:         } else {
                   8647:             $result = 'error: data to store was not a hash reference'; 
                   8648:         }
                   8649:     } else {
                   8650:         $result= 'error: invalid requestkey'; 
                   8651:     }
                   8652:     return $result;
                   8653: }
                   8654: 
1.21      www      8655: # ---------------------------------------------------------- Assign Custom Role
                   8656: 
                   8657: sub assigncustomrole {
1.957     raeburn  8658:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8659:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  8660:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      8661: }
                   8662: 
                   8663: # ----------------------------------------------------------------- Revoke Role
                   8664: 
                   8665: sub revokerole {
1.957     raeburn  8666:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8667:     my $now=time;
1.965     raeburn  8668:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      8669: }
                   8670: 
                   8671: # ---------------------------------------------------------- Revoke Custom Role
                   8672: 
                   8673: sub revokecustomrole {
1.957     raeburn  8674:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8675:     my $now=time;
1.357     www      8676:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  8677:            $deleteflag,$selfenroll,$context);
1.17      www      8678: }
                   8679: 
1.533     banghart 8680: # ------------------------------------------------------------ Disk usage
1.535     albertel 8681: sub diskusage {
1.955     raeburn  8682:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   8683:     $directorypath =~ s/\/$//;
                   8684:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   8685:                        .&escape($getpropath).':'.&escape($uname).':'
                   8686:                        .&escape($udom),homeserver($uname,$udom));
                   8687:     if ($listing eq 'unknown_cmd') {
                   8688:         if ($getpropath) {
                   8689:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   8690:         }
                   8691:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   8692:     }
1.514     albertel 8693:     return $listing;
1.512     banghart 8694: }
                   8695: 
1.566     banghart 8696: sub is_locked {
1.1096    raeburn  8697:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 8698:     my @check;
                   8699:     my $is_locked;
1.1093    raeburn  8700:     push (@check,$file_name);
1.613     albertel 8701:     my %locked = &get('file_permissions',\@check,
1.620     albertel 8702: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 8703:     my ($tmp)=keys(%locked);
                   8704:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  8705:     
1.566     banghart 8706:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  8707:         $is_locked = 'false';
                   8708:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  8709:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  8710:                $is_locked = 'true';
1.1096    raeburn  8711:                if (ref($which) eq 'ARRAY') {
                   8712:                    push(@{$which},$entry);
                   8713:                } else {
                   8714:                    last;
                   8715:                }
1.745     raeburn  8716:            }
                   8717:        }
1.566     banghart 8718:     } else {
                   8719:         $is_locked = 'false';
                   8720:     }
1.1093    raeburn  8721:     return $is_locked;
1.566     banghart 8722: }
                   8723: 
1.759     albertel 8724: sub declutter_portfile {
                   8725:     my ($file) = @_;
1.833     albertel 8726:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 8727:     return $file;
                   8728: }
                   8729: 
1.559     banghart 8730: # ------------------------------------------------------------- Mark as Read Only
                   8731: 
                   8732: sub mark_as_readonly {
                   8733:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 8734:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 8735:     my ($tmp)=keys(%current_permissions);
                   8736:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 8737:     foreach my $file (@{$files}) {
1.759     albertel 8738: 	$file = &declutter_portfile($file);
1.561     banghart 8739:         push(@{$current_permissions{$file}},$what);
1.559     banghart 8740:     }
1.613     albertel 8741:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 8742:     return;
                   8743: }
                   8744: 
1.572     banghart 8745: # ------------------------------------------------------------Save Selected Files
                   8746: 
                   8747: sub save_selected_files {
                   8748:     my ($user, $path, @files) = @_;
                   8749:     my $filename = $user."savedfiles";
1.573     banghart 8750:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 8751:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 8752:     foreach my $file (@files) {
1.620     albertel 8753:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 8754:     }
                   8755:     foreach my $file (@other_files) {
1.574     banghart 8756:         print (OUT $file."\n");
1.572     banghart 8757:     }
1.574     banghart 8758:     close (OUT);
1.572     banghart 8759:     return 'ok';
                   8760: }
                   8761: 
1.574     banghart 8762: sub clear_selected_files {
                   8763:     my ($user) = @_;
                   8764:     my $filename = $user."savedfiles";
1.1117    foxr     8765:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 8766:     print (OUT undef);
                   8767:     close (OUT);
                   8768:     return ("ok");    
                   8769: }
                   8770: 
1.572     banghart 8771: sub files_in_path {
                   8772:     my ($user, $path) = @_;
                   8773:     my $filename = $user."savedfiles";
                   8774:     my %return_files;
1.1117    foxr     8775:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 8776:     while (my $line_in = <IN>) {
1.574     banghart 8777:         chomp ($line_in);
                   8778:         my @paths_and_file = split (m!/!, $line_in);
                   8779:         my $file_part = pop (@paths_and_file);
                   8780:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 8781:         $path_part.='/';
                   8782:         my $path_and_file = $path_part.$file_part;
                   8783:         if ($path_part eq $path) {
                   8784:             $return_files{$file_part}= 'selected';
                   8785:         }
                   8786:     }
1.574     banghart 8787:     close (IN);
                   8788:     return (\%return_files);
1.572     banghart 8789: }
                   8790: 
                   8791: # called in portfolio select mode, to show files selected NOT in current directory
                   8792: sub files_not_in_path {
                   8793:     my ($user, $path) = @_;
                   8794:     my $filename = $user."savedfiles";
                   8795:     my @return_files;
                   8796:     my $path_part;
1.1117    foxr     8797:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 8798:     while (my $line = <IN>) {
1.572     banghart 8799:         #ok, I know it's clunky, but I want it to work
1.800     albertel 8800:         my @paths_and_file = split(m|/|, $line);
                   8801:         my $file_part = pop(@paths_and_file);
                   8802:         chomp($file_part);
                   8803:         my $path_part = join('/', @paths_and_file);
1.572     banghart 8804:         $path_part .= '/';
                   8805:         my $path_and_file = $path_part.$file_part;
                   8806:         if ($path_part ne $path) {
1.800     albertel 8807:             push(@return_files, ($path_and_file));
1.572     banghart 8808:         }
                   8809:     }
1.800     albertel 8810:     close(OUT);
1.574     banghart 8811:     return (@return_files);
1.572     banghart 8812: }
                   8813: 
1.745     raeburn  8814: #----------------------------------------------Get portfolio file permissions
1.629     banghart 8815: 
1.745     raeburn  8816: sub get_portfile_permissions {
                   8817:     my ($domain,$user) = @_;
1.613     albertel 8818:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 8819:     my ($tmp)=keys(%current_permissions);
                   8820:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  8821:     return \%current_permissions;
                   8822: }
                   8823: 
                   8824: #---------------------------------------------Get portfolio file access controls
                   8825: 
1.749     raeburn  8826: sub get_access_controls {
1.745     raeburn  8827:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 8828:     my %access;
                   8829:     my $real_file = $file;
                   8830:     $file =~ s/\.meta$//;
1.745     raeburn  8831:     if (defined($file)) {
1.749     raeburn  8832:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   8833:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 8834:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  8835:             }
                   8836:         }
1.745     raeburn  8837:     } else {
1.749     raeburn  8838:         foreach my $key (keys(%{$current_permissions})) {
                   8839:             if ($key =~ /\0accesscontrol$/) {
                   8840:                 if (defined($group)) {
                   8841:                     if ($key !~ m-^\Q$group\E/-) {
                   8842:                         next;
                   8843:                     }
                   8844:                 }
                   8845:                 my ($fullpath) = split(/\0/,$key);
                   8846:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   8847:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   8848:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   8849:                     }
                   8850:                 }
                   8851:             }
                   8852:         }
                   8853:     }
                   8854:     return %access;
                   8855: }
                   8856: 
                   8857: sub modify_access_controls {
                   8858:     my ($file_name,$changes,$domain,$user)=@_;
                   8859:     my ($outcome,$deloutcome);
                   8860:     my %store_permissions;
                   8861:     my %new_values;
                   8862:     my %new_control;
                   8863:     my %translation;
                   8864:     my @deletions = ();
                   8865:     my $now = time;
                   8866:     if (exists($$changes{'activate'})) {
                   8867:         if (ref($$changes{'activate'}) eq 'HASH') {
                   8868:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   8869:             my $numnew = scalar(@newitems);
                   8870:             for (my $i=0; $i<$numnew; $i++) {
                   8871:                 my $newkey = $newitems[$i];
                   8872:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  8873:                 if ($newkey =~ /^\d+:/) { 
                   8874:                     $newkey =~ s/^(\d+)/$newid/;
                   8875:                     $translation{$1} = $newid;
                   8876:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   8877:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   8878:                     $translation{$1} = $newid;
                   8879:                 }
1.749     raeburn  8880:                 $new_values{$file_name."\0".$newkey} = 
                   8881:                                           $$changes{'activate'}{$newitems[$i]};
                   8882:                 $new_control{$newkey} = $now;
                   8883:             }
                   8884:         }
                   8885:     }
                   8886:     my %todelete;
                   8887:     my %changed_items;
                   8888:     foreach my $action ('delete','update') {
                   8889:         if (exists($$changes{$action})) {
                   8890:             if (ref($$changes{$action}) eq 'HASH') {
                   8891:                 foreach my $key (keys(%{$$changes{$action}})) {
                   8892:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   8893:                     if ($action eq 'delete') { 
                   8894:                         $todelete{$itemnum} = 1;
                   8895:                     } else {
                   8896:                         $changed_items{$itemnum} = $key;
                   8897:                     }
                   8898:                 }
1.745     raeburn  8899:             }
                   8900:         }
1.749     raeburn  8901:     }
                   8902:     # get lock on access controls for file.
                   8903:     my $lockhash = {
                   8904:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   8905:                                                        ':'.$env{'user.domain'},
                   8906:                    }; 
                   8907:     my $tries = 0;
                   8908:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   8909:    
                   8910:     while (($gotlock ne 'ok') && $tries <3) {
                   8911:         $tries ++;
                   8912:         sleep 1;
                   8913:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   8914:     }
                   8915:     if ($gotlock eq 'ok') {
                   8916:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   8917:         my ($tmp)=keys(%curr_permissions);
                   8918:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   8919:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   8920:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   8921:             if (ref($curr_controls) eq 'HASH') {
                   8922:                 foreach my $control_item (keys(%{$curr_controls})) {
                   8923:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   8924:                     if (defined($todelete{$itemnum})) {
                   8925:                         push(@deletions,$file_name."\0".$control_item);
                   8926:                     } else {
                   8927:                         if (defined($changed_items{$itemnum})) {
                   8928:                             $new_control{$changed_items{$itemnum}} = $now;
                   8929:                             push(@deletions,$file_name."\0".$control_item);
                   8930:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   8931:                         } else {
                   8932:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   8933:                         }
                   8934:                     }
1.745     raeburn  8935:                 }
                   8936:             }
                   8937:         }
1.970     raeburn  8938:         my ($group);
                   8939:         if (&is_course($domain,$user)) {
                   8940:             ($group,my $file) = split(/\//,$file_name,2);
                   8941:         }
1.749     raeburn  8942:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   8943:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   8944:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   8945:         #  remove lock
                   8946:         my @del_lock = ($file_name."\0".'locked_access_records');
                   8947:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  8948:         my $sqlresult =
1.970     raeburn  8949:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  8950:                                     $group);
1.749     raeburn  8951:     } else {
                   8952:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  8953:     }
1.749     raeburn  8954:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  8955: }
                   8956: 
1.827     raeburn  8957: sub make_public_indefinitely {
                   8958:     my ($requrl) = @_;
                   8959:     my $now = time;
                   8960:     my $action = 'activate';
                   8961:     my $aclnum = 0;
                   8962:     if (&is_portfolio_url($requrl)) {
                   8963:         my (undef,$udom,$unum,$file_name,$group) =
                   8964:             &parse_portfolio_url($requrl);
                   8965:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   8966:         my %access_controls = &get_access_controls($current_perms,
                   8967:                                                    $group,$file_name);
                   8968:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   8969:             my ($num,$scope,$end,$start) = 
                   8970:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   8971:             if ($scope eq 'public') {
                   8972:                 if ($start <= $now && $end == 0) {
                   8973:                     $action = 'none';
                   8974:                 } else {
                   8975:                     $action = 'update';
                   8976:                     $aclnum = $num;
                   8977:                 }
                   8978:                 last;
                   8979:             }
                   8980:         }
                   8981:         if ($action eq 'none') {
                   8982:              return 'ok';
                   8983:         } else {
                   8984:             my %changes;
                   8985:             my $newend = 0;
                   8986:             my $newstart = $now;
                   8987:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   8988:             $changes{$action}{$newkey} = {
                   8989:                 type => 'public',
                   8990:                 time => {
                   8991:                     start => $newstart,
                   8992:                     end   => $newend,
                   8993:                 },
                   8994:             };
                   8995:             my ($outcome,$deloutcome,$new_values,$translation) =
                   8996:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   8997:             return $outcome;
                   8998:         }
                   8999:     } else {
                   9000:         return 'invalid';
                   9001:     }
                   9002: }
                   9003: 
1.745     raeburn  9004: #------------------------------------------------------Get Marked as Read Only
                   9005: 
                   9006: sub get_marked_as_readonly {
                   9007:     my ($domain,$user,$what,$group) = @_;
                   9008:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 9009:     my @readonly_files;
1.629     banghart 9010:     my $cmp1=$what;
                   9011:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  9012:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9013:         if (defined($group)) {
                   9014:             if ($file_name !~ m-^\Q$group\E/-) {
                   9015:                 next;
                   9016:             }
                   9017:         }
1.561     banghart 9018:         if (ref($value) eq "ARRAY"){
                   9019:             foreach my $stored_what (@{$value}) {
1.629     banghart 9020:                 my $cmp2=$stored_what;
1.759     albertel 9021:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  9022:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  9023:                 }
1.629     banghart 9024:                 if ($cmp1 eq $cmp2) {
1.561     banghart 9025:                     push(@readonly_files, $file_name);
1.745     raeburn  9026:                     last;
1.563     banghart 9027:                 } elsif (!defined($what)) {
                   9028:                     push(@readonly_files, $file_name);
1.745     raeburn  9029:                     last;
1.561     banghart 9030:                 }
                   9031:             }
1.745     raeburn  9032:         }
1.561     banghart 9033:     }
                   9034:     return @readonly_files;
                   9035: }
1.577     banghart 9036: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 9037: 
1.577     banghart 9038: sub get_marked_as_readonly_hash {
1.745     raeburn  9039:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 9040:     my %readonly_files;
1.745     raeburn  9041:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9042:         if (defined($group)) {
                   9043:             if ($file_name !~ m-^\Q$group\E/-) {
                   9044:                 next;
                   9045:             }
                   9046:         }
1.577     banghart 9047:         if (ref($value) eq "ARRAY"){
                   9048:             foreach my $stored_what (@{$value}) {
1.745     raeburn  9049:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 9050:                     foreach my $lock_descriptor(@{$stored_what}) {
                   9051:                         if ($lock_descriptor eq 'graded') {
                   9052:                             $readonly_files{$file_name} = 'graded';
                   9053:                         } elsif ($lock_descriptor eq 'handback') {
                   9054:                             $readonly_files{$file_name} = 'handback';
                   9055:                         } else {
                   9056:                             if (!exists($readonly_files{$file_name})) {
                   9057:                                 $readonly_files{$file_name} = 'locked';
                   9058:                             }
                   9059:                         }
1.745     raeburn  9060:                     }
1.750     banghart 9061:                 } 
1.577     banghart 9062:             }
                   9063:         } 
                   9064:     }
                   9065:     return %readonly_files;
                   9066: }
1.559     banghart 9067: # ------------------------------------------------------------ Unmark as Read Only
                   9068: 
                   9069: sub unmark_as_readonly {
1.629     banghart 9070:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   9071:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  9072:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 9073:     $file_name = &declutter_portfile($file_name);
1.634     albertel 9074:     my $symb_crs = $what;
                   9075:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  9076:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 9077:     my ($tmp)=keys(%current_permissions);
                   9078:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9079:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 9080:     foreach my $file (@readonly_files) {
1.759     albertel 9081: 	my $clean_file = &declutter_portfile($file);
                   9082: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 9083: 	my $current_locks = $current_permissions{$file};
1.563     banghart 9084:         my @new_locks;
                   9085:         my @del_keys;
                   9086:         if (ref($current_locks) eq "ARRAY"){
                   9087:             foreach my $locker (@{$current_locks}) {
1.632     albertel 9088:                 my $compare=$locker;
1.749     raeburn  9089:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  9090:                     $compare=join('',@{$locker});
1.746     raeburn  9091:                     if ($compare ne $symb_crs) {
                   9092:                         push(@new_locks, $locker);
                   9093:                     }
1.563     banghart 9094:                 }
                   9095:             }
1.650     albertel 9096:             if (scalar(@new_locks) > 0) {
1.563     banghart 9097:                 $current_permissions{$file} = \@new_locks;
                   9098:             } else {
                   9099:                 push(@del_keys, $file);
1.613     albertel 9100:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 9101:                 delete($current_permissions{$file});
1.563     banghart 9102:             }
                   9103:         }
1.561     banghart 9104:     }
1.613     albertel 9105:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9106:     return;
                   9107: }
1.512     banghart 9108: 
1.17      www      9109: # ------------------------------------------------------------ Directory lister
                   9110: 
                   9111: sub dirlist {
1.955     raeburn  9112:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      9113:     $uri=~s/^\///;
                   9114:     $uri=~s/\/$//;
1.253     stredwic 9115:     my ($udom, $uname);
1.955     raeburn  9116:     if ($getuserdir) {
1.253     stredwic 9117:         $udom = $userdomain;
                   9118:         $uname = $username;
1.955     raeburn  9119:     } else {
                   9120:         (undef,$udom,$uname)=split(/\//,$uri);
                   9121:         if(defined($userdomain)) {
                   9122:             $udom = $userdomain;
                   9123:         }
                   9124:         if(defined($username)) {
                   9125:             $uname = $username;
                   9126:         }
1.253     stredwic 9127:     }
1.955     raeburn  9128:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 9129: 
1.955     raeburn  9130:     $dirRoot = $perlvar{'lonDocRoot'};
                   9131:     if (defined($getpropath)) {
                   9132:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 9133:         $dirRoot =~ s/\/$//;
1.955     raeburn  9134:     } elsif (defined($getuserdir)) {
                   9135:         my $subdir=$uname.'__';
                   9136:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   9137:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   9138:                    ."/$udom/$subdir/$uname";
                   9139:     } elsif (defined($alternateRoot)) {
                   9140:         $dirRoot = $alternateRoot;
1.751     banghart 9141:     }
1.253     stredwic 9142: 
                   9143:     if($udom) {
                   9144:         if($uname) {
1.1135    raeburn  9145:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  9146:             if ($uhome eq 'no_host') {
                   9147:                 return ([],'no_host');
                   9148:             }
1.955     raeburn  9149:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  9150:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  9151:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  9152:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9153:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  9154:             } else {
                   9155:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9156:             }
1.605     matthew  9157:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9158:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  9159:                 @listing_results = split(/:/,$listing);
                   9160:             } else {
                   9161:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9162:             }
1.1135    raeburn  9163:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  9164:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9165:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9166:                 return ([],$listing);
                   9167:             } else {
                   9168:                 return (\@listing_results);
1.1135    raeburn  9169:             }
1.955     raeburn  9170:         } elsif(!$alternateRoot) {
1.1136    raeburn  9171:             my (%allusers,%listerror);
1.841     albertel 9172: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  9173:  	    foreach my $tryserver (keys(%servers)) {
                   9174:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   9175:                                   &escape($udom),$tryserver);
                   9176:                 if ($listing eq 'unknown_cmd') {
                   9177: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9178: 				      $udom, $tryserver);
                   9179:                 } else {
                   9180:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9181:                 }
1.841     albertel 9182: 		if ($listing eq 'unknown_cmd') {
                   9183: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9184: 				      $udom, $tryserver);
                   9185: 		    @listing_results = split(/:/,$listing);
                   9186: 		} else {
                   9187: 		    @listing_results =
                   9188: 			map { &unescape($_); } split(/:/,$listing);
                   9189: 		}
1.1136    raeburn  9190:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   9191:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9192:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9193:                     $listerror{$tryserver} = $listing;
                   9194:                 } else {
1.841     albertel 9195: 		    foreach my $line (@listing_results) {
                   9196: 			my ($entry) = split(/&/,$line,2);
                   9197: 			$allusers{$entry} = 1;
                   9198: 		    }
                   9199: 		}
1.253     stredwic 9200:             }
1.1136    raeburn  9201:             my @alluserslist=();
1.800     albertel 9202:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  9203:                 push(@alluserslist,$user.'&user');
1.253     stredwic 9204:             }
1.1136    raeburn  9205:             return (\@alluserslist);
1.253     stredwic 9206:         } else {
1.1136    raeburn  9207:             return ([],'missing username');
1.253     stredwic 9208:         }
1.955     raeburn  9209:     } elsif(!defined($getpropath)) {
1.1136    raeburn  9210:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   9211:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   9212:         return (\@all_domains);
1.955     raeburn  9213:     } else {
1.1136    raeburn  9214:         return ([],'missing domain');
1.275     stredwic 9215:     }
                   9216: }
                   9217: 
                   9218: # --------------------------------------------- GetFileTimestamp
                   9219: # This function utilizes dirlist and returns the date stamp for
                   9220: # when it was last modified.  It will also return an error of -1
                   9221: # if an error occurs
                   9222: 
                   9223: sub GetFileTimestamp {
1.955     raeburn  9224:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 9225:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   9226:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  9227:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   9228:                                     undef,$getuserdir);
                   9229:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9230:         return -1;
                   9231:     }
                   9232:     if (ref($fileref) eq 'ARRAY') {
                   9233:         my @stats = split('&',$fileref->[0]);
1.375     matthew  9234:         # @stats contains first the filename, then the stat output
                   9235:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 9236:     } else {
                   9237:         return -1;
1.253     stredwic 9238:     }
1.26      www      9239: }
                   9240: 
1.712     albertel 9241: sub stat_file {
                   9242:     my ($uri) = @_;
1.787     albertel 9243:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 9244: 
1.955     raeburn  9245:     my ($udom,$uname,$file);
1.712     albertel 9246:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   9247: 	($udom,$uname,$file) =
1.811     albertel 9248: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 9249: 	$file = 'userfiles/'.$file;
                   9250:     }
                   9251:     if ($uri =~ m-^/res/-) {
                   9252: 	($udom,$uname) = 
1.807     albertel 9253: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 9254: 	$file = $uri;
                   9255:     }
                   9256: 
                   9257:     if (!$udom || !$uname || !$file) {
                   9258: 	# unable to handle the uri
                   9259: 	return ();
                   9260:     }
1.956     raeburn  9261:     my $getpropath;
                   9262:     if ($file =~ /^userfiles\//) {
                   9263:         $getpropath = 1;
                   9264:     }
1.1136    raeburn  9265:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   9266:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9267:         return ();
                   9268:     } else {
                   9269:         if (ref($listref) eq 'ARRAY') {
                   9270:             my @stats = split('&',$listref->[0]);
                   9271: 	    shift(@stats); #filename is first
                   9272: 	    return @stats;
                   9273:         }
1.712     albertel 9274:     }
                   9275:     return ();
                   9276: }
                   9277: 
1.26      www      9278: # -------------------------------------------------------- Value of a Condition
                   9279: 
1.713     albertel 9280: # gets the value of a specific preevaluated condition
                   9281: #    stored in the string  $env{user.state.<cid>}
                   9282: # or looks up a condition reference in the bighash and if if hasn't
                   9283: # already been evaluated recurses into docondval to get the value of
                   9284: # the condition, then memoizing it to 
                   9285: #   $env{user.state.<cid>.<condition>}
1.40      www      9286: sub directcondval {
                   9287:     my $number=shift;
1.620     albertel 9288:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 9289: 	&Apache::lonuserstate::evalstate();
                   9290:     }
1.713     albertel 9291:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   9292: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   9293:     } elsif ($number =~ /^_/) {
                   9294: 	my $sub_condition;
                   9295: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   9296: 		&GDBM_READER(),0640)) {
                   9297: 	    $sub_condition=$bighash{'conditions'.$number};
                   9298: 	    untie(%bighash);
                   9299: 	}
                   9300: 	my $value = &docondval($sub_condition);
1.949     raeburn  9301: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 9302: 	return $value;
                   9303:     }
1.620     albertel 9304:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   9305:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      9306:     } else {
                   9307:        return 2;
                   9308:     }
                   9309: }
                   9310: 
1.713     albertel 9311: # get the collection of conditions for this resource
1.26      www      9312: sub condval {
                   9313:     my $condidx=shift;
1.54      www      9314:     my $allpathcond='';
1.713     albertel 9315:     foreach my $cond (split(/\|/,$condidx)) {
                   9316: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   9317: 	    $allpathcond.=
                   9318: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   9319: 	}
1.191     harris41 9320:     }
1.54      www      9321:     $allpathcond=~s/\|$//;
1.713     albertel 9322:     return &docondval($allpathcond);
                   9323: }
                   9324: 
                   9325: #evaluates an expression of conditions
                   9326: sub docondval {
                   9327:     my ($allpathcond) = @_;
                   9328:     my $result=0;
                   9329:     if ($env{'request.course.id'}
                   9330: 	&& defined($allpathcond)) {
                   9331: 	my $operand='|';
                   9332: 	my @stack;
                   9333: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   9334: 	    if ($chunk eq '(') {
                   9335: 		push @stack,($operand,$result);
                   9336: 	    } elsif ($chunk eq ')') {
                   9337: 		my $before=pop @stack;
                   9338: 		if (pop @stack eq '&') {
                   9339: 		    $result=$result>$before?$before:$result;
                   9340: 		} else {
                   9341: 		    $result=$result>$before?$result:$before;
                   9342: 		}
                   9343: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   9344: 		$operand=$chunk;
                   9345: 	    } else {
                   9346: 		my $new=directcondval($chunk);
                   9347: 		if ($operand eq '&') {
                   9348: 		    $result=$result>$new?$new:$result;
                   9349: 		} else {
                   9350: 		    $result=$result>$new?$result:$new;
                   9351: 		}
                   9352: 	    }
                   9353: 	}
1.26      www      9354:     }
                   9355:     return $result;
1.421     albertel 9356: }
                   9357: 
                   9358: # ---------------------------------------------------- Devalidate courseresdata
                   9359: 
                   9360: sub devalidatecourseresdata {
                   9361:     my ($coursenum,$coursedomain)=@_;
                   9362:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9363:     &devalidate_cache_new('courseres',$hashid);
1.28      www      9364: }
                   9365: 
1.763     www      9366: 
1.200     www      9367: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     9368: #
                   9369: #  Parameters:
                   9370: #      $coursenum    - Number of the course.
                   9371: #      $coursedomain - Domain at which the course was created.
                   9372: #  Returns:
                   9373: #     A hash of the course parameters along (I think) with timestamps
                   9374: #     and version info.
1.877     foxr     9375: 
1.624     albertel 9376: sub get_courseresdata {
                   9377:     my ($coursenum,$coursedomain)=@_;
1.200     www      9378:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   9379:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9380:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 9381:     my %dumpreply;
1.417     albertel 9382:     unless (defined($cached)) {
1.624     albertel 9383: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 9384: 	$result=\%dumpreply;
1.251     albertel 9385: 	my ($tmp) = keys(%dumpreply);
                   9386: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 9387: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 9388: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   9389: 	    return $tmp;
1.416     albertel 9390: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 9391: 	    $result=undef;
1.599     albertel 9392: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 9393: 	}
                   9394:     }
1.624     albertel 9395:     return $result;
                   9396: }
                   9397: 
1.633     albertel 9398: sub devalidateuserresdata {
                   9399:     my ($uname,$udom)=@_;
                   9400:     my $hashid="$udom:$uname";
                   9401:     &devalidate_cache_new('userres',$hashid);
                   9402: }
                   9403: 
1.624     albertel 9404: sub get_userresdata {
                   9405:     my ($uname,$udom)=@_;
                   9406:     #most student don\'t have any data set, check if there is some data
                   9407:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   9408: 
                   9409:     my $hashid="$udom:$uname";
                   9410:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   9411:     if (!defined($cached)) {
                   9412: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   9413: 	$result=\%resourcedata;
                   9414: 	&do_cache_new('userres',$hashid,$result,600);
                   9415:     }
                   9416:     my ($tmp)=keys(%$result);
                   9417:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   9418: 	return $result;
                   9419:     }
                   9420:     #error 2 occurs when the .db doesn't exist
                   9421:     if ($tmp!~/error: 2 /) {
1.672     albertel 9422: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 9423: 		 " Trying to get resource data for ".
                   9424: 		 $uname." at ".$udom.": ".
                   9425: 		 $tmp."</font>");
                   9426:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 9427: 	#&EXT_cache_set($udom,$uname);
                   9428: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 9429: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 9430:     }
                   9431:     return $tmp;
                   9432: }
1.879     foxr     9433: #----------------------------------------------- resdata - return resource data
                   9434: #  Purpose:
                   9435: #    Return resource data for either users or for a course.
                   9436: #  Parameters:
                   9437: #     $name      - Course/user name.
                   9438: #     $domain    - Name of the domain the user/course is registered on.
                   9439: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   9440: #     @which     - Array of names of resources desired.
                   9441: #  Returns:
                   9442: #     The value of the first reasource in @which that is found in the
                   9443: #     resource hash.
                   9444: #  Exceptional Conditions:
                   9445: #     If the $type passed in is not valid (not the string 'course' or 
                   9446: #     'user', an undefined  reference is returned.
                   9447: #     If none of the resources are found, an undef is returned
1.624     albertel 9448: sub resdata {
                   9449:     my ($name,$domain,$type,@which)=@_;
                   9450:     my $result;
                   9451:     if ($type eq 'course') {
                   9452: 	$result=&get_courseresdata($name,$domain);
                   9453:     } elsif ($type eq 'user') {
                   9454: 	$result=&get_userresdata($name,$domain);
                   9455:     }
                   9456:     if (!ref($result)) { return $result; }    
1.251     albertel 9457:     foreach my $item (@which) {
1.927     albertel 9458: 	if (defined($result->{$item->[0]})) {
                   9459: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 9460: 	}
1.250     albertel 9461:     }
1.291     albertel 9462:     return undef;
1.200     www      9463: }
                   9464: 
1.379     matthew  9465: #
                   9466: # EXT resource caching routines
                   9467: #
                   9468: 
                   9469: sub clear_EXT_cache_status {
1.383     albertel 9470:     &delenv('cache.EXT.');
1.379     matthew  9471: }
                   9472: 
                   9473: sub EXT_cache_status {
                   9474:     my ($target_domain,$target_user) = @_;
1.383     albertel 9475:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 9476:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  9477:         # We know already the user has no data
                   9478:         return 1;
                   9479:     } else {
                   9480:         return 0;
                   9481:     }
                   9482: }
                   9483: 
                   9484: sub EXT_cache_set {
                   9485:     my ($target_domain,$target_user) = @_;
1.383     albertel 9486:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  9487:     #&appenv({$cachename => time});
1.379     matthew  9488: }
                   9489: 
1.28      www      9490: # --------------------------------------------------------- Value of a Variable
1.58      www      9491: sub EXT {
1.715     albertel 9492: 
1.395     albertel 9493:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      9494:     unless ($varname) { return ''; }
1.218     albertel 9495:     #get real user name/domain, courseid and symb
                   9496:     my $courseid;
1.359     albertel 9497:     my $publicuser;
1.427     www      9498:     if ($symbparm) {
                   9499: 	$symbparm=&get_symb_from_alias($symbparm);
                   9500:     }
1.218     albertel 9501:     if (!($uname && $udom)) {
1.790     albertel 9502:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 9503:       if (!$symbparm) {	$symbparm=$cursymb; }
                   9504:     } else {
1.620     albertel 9505: 	$courseid=$env{'request.course.id'};
1.218     albertel 9506:     }
1.48      www      9507:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   9508:     my $rest;
1.320     albertel 9509:     if (defined($therest[0])) {
1.48      www      9510:        $rest=join('.',@therest);
                   9511:     } else {
                   9512:        $rest='';
                   9513:     }
1.320     albertel 9514: 
1.57      www      9515:     my $qualifierrest=$qualifier;
                   9516:     if ($rest) { $qualifierrest.='.'.$rest; }
                   9517:     my $spacequalifierrest=$space;
                   9518:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      9519:     if ($realm eq 'user') {
1.48      www      9520: # --------------------------------------------------------------- user.resource
                   9521: 	if ($space eq 'resource') {
1.651     albertel 9522: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   9523: 		  || defined($Apache::lonhomework::parsing_a_task))
                   9524: 		 &&
1.744     albertel 9525: 		 ($symbparm eq &symbread()) ) {	
                   9526: 		# if we are in the middle of processing the resource the
                   9527: 		# get the value we are planning on committing
                   9528:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   9529:                     return $Apache::lonhomework::results{$qualifierrest};
                   9530:                 } else {
                   9531:                     return $Apache::lonhomework::history{$qualifierrest};
                   9532:                 }
1.335     albertel 9533: 	    } else {
1.359     albertel 9534: 		my %restored;
1.620     albertel 9535: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 9536: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   9537: 		} else {
                   9538: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   9539: 		}
1.335     albertel 9540: 		return $restored{$qualifierrest};
                   9541: 	    }
1.48      www      9542: # ----------------------------------------------------------------- user.access
                   9543:         } elsif ($space eq 'access') {
1.218     albertel 9544: 	    # FIXME - not supporting calls for a specific user
1.48      www      9545:             return &allowed($qualifier,$rest);
                   9546: # ------------------------------------------ user.preferences, user.environment
                   9547:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 9548: 	    if (($uname eq $env{'user.name'}) &&
                   9549: 		($udom eq $env{'user.domain'})) {
                   9550: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 9551: 	    } else {
1.359     albertel 9552: 		my %returnhash;
                   9553: 		if (!$publicuser) {
                   9554: 		    %returnhash=&userenvironment($udom,$uname,
                   9555: 						 $qualifierrest);
                   9556: 		}
1.218     albertel 9557: 		return $returnhash{$qualifierrest};
                   9558: 	    }
1.48      www      9559: # ----------------------------------------------------------------- user.course
                   9560:         } elsif ($space eq 'course') {
1.218     albertel 9561: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9562:             return $env{join('.',('request.course',$qualifier))};
1.48      www      9563: # ------------------------------------------------------------------- user.role
                   9564:         } elsif ($space eq 'role') {
1.218     albertel 9565: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9566:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      9567:             if ($qualifier eq 'value') {
                   9568: 		return $role;
                   9569:             } elsif ($qualifier eq 'extent') {
                   9570:                 return $where;
                   9571:             }
                   9572: # ----------------------------------------------------------------- user.domain
                   9573:         } elsif ($space eq 'domain') {
1.218     albertel 9574:             return $udom;
1.48      www      9575: # ------------------------------------------------------------------- user.name
                   9576:         } elsif ($space eq 'name') {
1.218     albertel 9577:             return $uname;
1.48      www      9578: # ---------------------------------------------------- Any other user namespace
1.29      www      9579:         } else {
1.359     albertel 9580: 	    my %reply;
                   9581: 	    if (!$publicuser) {
                   9582: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   9583: 	    }
                   9584: 	    return $reply{$qualifierrest};
1.48      www      9585:         }
1.236     www      9586:     } elsif ($realm eq 'query') {
                   9587: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 9588:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   9589: 						[$spacequalifierrest]);
1.620     albertel 9590: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      9591:    } elsif ($realm eq 'request') {
1.48      www      9592: # ------------------------------------------------------------- request.browser
                   9593:         if ($space eq 'browser') {
1.1145    bisitz   9594:             return $env{'browser.'.$qualifier};
1.57      www      9595: # ------------------------------------------------------------ request.filename
                   9596:         } else {
1.620     albertel 9597:             return $env{'request.'.$spacequalifierrest};
1.29      www      9598:         }
1.28      www      9599:     } elsif ($realm eq 'course') {
1.48      www      9600: # ---------------------------------------------------------- course.description
1.620     albertel 9601:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      9602:     } elsif ($realm eq 'resource') {
1.165     www      9603: 
1.620     albertel 9604: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 9605: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   9606: 	}
1.693     albertel 9607: 
                   9608: 	if ($space eq 'title') {
                   9609: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   9610: 	    return &gettitle($symbparm);
                   9611: 	}
                   9612: 	
                   9613: 	if ($space eq 'map') {
                   9614: 	    my ($map) = &decode_symb($symbparm);
                   9615: 	    return &symbread($map);
                   9616: 	}
1.905     albertel 9617: 	if ($space eq 'filename') {
                   9618: 	    if ($symbparm) {
                   9619: 		return &clutter((&decode_symb($symbparm))[2]);
                   9620: 	    }
                   9621: 	    return &hreflocation('',$env{'request.filename'});
                   9622: 	}
1.693     albertel 9623: 
                   9624: 	my ($section, $group, @groups);
1.593     albertel 9625: 	my ($courselevelm,$courselevel);
1.539     albertel 9626: 	if ($symbparm && defined($courseid) && 
1.620     albertel 9627: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      9628: 
1.218     albertel 9629: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      9630: 
1.60      www      9631: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 9632: 	    my $symbp=$symbparm;
1.735     albertel 9633: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 9634: 
                   9635: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   9636: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   9637: 
1.620     albertel 9638: 	    if (($env{'user.name'} eq $uname) &&
                   9639: 		($env{'user.domain'} eq $udom)) {
                   9640: 		$section=$env{'request.course.sec'};
1.733     raeburn  9641:                 @groups = split(/:/,$env{'request.course.groups'});  
                   9642:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 9643: 	    } else {
1.539     albertel 9644: 		if (! defined($usection)) {
1.551     albertel 9645: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 9646: 		} else {
                   9647: 		    $section = $usection;
                   9648: 		}
1.733     raeburn  9649:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 9650: 	    }
                   9651: 
                   9652: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   9653: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   9654: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   9655: 
1.593     albertel 9656: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 9657: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 9658: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      9659: 
1.60      www      9660: # ----------------------------------------------------------- first, check user
1.624     albertel 9661: 
                   9662: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 9663: 				       ([$courselevelr,'resource'],
                   9664: 					[$courselevelm,'map'     ],
                   9665: 					[$courselevel, 'course'  ]));
1.931     albertel 9666: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      9667: 
1.594     albertel 9668: # ------------------------------------------------ second, check some of course
1.684     raeburn  9669:             my $coursereply;
1.691     raeburn  9670:             if (@groups > 0) {
                   9671:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   9672:                                        $mapparm,$spacequalifierrest);
1.927     albertel 9673:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  9674:             }
1.96      www      9675: 
1.684     raeburn  9676: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 9677: 				  $env{'course.'.$courseid.'.domain'},
                   9678: 				  'course',
                   9679: 				  ([$seclevelr,   'resource'],
                   9680: 				   [$seclevelm,   'map'     ],
                   9681: 				   [$seclevel,    'course'  ],
                   9682: 				   [$courselevelr,'resource']));
                   9683: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      9684: 
1.60      www      9685: # ------------------------------------------------------ third, check map parms
1.218     albertel 9686: 	    my %parmhash=();
                   9687: 	    my $thisparm='';
                   9688: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 9689: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 9690: 		    &GDBM_READER(),0640)) {
1.218     albertel 9691: 		$thisparm=$parmhash{$symbparm};
                   9692: 		untie(%parmhash);
                   9693: 	    }
1.927     albertel 9694: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 9695: 	}
1.594     albertel 9696: # ------------------------------------------ fourth, look in resource metadata
1.71      www      9697: 
1.218     albertel 9698: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 9699: 	my $filename;
                   9700: 	if (!$symbparm) { $symbparm=&symbread(); }
                   9701: 	if ($symbparm) {
1.409     www      9702: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 9703: 	} else {
1.620     albertel 9704: 	    $filename=$env{'request.filename'};
1.282     albertel 9705: 	}
                   9706: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 9707: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 9708: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 9709: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      9710: 
1.927     albertel 9711: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 9712: 	if ($symbparm && defined($courseid) && 
1.620     albertel 9713: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 9714: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   9715: 				     $env{'course.'.$courseid.'.domain'},
                   9716: 				     'course',
1.927     albertel 9717: 				     ([$courselevelm,'map'   ],
                   9718: 				      [$courselevel, 'course']));
                   9719: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 9720: 	}
1.145     www      9721: # ------------------------------------------------------------------ Cascade up
1.218     albertel 9722: 	unless ($space eq '0') {
1.336     albertel 9723: 	    my @parts=split(/_/,$space);
                   9724: 	    my $id=pop(@parts);
                   9725: 	    my $part=join('_',@parts);
                   9726: 	    if ($part eq '') { $part='0'; }
1.927     albertel 9727: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 9728: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  9729: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 9730: 	}
1.395     albertel 9731: 	if ($recurse) { return undef; }
                   9732: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 9733: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      9734: # ---------------------------------------------------- Any other user namespace
                   9735:     } elsif ($realm eq 'environment') {
                   9736: # ----------------------------------------------------------------- environment
1.620     albertel 9737: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   9738: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 9739: 	} else {
1.770     albertel 9740: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   9741: 		return '';
                   9742: 	    }
1.219     albertel 9743: 	    my %returnhash=&userenvironment($udom,$uname,
                   9744: 					    $spacequalifierrest);
                   9745: 	    return $returnhash{$spacequalifierrest};
                   9746: 	}
1.28      www      9747:     } elsif ($realm eq 'system') {
1.48      www      9748: # ----------------------------------------------------------------- system.time
                   9749: 	if ($space eq 'time') {
                   9750: 	    return time;
                   9751:         }
1.696     albertel 9752:     } elsif ($realm eq 'server') {
                   9753: # ----------------------------------------------------------------- system.time
                   9754: 	if ($space eq 'name') {
                   9755: 	    return $ENV{'SERVER_NAME'};
                   9756:         }
1.28      www      9757:     }
1.48      www      9758:     return '';
1.61      www      9759: }
                   9760: 
1.927     albertel 9761: sub get_reply {
                   9762:     my ($reply_value) = @_;
1.940     raeburn  9763:     if (ref($reply_value) eq 'ARRAY') {
                   9764:         if (wantarray) {
                   9765: 	    return @$reply_value;
                   9766:         }
                   9767:         return $reply_value->[0];
                   9768:     } else {
                   9769:         return $reply_value;
1.927     albertel 9770:     }
                   9771: }
                   9772: 
1.691     raeburn  9773: sub check_group_parms {
                   9774:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   9775:     my @groupitems = ();
                   9776:     my $resultitem;
1.927     albertel 9777:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  9778:     foreach my $group (@{$groups}) {
                   9779:         foreach my $level (@levels) {
1.927     albertel 9780:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   9781:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  9782:         }
                   9783:     }
                   9784:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   9785:                             $env{'course.'.$courseid.'.domain'},
                   9786:                                      'course',@groupitems);
                   9787:     return $coursereply;
                   9788: }
                   9789: 
                   9790: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  9791:     my ($courseid,@groups) = @_;
                   9792:     @groups = sort(@groups);
1.691     raeburn  9793:     return @groups;
                   9794: }
                   9795: 
1.395     albertel 9796: sub packages_tab_default {
                   9797:     my ($uri,$varname)=@_;
                   9798:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 9799: 
                   9800:     my (@extension,@specifics,$do_default);
                   9801:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 9802: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 9803: 	if ($pack_type eq 'default') {
                   9804: 	    $do_default=1;
                   9805: 	} elsif ($pack_type eq 'extension') {
                   9806: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 9807: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 9808: 	    # only look at packages defaults for packages that this id is
1.738     albertel 9809: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   9810: 	}
                   9811:     }
                   9812:     # first look for a package that matches the requested part id
                   9813:     foreach my $package (@specifics) {
                   9814: 	my (undef,$pack_type,$pack_part)=@{$package};
                   9815: 	next if ($pack_part ne $part);
                   9816: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9817: 	    return $packagetab{"$pack_type&$name&default"};
                   9818: 	}
                   9819:     }
                   9820:     # look for any possible matching non extension_ package
                   9821:     foreach my $package (@specifics) {
                   9822: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 9823: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9824: 	    return $packagetab{"$pack_type&$name&default"};
                   9825: 	}
1.585     albertel 9826: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 9827: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   9828: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 9829: 	}
                   9830:     }
1.738     albertel 9831:     # look for any posible extension_ match
                   9832:     foreach my $package (@extension) {
                   9833: 	my ($package,$pack_type)=@{$package};
                   9834: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9835: 	    return $packagetab{"$pack_type&$name&default"};
                   9836: 	}
                   9837: 	if (defined($packagetab{$package."&$name&default"})) {
                   9838: 	    return $packagetab{$package."&$name&default"};
                   9839: 	}
                   9840:     }
                   9841:     # look for a global default setting
                   9842:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   9843: 	return $packagetab{"default&$name&default"};
                   9844:     }
1.395     albertel 9845:     return undef;
                   9846: }
                   9847: 
1.334     albertel 9848: sub add_prefix_and_part {
                   9849:     my ($prefix,$part)=@_;
                   9850:     my $keyroot;
                   9851:     if (defined($prefix) && $prefix !~ /^__/) {
                   9852: 	# prefix that has a part already
                   9853: 	$keyroot=$prefix;
                   9854:     } elsif (defined($prefix)) {
                   9855: 	# prefix that is missing a part
                   9856: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   9857:     } else {
                   9858: 	# no prefix at all
                   9859: 	if (defined($part)) { $keyroot='_'.$part; }
                   9860:     }
                   9861:     return $keyroot;
                   9862: }
                   9863: 
1.71      www      9864: # ---------------------------------------------------------------- Get metadata
                   9865: 
1.599     albertel 9866: my %metaentry;
1.1070    www      9867: my %importedpartids;
1.71      www      9868: sub metadata {
1.176     www      9869:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      9870:     $uri=&declutter($uri);
1.288     albertel 9871:     # if it is a non metadata possible uri return quickly
1.529     albertel 9872:     if (($uri eq '') || 
                   9873: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 9874: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1108    raeburn  9875:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 9876: 	return undef;
                   9877:     }
1.1140    www      9878:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
1.924     albertel 9879: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 9880: 	return undef;
1.288     albertel 9881:     }
1.73      www      9882:     my $filename=$uri;
                   9883:     $uri=~s/\.meta$//;
1.172     www      9884: #
                   9885: # Is the metadata already cached?
1.177     www      9886: # Look at timestamp of caching
1.172     www      9887: # Everything is cached by the main uri, libraries are never directly cached
                   9888: #
1.428     albertel 9889:     if (!defined($liburi)) {
1.599     albertel 9890: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 9891: 	if (defined($cached)) { return $result->{':'.$what}; }
                   9892:     }
                   9893:     {
1.1069    www      9894: # Imported parts would go here
1.1070    www      9895:         my %importedids=();
                   9896:         my @origfileimportpartids=();
1.1069    www      9897:         my $importedparts=0;
1.172     www      9898: #
                   9899: # Is this a recursive call for a library?
                   9900: #
1.599     albertel 9901: #	if (! exists($metacache{$uri})) {
                   9902: #	    $metacache{$uri}={};
                   9903: #	}
1.924     albertel 9904: 	my $cachetime = 60*60;
1.171     www      9905:         if ($liburi) {
                   9906: 	    $liburi=&declutter($liburi);
                   9907:             $filename=$liburi;
1.401     bowersj2 9908:         } else {
1.599     albertel 9909: 	    &devalidate_cache_new('meta',$uri);
                   9910: 	    undef(%metaentry);
1.401     bowersj2 9911: 	}
1.140     www      9912:         my %metathesekeys=();
1.73      www      9913:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 9914: 	my $metastring;
1.1140    www      9915: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 9916: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 9917: 	    $metastring = 
1.929     albertel 9918: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 9919: 					  ('grade_target' => 'meta'));
                   9920: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  9921: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   9922:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 9923: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 9924: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 9925: 	    $metastring=&getfile($file);
1.489     albertel 9926: 	}
1.208     albertel 9927:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      9928:         my $token;
1.140     www      9929:         undef %metathesekeys;
1.71      www      9930:         while ($token=$parser->get_token) {
1.339     albertel 9931: 	    if ($token->[0] eq 'S') {
                   9932: 		if (defined($token->[2]->{'package'})) {
1.172     www      9933: #
                   9934: # This is a package - get package info
                   9935: #
1.339     albertel 9936: 		    my $package=$token->[2]->{'package'};
                   9937: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9938: 		    if (defined($token->[2]->{'id'})) { 
                   9939: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   9940: 		    }
1.599     albertel 9941: 		    if ($metaentry{':packages'}) {
                   9942: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 9943: 		    } else {
1.599     albertel 9944: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 9945: 		    }
1.736     albertel 9946: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 9947: 			my $part=$keyroot;
                   9948: 			$part=~s/^\_//;
1.736     albertel 9949: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   9950: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   9951: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 9952: 			    # ignore package.tab specified default values
                   9953:                             # here &package_tab_default() will fetch those
                   9954: 			    if ($subp eq 'default') { next; }
1.736     albertel 9955: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 9956: 			    my $unikey;
                   9957: 			    if ($pack =~ /_0$/) {
                   9958: 				$unikey='parameter_0_'.$name;
                   9959: 				$part=0;
                   9960: 			    } else {
                   9961: 				$unikey='parameter'.$keyroot.'_'.$name;
                   9962: 			    }
1.339     albertel 9963: 			    if ($subp eq 'display') {
                   9964: 				$value.=' [Part: '.$part.']';
                   9965: 			    }
1.599     albertel 9966: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 9967: 			    $metathesekeys{$unikey}=1;
1.599     albertel 9968: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   9969: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 9970: 			    }
1.599     albertel 9971: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   9972: 				$metaentry{':'.$unikey}=
                   9973: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 9974: 			    }
1.339     albertel 9975: 			}
                   9976: 		    }
                   9977: 		} else {
1.172     www      9978: #
                   9979: # This is not a package - some other kind of start tag
1.339     albertel 9980: #
                   9981: 		    my $entry=$token->[1];
1.1068    www      9982: 		    my $unikey='';
1.175     www      9983: 
1.339     albertel 9984: 		    if ($entry eq 'import') {
1.175     www      9985: #
                   9986: # Importing a library here
1.339     albertel 9987: #
1.1067    www      9988:                         my $location=$parser->get_text('/import');
                   9989:                         my $dir=$filename;
                   9990:                         $dir=~s|[^/]*$||;
                   9991:                         $location=&filelocation($dir,$location);
1.1069    www      9992:                        
1.1068    www      9993:                         my $importmode=$token->[2]->{'importmode'};
                   9994:                         if ($importmode eq 'problem') {
1.1069    www      9995: # Import as problem/response
1.1068    www      9996:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9997:                         } elsif ($importmode eq 'part') {
                   9998: # Import as part(s)
1.1069    www      9999:                            $importedparts=1;
                   10000: # We need to get the original file and the imported file to get the part order correct
                   10001: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   10002: # Load and inspect original file
1.1070    www      10003:                            if ($#origfileimportpartids<0) {
                   10004:                               undef(%importedpartids);
                   10005:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   10006:                               my $origfile=&getfile($origfilelocation);
                   10007:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10008:                            }
                   10009: 
1.1069    www      10010: # Load and inspect imported file
                   10011:                            my $impfile=&getfile($location);
                   10012:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10013:                            if ($#impfilepartids>=0) {
                   10014: # This problem had parts
1.1070    www      10015:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      10016:                            } else {
                   10017: # Importing by turning a single problem into a problem part
                   10018: # It gets the import-tags ID as part-ID
                   10019:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      10020:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      10021:                            }
1.1068    www      10022:                         } else {
                   10023: # Normal import
                   10024:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10025:                            if (defined($token->[2]->{'id'})) {
                   10026:                               $unikey.='_'.$token->[2]->{'id'};
                   10027:                            }
1.1067    www      10028:                         }
                   10029: 
1.339     albertel 10030: 			if ($depthcount<20) {
1.736     albertel 10031: 			    my $metadata = 
                   10032: 				&metadata($uri,'keys', $location,$unikey,
                   10033: 					  $depthcount+1);
                   10034: 			    foreach my $meta (split(',',$metadata)) {
                   10035: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   10036: 				$metathesekeys{$meta}=1;
1.339     albertel 10037: 			    }
1.1068    www      10038: 			
                   10039:                         }
1.1067    www      10040: 		    } else {
                   10041: #
                   10042: # Not importing, some other kind of non-package, non-library start tag
                   10043: # 
                   10044:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10045:                         if (defined($token->[2]->{'id'})) {
                   10046:                             $unikey.='_'.$token->[2]->{'id'};
                   10047:                         }
1.339     albertel 10048: 			if (defined($token->[2]->{'name'})) { 
                   10049: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   10050: 			}
                   10051: 			$metathesekeys{$unikey}=1;
1.736     albertel 10052: 			foreach my $param (@{$token->[3]}) {
                   10053: 			    $metaentry{':'.$unikey.'.'.$param} =
                   10054: 				$token->[2]->{$param};
1.339     albertel 10055: 			}
                   10056: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 10057: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 10058: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   10059: 		 # only ws inside the tag, and not in default, so use default
                   10060: 		 # as value
1.599     albertel 10061: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 10062: 			} elsif ( $internaltext =~ /\S/ ) {
                   10063: 		  # something interesting inside the tag
                   10064: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 10065: 			} else {
1.908     albertel 10066: 		  # no interesting values, don't set a default
1.339     albertel 10067: 			}
1.172     www      10068: # end of not-a-package not-a-library import
1.339     albertel 10069: 		    }
1.172     www      10070: # end of not-a-package start tag
1.339     albertel 10071: 		}
1.172     www      10072: # the next is the end of "start tag"
1.339     albertel 10073: 	    }
                   10074: 	}
1.483     albertel 10075: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 10076: 	$extension = lc($extension);
                   10077: 	if ($extension eq 'htm') { $extension='html'; }
                   10078: 
1.737     albertel 10079: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 10080: 	    #no specific packages #how's our extension
                   10081: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 10082: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 10083: 					 \%metathesekeys);
                   10084: 	}
1.883     albertel 10085: 
                   10086: 	if (!exists($metaentry{':packages'})
                   10087: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 10088: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 10089: 		#no specific packages well let's get default then
                   10090: 		if ($key!~/^default&/) { next; }
1.488     albertel 10091: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 10092: 					     \%metathesekeys);
                   10093: 	    }
                   10094: 	}
1.338     www      10095: # are there custom rights to evaluate
1.599     albertel 10096: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 10097: 
1.338     www      10098:     #
                   10099:     # Importing a rights file here
1.339     albertel 10100:     #
                   10101: 	    unless ($depthcount) {
1.599     albertel 10102: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 10103: 		my $dir=$filename;
                   10104: 		$dir=~s|[^/]*$||;
                   10105: 		$location=&filelocation($dir,$location);
1.736     albertel 10106: 		my $rights_metadata =
                   10107: 		    &metadata($uri,'keys',$location,'_rights',
                   10108: 			      $depthcount+1);
                   10109: 		foreach my $rights (split(',',$rights_metadata)) {
                   10110: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   10111: 		    $metathesekeys{$rights}=1;
1.339     albertel 10112: 		}
                   10113: 	    }
                   10114: 	}
1.737     albertel 10115: 	# uniqifiy package listing
                   10116: 	my %seen;
                   10117: 	my @uniq_packages =
                   10118: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   10119: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   10120: 
1.1070    www      10121:         if ($importedparts) {
                   10122: # We had imported parts and need to rebuild partorder
                   10123:            $metaentry{':partorder'}='';
                   10124:            $metathesekeys{'partorder'}=1;
                   10125:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   10126:                if ($origfileimportpartids[$index] eq 'part') {
                   10127: # original part, part of the problem
                   10128:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   10129:                } else {
                   10130: # we have imported parts at this position
                   10131:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   10132:                }
                   10133:            }
                   10134:            $metaentry{':partorder'}=~s/^\,//;
                   10135:         }
                   10136: 
1.737     albertel 10137: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 10138: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   10139: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 10140: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      10141: # this is the end of "was not already recently cached
1.71      www      10142:     }
1.599     albertel 10143:     return $metaentry{':'.$what};
1.261     albertel 10144: }
                   10145: 
1.488     albertel 10146: sub metadata_create_package_def {
1.483     albertel 10147:     my ($uri,$key,$package,$metathesekeys)=@_;
                   10148:     my ($pack,$name,$subp)=split(/\&/,$key);
                   10149:     if ($subp eq 'default') { next; }
                   10150:     
1.599     albertel 10151:     if (defined($metaentry{':packages'})) {
                   10152: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 10153:     } else {
1.599     albertel 10154: 	$metaentry{':packages'}=$package;
1.483     albertel 10155:     }
                   10156:     my $value=$packagetab{$key};
                   10157:     my $unikey;
                   10158:     $unikey='parameter_0_'.$name;
1.599     albertel 10159:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 10160:     $$metathesekeys{$unikey}=1;
1.599     albertel 10161:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10162: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 10163:     }
1.599     albertel 10164:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   10165: 	$metaentry{':'.$unikey}=
                   10166: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 10167:     }
                   10168: }
                   10169: 
1.261     albertel 10170: sub metadata_generate_part0 {
                   10171:     my ($metadata,$metacache,$uri) = @_;
                   10172:     my %allnames;
1.737     albertel 10173:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 10174: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 10175: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   10176: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 10177: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 10178: 	    $allnames{$name}=$part;
                   10179: 	  }
                   10180: 	}
                   10181:     }
                   10182:     foreach my $name (keys(%allnames)) {
                   10183:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 10184:       my $key=":parameter_0_$name";
1.261     albertel 10185:       $$metacache{"$key.part"}='0';
                   10186:       $$metacache{"$key.name"}=$name;
1.428     albertel 10187:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 10188: 					   $allnames{$name}.'_'.$name.
                   10189: 					   '.type'};
1.428     albertel 10190:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 10191: 			     '.display'};
1.644     www      10192:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 10193:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 10194:       $$metacache{"$key.display"}=$olddis;
                   10195:     }
1.71      www      10196: }
                   10197: 
1.764     albertel 10198: # ------------------------------------------------------ Devalidate title cache
                   10199: 
                   10200: sub devalidate_title_cache {
                   10201:     my ($url)=@_;
                   10202:     if (!$env{'request.course.id'}) { return; }
                   10203:     my $symb=&symbread($url);
                   10204:     if (!$symb) { return; }
                   10205:     my $key=$env{'request.course.id'}."\0".$symb;
                   10206:     &devalidate_cache_new('title',$key);
                   10207: }
                   10208: 
1.1014    droeschl 10209: # ------------------------------------------------- Get the title of a course
                   10210: 
                   10211: sub current_course_title {
                   10212:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   10213: }
1.301     www      10214: # ------------------------------------------------- Get the title of a resource
                   10215: 
                   10216: sub gettitle {
                   10217:     my $urlsymb=shift;
                   10218:     my $symb=&symbread($urlsymb);
1.534     albertel 10219:     if ($symb) {
1.620     albertel 10220: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 10221: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 10222: 	if (defined($cached)) { 
                   10223: 	    return $result;
                   10224: 	}
1.534     albertel 10225: 	my ($map,$resid,$url)=&decode_symb($symb);
                   10226: 	my $title='';
1.907     albertel 10227: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   10228: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   10229: 	} else {
                   10230: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10231: 		    &GDBM_READER(),0640)) {
                   10232: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   10233: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   10234: 		untie(%bighash);
                   10235: 	    }
1.534     albertel 10236: 	}
                   10237: 	$title=~s/\&colon\;/\:/gs;
                   10238: 	if ($title) {
1.1159    www      10239: # Remember both $symb and $title for dynamic metadata
                   10240:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      10241:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      10242: # Cache this title and then return it
1.599     albertel 10243: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 10244: 	}
                   10245: 	$urlsymb=$url;
                   10246:     }
                   10247:     my $title=&metadata($urlsymb,'title');
                   10248:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   10249:     return $title;
1.301     www      10250: }
1.613     albertel 10251: 
1.1172.2.13! raeburn  10252: sub getdocspath {
        !          10253:     my ($symb) = @_;
        !          10254:     my $path;
        !          10255:     if ($symb) {
        !          10256:         my ($mapurl,$id,$resurl) = &decode_symb($symb);
        !          10257:         if ($resurl=~/\.(sequence|page)$/) {
        !          10258:             $mapurl=$resurl;
        !          10259:         } elsif ($resurl eq 'adm/navmaps') {
        !          10260:             $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
        !          10261:         }
        !          10262:         my $mapresobj;
        !          10263:         my $navmap = Apache::lonnavmaps::navmap->new();
        !          10264:         if (ref($navmap)) {
        !          10265:             $mapresobj = $navmap->getResourceByUrl($mapurl);
        !          10266:         }
        !          10267:         $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
        !          10268:         my $type=$2;
        !          10269:         if (ref($mapresobj)) {
        !          10270:             my $pcslist = $mapresobj->map_hierarchy();
        !          10271:             if ($pcslist ne '') {
        !          10272:                 foreach my $pc (split(/,/,$pcslist)) {
        !          10273:                     next if ($pc <= 1);
        !          10274:                     my $res = $navmap->getByMapPc($pc);
        !          10275:                     if (ref($res)) {
        !          10276:                         my $thisurl = $res->src();
        !          10277:                         $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
        !          10278:                         my $thistitle = $res->title();
        !          10279:                         $path .= '&'.
        !          10280:                                  &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
        !          10281:                                  &Apache::lonhtmlcommon::entity_encode($thistitle).
        !          10282:                                  ':'.$res->randompick().
        !          10283:                                  ':'.$res->randomout().
        !          10284:                                  ':'.$res->encrypted().
        !          10285:                                  ':'.$res->randomorder().
        !          10286:                                  ':'.$res->is_page();
        !          10287:                     }
        !          10288:                 }
        !          10289:             }
        !          10290:             $path =~ s/^\&//;
        !          10291:             my $maptitle = $mapresobj->title();
        !          10292:             if ($mapurl eq 'default') {
        !          10293:                 $maptitle = 'Main Course Documents';
        !          10294:             }
        !          10295:             $path .= ($path ne '')? '&' : ''.
        !          10296:                     &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
        !          10297:                     &Apache::lonhtmlcommon::entity_encode($maptitle).
        !          10298:                     ':'.$mapresobj->randompick().
        !          10299:                     ':'.$mapresobj->randomout().
        !          10300:                     ':'.$mapresobj->encrypted().
        !          10301:                     ':'.$mapresobj->randomorder().
        !          10302:                     ':'.$mapresobj->is_page();
        !          10303:         } else {
        !          10304:             my $maptitle = &gettitle($mapurl);
        !          10305:             my $ispage;
        !          10306:             if ($mapurl =~ /\.page$/) {
        !          10307:                 $ispage = 1;
        !          10308:             }
        !          10309:             if ($mapurl eq 'default') {
        !          10310:                 $maptitle = 'Main Course Documents';
        !          10311:             }
        !          10312:             $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
        !          10313:                     &Apache::lonhtmlcommon::entity_encode($maptitle).':::::'.$ispage;
        !          10314:         }
        !          10315:         unless ($mapurl eq 'default') {
        !          10316:             $path = 'default&'.
        !          10317:                     &Apache::lonhtmlcommon::entity_encode('Main Course Documents').
        !          10318:                     ':::::&'.$path;
        !          10319:         }
        !          10320:     }
        !          10321:     return $path;
        !          10322: }
        !          10323: 
1.614     albertel 10324: sub get_slot {
                   10325:     my ($which,$cnum,$cdom)=@_;
                   10326:     if (!$cnum || !$cdom) {
1.790     albertel 10327: 	(undef,my $courseid)=&whichuser();
1.620     albertel 10328: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   10329: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 10330:     }
1.703     albertel 10331:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   10332:     my %slotinfo;
                   10333:     if (exists($remembered{$key})) {
                   10334: 	$slotinfo{$which} = $remembered{$key};
                   10335:     } else {
                   10336: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   10337: 	&Apache::lonhomework::showhash(%slotinfo);
                   10338: 	my ($tmp)=keys(%slotinfo);
                   10339: 	if ($tmp=~/^error:/) { return (); }
                   10340: 	$remembered{$key} = $slotinfo{$which};
                   10341:     }
1.616     albertel 10342:     if (ref($slotinfo{$which}) eq 'HASH') {
                   10343: 	return %{$slotinfo{$which}};
                   10344:     }
                   10345:     return $slotinfo{$which};
1.614     albertel 10346: }
1.1150    raeburn  10347: 
                   10348: sub get_reservable_slots {
                   10349:     my ($cnum,$cdom,$uname,$udom) = @_;
                   10350:     my $now = time;
                   10351:     my $reservable_info;
                   10352:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   10353:     if (exists($remembered{$key})) {
                   10354:         $reservable_info = $remembered{$key};
                   10355:     } else {
                   10356:         my %resv;
                   10357:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   10358:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   10359:         $reservable_info = \%resv;
                   10360:         $remembered{$key} = $reservable_info;
                   10361:     }
                   10362:     return $reservable_info;
                   10363: }
                   10364: 
                   10365: sub get_course_slots {
                   10366:     my ($cnum,$cdom) = @_;
                   10367:     my $hashid=$cnum.':'.$cdom;
                   10368:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   10369:     if (defined($cached)) {
                   10370:         if (ref($result) eq 'HASH') {
                   10371:             return %{$result};
                   10372:         }
                   10373:     } else {
                   10374:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   10375:         my ($tmp) = keys(%slots);
                   10376:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   10377:             &Apache::lonnet::do_cache_new('allslots',$hashid,\%slots,600);
                   10378:             return %slots;
                   10379:         }
                   10380:     }
                   10381:     return;
                   10382: }
                   10383: 
                   10384: sub devalidate_slots_cache {
                   10385:     my ($cnum,$cdom)=@_;
                   10386:     my $hashid=$cnum.':'.$cdom;
                   10387:     &devalidate_cache_new('allslots',$hashid);
                   10388: }
                   10389: 
1.1172.2.8  raeburn  10390: sub get_coursechange {
                   10391:     my ($cdom,$cnum) = @_;
                   10392:     if ($cdom eq '' || $cnum eq '') {
                   10393:         return unless ($env{'request.course.id'});
                   10394:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10395:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10396:     }
                   10397:     my $hashid=$cdom.'_'.$cnum;
                   10398:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   10399:     if ((defined($cached)) && ($change ne '')) {
                   10400:         return $change;
                   10401:     } else {
                   10402:         my %crshash;
                   10403:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   10404:         if ($crshash{'internal.contentchange'} eq '') {
                   10405:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   10406:             if ($change eq '') {
                   10407:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   10408:                 $change = $crshash{'internal.created'};
                   10409:             }
                   10410:         } else {
                   10411:             $change = $crshash{'internal.contentchange'};
                   10412:         }
                   10413:         my $cachetime = 600;
                   10414:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   10415:     }
                   10416:     return $change;
                   10417: }
                   10418: 
                   10419: sub devalidate_coursechange_cache {
                   10420:     my ($cnum,$cdom)=@_;
                   10421:     my $hashid=$cnum.':'.$cdom;
                   10422:     &devalidate_cache_new('crschange',$hashid);
                   10423: }
                   10424: 
1.31      www      10425: # ------------------------------------------------- Update symbolic store links
                   10426: 
                   10427: sub symblist {
                   10428:     my ($mapname,%newhash)=@_;
1.438     www      10429:     $mapname=&deversion(&declutter($mapname));
1.31      www      10430:     my %hash;
1.620     albertel 10431:     if (($env{'request.course.fn'}) && (%newhash)) {
                   10432:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10433:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  10434: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 10435: 		next if ($url eq 'last_known'
                   10436: 			 && $env{'form.no_update_last_known'});
                   10437: 		$hash{declutter($url)}=&encode_symb($mapname,
                   10438: 						    $newhash{$url}->[1],
                   10439: 						    $newhash{$url}->[0]);
1.191     harris41 10440:             }
1.31      www      10441:             if (untie(%hash)) {
                   10442: 		return 'ok';
                   10443:             }
                   10444:         }
                   10445:     }
                   10446:     return 'error';
1.212     www      10447: }
                   10448: 
                   10449: # --------------------------------------------------------------- Verify a symb
                   10450: 
                   10451: sub symbverify {
1.1172.2.11  raeburn  10452:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      10453:     my $thisfn=$thisurl;
1.439     www      10454:     $thisfn=&declutter($thisfn);
1.215     www      10455: # direct jump to resource in page or to a sequence - will construct own symbs
                   10456:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   10457: # check URL part
1.409     www      10458:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      10459: 
1.431     www      10460:     unless ($url eq $thisfn) { return 0; }
1.213     www      10461: 
1.216     www      10462:     $symb=&symbclean($symb);
1.510     www      10463:     $thisurl=&deversion($thisurl);
1.439     www      10464:     $thisfn=&deversion($thisfn);
1.213     www      10465: 
                   10466:     my %bighash;
                   10467:     my $okay=0;
1.431     www      10468: 
1.620     albertel 10469:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10470:                             &GDBM_READER(),0640)) {
1.1172.2.13! raeburn  10471:         my $noclutter;
1.1032    raeburn  10472:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   10473:             $thisurl =~ s/\?.+$//;
1.1172.2.13! raeburn  10474:             if ($map =~ m{^uploaded/.+\.page$}) {
        !          10475:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
        !          10476:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
        !          10477:                 $noclutter = 1;
        !          10478:             }
        !          10479:         }
        !          10480:         my $ids;
        !          10481:         if ($noclutter) {
        !          10482:             $ids=$bighash{'ids_'.$thisurl};
        !          10483:         } else {
        !          10484:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  10485:         }
1.1102    raeburn  10486:         unless ($ids) {
1.1172.2.13! raeburn  10487:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  10488:             $ids=$bighash{$idkey};
1.216     www      10489:         }
                   10490:         if ($ids) {
                   10491: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13! raeburn  10492:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
        !          10493:                 $symb =~ s/\?.+$//;
        !          10494:             }
1.800     albertel 10495: 	    foreach my $id (split(/\,/,$ids)) {
                   10496: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      10497:                if (
                   10498:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13! raeburn  10499:    eq $symb) {
1.1172.2.11  raeburn  10500:                    if (ref($encstate)) {
                   10501:                        $$encstate = $bighash{'encrypted_'.$id};
                   10502:                    }
1.1172.2.13! raeburn  10503:                    if (($env{'request.role.adv'}) ||
        !          10504:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  10505:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13! raeburn  10506:                        $okay=1;
        !          10507:                        last;
        !          10508:                    }
        !          10509:                }
        !          10510:            }
1.216     www      10511:         }
1.213     www      10512: 	untie(%bighash);
                   10513:     }
                   10514:     return $okay;
1.31      www      10515: }
                   10516: 
1.210     www      10517: # --------------------------------------------------------------- Clean-up symb
                   10518: 
                   10519: sub symbclean {
                   10520:     my $symb=shift;
1.568     albertel 10521:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      10522: # remove version from map
                   10523:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      10524: 
1.210     www      10525: # remove version from URL
                   10526:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      10527: 
1.507     www      10528: # remove wrapper
                   10529: 
1.510     www      10530:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 10531:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      10532:     return $symb;
1.409     www      10533: }
                   10534: 
                   10535: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 10536: 
                   10537: sub encode_symb {
                   10538:     my ($map,$resid,$url)=@_;
                   10539:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   10540: }
1.409     www      10541: 
                   10542: sub decode_symb {
1.568     albertel 10543:     my $symb=shift;
                   10544:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   10545:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      10546:     return (&fixversion($map),$resid,&fixversion($url));
                   10547: }
                   10548: 
                   10549: sub fixversion {
                   10550:     my $fn=shift;
1.609     banghart 10551:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      10552:     my %bighash;
                   10553:     my $uri=&clutter($fn);
1.620     albertel 10554:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      10555: # is this cached?
1.599     albertel 10556:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      10557:     if (defined($cached)) { return $result; }
                   10558: # unfortunately not cached, or expired
1.620     albertel 10559:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      10560: 	    &GDBM_READER(),0640)) {
                   10561:  	if ($bighash{'version_'.$uri}) {
                   10562:  	    my $version=$bighash{'version_'.$uri};
1.444     www      10563:  	    unless (($version eq 'mostrecent') || 
                   10564: 		    ($version==&getversion($uri))) {
1.440     www      10565:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   10566:  	    }
                   10567:  	}
                   10568:  	untie %bighash;
1.413     www      10569:     }
1.599     albertel 10570:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      10571: }
                   10572: 
                   10573: sub deversion {
                   10574:     my $url=shift;
                   10575:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   10576:     return $url;
1.210     www      10577: }
                   10578: 
1.31      www      10579: # ------------------------------------------------------ Return symb list entry
                   10580: 
                   10581: sub symbread {
1.249     www      10582:     my ($thisfn,$donotrecurse)=@_;
1.1172.2.13! raeburn  10583:     my $cache_str;
        !          10584:     if ($thisfn ne '') {
        !          10585:         $cache_str='request.symbread.cached.'.$thisfn;
        !          10586:         if ($env{$cache_str} ne '') {
1.1172.2.8  raeburn  10587:             return $env{$cache_str};
                   10588:         }
1.1172.2.13! raeburn  10589:    } else {
1.242     www      10590: # no filename provided? try from environment
1.620     albertel 10591:         if ($env{'request.symb'}) {
1.1172.2.13! raeburn  10592:             return $env{$cache_str}=&symbclean($env{'request.symb'});
        !          10593:         }
        !          10594:         $thisfn=$env{'request.filename'};
1.44      www      10595:     }
1.569     albertel 10596:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      10597: # is that filename actually a symb? Verify, clean, and return
                   10598:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 10599: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 10600: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 10601: 	}
1.242     www      10602:     }
1.44      www      10603:     $thisfn=declutter($thisfn);
1.31      www      10604:     my %hash;
1.37      www      10605:     my %bighash;
                   10606:     my $syval='';
1.620     albertel 10607:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  10608:         my $targetfn = $thisfn;
1.609     banghart 10609:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  10610:             $targetfn = 'adm/wrapper/'.$thisfn;
                   10611:         }
1.687     albertel 10612: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   10613: 	    $targetfn=$1;
                   10614: 	}
1.620     albertel 10615:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10616:                       &GDBM_READER(),0640)) {
1.481     raeburn  10617: 	    $syval=$hash{$targetfn};
1.37      www      10618:             untie(%hash);
                   10619:         }
                   10620: # ---------------------------------------------------------- There was an entry
                   10621:         if ($syval) {
1.601     albertel 10622: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 10623: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  10624: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10625: 		    #return $env{$cache_str}='';
1.601     albertel 10626: 		#}    
                   10627: 		#$syval.=$1;
                   10628: 	    #}
1.37      www      10629:         } else {
                   10630: # ------------------------------------------------------- Was not in symb table
1.620     albertel 10631:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10632:                             &GDBM_READER(),0640)) {
1.37      www      10633: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      10634:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      10635:               unless ($ids) { 
                   10636:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      10637:               }
                   10638:               unless ($ids) {
                   10639: # alias?
                   10640: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      10641:               }
1.37      www      10642:               if ($ids) {
                   10643: # ------------------------------------------------------------------- Has ID(s)
                   10644:                  my @possibilities=split(/\,/,$ids);
1.39      www      10645:                  if ($#possibilities==0) {
                   10646: # ----------------------------------------------- There is only one possibility
1.37      www      10647: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 10648: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10649: 						    $resid,$thisfn);
1.249     www      10650:                  } elsif (!$donotrecurse) {
1.39      www      10651: # ------------------------------------------ There is more than one possibility
                   10652:                      my $realpossible=0;
1.800     albertel 10653:                      foreach my $id (@possibilities) {
                   10654: 			 my $file=$bighash{'src_'.$id};
1.39      www      10655:                          if (&allowed('bre',$file)) {
1.800     albertel 10656:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      10657:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   10658: 				$realpossible++;
1.626     albertel 10659:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10660: 						    $resid,$thisfn);
1.39      www      10661:                             }
                   10662: 			 }
1.191     harris41 10663:                      }
1.39      www      10664: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      10665:                  } else {
                   10666:                      $syval='';
1.37      www      10667:                  }
                   10668: 	      }
                   10669:               untie(%bighash)
1.481     raeburn  10670:            }
1.31      www      10671:         }
1.62      www      10672:         if ($syval) {
1.620     albertel 10673: 	    return $env{$cache_str}=$syval;
1.62      www      10674:         }
1.31      www      10675:     }
1.949     raeburn  10676:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10677:     return $env{$cache_str}='';
1.31      www      10678: }
                   10679: 
                   10680: # ---------------------------------------------------------- Return random seed
                   10681: 
1.32      www      10682: sub numval {
                   10683:     my $txt=shift;
                   10684:     $txt=~tr/A-J/0-9/;
                   10685:     $txt=~tr/a-j/0-9/;
                   10686:     $txt=~tr/K-T/0-9/;
                   10687:     $txt=~tr/k-t/0-9/;
                   10688:     $txt=~tr/U-Z/0-5/;
                   10689:     $txt=~tr/u-z/0-5/;
                   10690:     $txt=~s/\D//g;
1.564     albertel 10691:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      10692:     return int($txt);
1.368     albertel 10693: }
                   10694: 
1.484     albertel 10695: sub numval2 {
                   10696:     my $txt=shift;
                   10697:     $txt=~tr/A-J/0-9/;
                   10698:     $txt=~tr/a-j/0-9/;
                   10699:     $txt=~tr/K-T/0-9/;
                   10700:     $txt=~tr/k-t/0-9/;
                   10701:     $txt=~tr/U-Z/0-5/;
                   10702:     $txt=~tr/u-z/0-5/;
                   10703:     $txt=~s/\D//g;
                   10704:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10705:     my $total;
                   10706:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 10707:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 10708:     return int($total);
                   10709: }
                   10710: 
1.575     albertel 10711: sub numval3 {
                   10712:     use integer;
                   10713:     my $txt=shift;
                   10714:     $txt=~tr/A-J/0-9/;
                   10715:     $txt=~tr/a-j/0-9/;
                   10716:     $txt=~tr/K-T/0-9/;
                   10717:     $txt=~tr/k-t/0-9/;
                   10718:     $txt=~tr/U-Z/0-5/;
                   10719:     $txt=~tr/u-z/0-5/;
                   10720:     $txt=~s/\D//g;
                   10721:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10722:     my $total;
                   10723:     foreach my $val (@txts) { $total+=$val; }
                   10724:     if ($_64bit) { $total=(($total<<32)>>32); }
                   10725:     return $total;
                   10726: }
                   10727: 
1.675     albertel 10728: sub digest {
                   10729:     my ($data)=@_;
                   10730:     my $digest=&Digest::MD5::md5($data);
                   10731:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   10732:     my ($e,$f);
                   10733:     {
                   10734:         use integer;
                   10735:         $e=($a+$b);
                   10736:         $f=($c+$d);
                   10737:         if ($_64bit) {
                   10738:             $e=(($e<<32)>>32);
                   10739:             $f=(($f<<32)>>32);
                   10740:         }
                   10741:     }
                   10742:     if (wantarray) {
                   10743: 	return ($e,$f);
                   10744:     } else {
                   10745: 	my $g;
                   10746: 	{
                   10747: 	    use integer;
                   10748: 	    $g=($e+$f);
                   10749: 	    if ($_64bit) {
                   10750: 		$g=(($g<<32)>>32);
                   10751: 	    }
                   10752: 	}
                   10753: 	return $g;
                   10754:     }
                   10755: }
                   10756: 
1.368     albertel 10757: sub latest_rnd_algorithm_id {
1.675     albertel 10758:     return '64bit5';
1.366     albertel 10759: }
1.32      www      10760: 
1.503     albertel 10761: sub get_rand_alg {
                   10762:     my ($courseid)=@_;
1.790     albertel 10763:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 10764:     if ($courseid) {
1.620     albertel 10765: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 10766:     }
                   10767:     return &latest_rnd_algorithm_id();
                   10768: }
                   10769: 
1.562     albertel 10770: sub validCODE {
                   10771:     my ($CODE)=@_;
                   10772:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   10773:     return 0;
                   10774: }
                   10775: 
1.491     albertel 10776: sub getCODE {
1.620     albertel 10777:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 10778:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   10779: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   10780: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 10781: 	return $Apache::lonhomework::history{'resource.CODE'};
                   10782:     }
                   10783:     return undef;
                   10784: }
1.1133    foxr     10785: #
                   10786: #  Determines the random seed for a specific context:
                   10787: #
                   10788: # parameters:
                   10789: #   symb      - in course context the symb for the seed.
                   10790: #   course_id - The course id of the form domain_coursenum.
                   10791: #   domain    - Domain for the user.
                   10792: #   course    - Course for the user.
                   10793: #   cenv      - environment of the course.
                   10794: #
                   10795: # NOTE:
                   10796: #   All parameters are picked out of the environment if missing
                   10797: #   or not defined.
                   10798: #   If a symb cannot be determined the current time is used instead.
                   10799: #
                   10800: #  For a given well defined symb, courside, domain, username,
                   10801: #  and course environment, the seed is reproducible.
                   10802: #
1.31      www      10803: sub rndseed {
1.1133    foxr     10804:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 10805:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 10806:     if (!defined($symb)) {
1.366     albertel 10807: 	unless ($symb=$wsymb) { return time; }
                   10808:     }
1.1146    foxr     10809:     if (!defined $courseid) { 
                   10810: 	$courseid=$wcourseid; 
                   10811:     }
                   10812:     if (!defined $domain) { $domain=$wdomain; }
                   10813:     if (!defined $username) { $username=$wusername }
1.1133    foxr     10814: 
                   10815:     my $which;
                   10816:     if (defined($cenv->{'rndseed'})) {
                   10817: 	$which = $cenv->{'rndseed'};
                   10818:     } else {
                   10819: 	$which =&get_rand_alg($courseid);
                   10820:     }
1.491     albertel 10821:     if (defined(&getCODE())) {
1.675     albertel 10822: 	if ($which eq '64bit5') {
                   10823: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   10824: 	} elsif ($which eq '64bit4') {
1.575     albertel 10825: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   10826: 	} else {
                   10827: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   10828: 	}
1.675     albertel 10829:     } elsif ($which eq '64bit5') {
                   10830: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 10831:     } elsif ($which eq '64bit4') {
                   10832: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 10833:     } elsif ($which eq '64bit3') {
                   10834: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 10835:     } elsif ($which eq '64bit2') {
                   10836: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 10837:     } elsif ($which eq '64bit') {
                   10838: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   10839:     }
                   10840:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   10841: }
                   10842: 
                   10843: sub rndseed_32bit {
                   10844:     my ($symb,$courseid,$domain,$username)=@_;
                   10845:     {
                   10846: 	use integer;
                   10847: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   10848: 	my $symbseed=numval($symb) << 22;
                   10849: 	my $namechck=unpack("%32C*",$username) << 17;
                   10850: 	my $nameseed=numval($username) << 12;
                   10851: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   10852: 	my $courseseed=unpack("%32C*",$courseid);
                   10853: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 10854: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10855: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 10856: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 10857: 	return $num;
                   10858:     }
                   10859: }
                   10860: 
                   10861: sub rndseed_64bit {
                   10862:     my ($symb,$courseid,$domain,$username)=@_;
                   10863:     {
                   10864: 	use integer;
                   10865: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   10866: 	my $symbseed=numval($symb) << 10;
                   10867: 	my $namechck=unpack("%32S*",$username);
                   10868: 	
                   10869: 	my $nameseed=numval($username) << 21;
                   10870: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   10871: 	my $courseseed=unpack("%32S*",$courseid);
                   10872: 	
                   10873: 	my $num1=$symbchck+$symbseed+$namechck;
                   10874: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10875: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10876: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 10877: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 10878: 	return "$num1,$num2";
1.155     albertel 10879:     }
1.366     albertel 10880: }
                   10881: 
1.443     albertel 10882: sub rndseed_64bit2 {
                   10883:     my ($symb,$courseid,$domain,$username)=@_;
                   10884:     {
                   10885: 	use integer;
                   10886: 	# strings need to be an even # of cahracters long, it it is odd the
                   10887:         # last characters gets thrown away
                   10888: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10889: 	my $symbseed=numval($symb) << 10;
                   10890: 	my $namechck=unpack("%32S*",$username.' ');
                   10891: 	
                   10892: 	my $nameseed=numval($username) << 21;
1.501     albertel 10893: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10894: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10895: 	
                   10896: 	my $num1=$symbchck+$symbseed+$namechck;
                   10897: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10898: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10899: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 10900: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 10901: 	return "$num1,$num2";
                   10902:     }
                   10903: }
                   10904: 
                   10905: sub rndseed_64bit3 {
                   10906:     my ($symb,$courseid,$domain,$username)=@_;
                   10907:     {
                   10908: 	use integer;
                   10909: 	# strings need to be an even # of cahracters long, it it is odd the
                   10910:         # last characters gets thrown away
                   10911: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10912: 	my $symbseed=numval2($symb) << 10;
                   10913: 	my $namechck=unpack("%32S*",$username.' ');
                   10914: 	
                   10915: 	my $nameseed=numval2($username) << 21;
1.443     albertel 10916: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10917: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10918: 	
                   10919: 	my $num1=$symbchck+$symbseed+$namechck;
                   10920: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10921: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10922: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 10923: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      10924: 	
1.503     albertel 10925: 	return "$num1:$num2";
1.443     albertel 10926:     }
                   10927: }
                   10928: 
1.575     albertel 10929: sub rndseed_64bit4 {
                   10930:     my ($symb,$courseid,$domain,$username)=@_;
                   10931:     {
                   10932: 	use integer;
                   10933: 	# strings need to be an even # of cahracters long, it it is odd the
                   10934:         # last characters gets thrown away
                   10935: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10936: 	my $symbseed=numval3($symb) << 10;
                   10937: 	my $namechck=unpack("%32S*",$username.' ');
                   10938: 	
                   10939: 	my $nameseed=numval3($username) << 21;
                   10940: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10941: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10942: 	
                   10943: 	my $num1=$symbchck+$symbseed+$namechck;
                   10944: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10945: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10946: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 10947: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      10948: 	
1.575     albertel 10949: 	return "$num1:$num2";
                   10950:     }
                   10951: }
                   10952: 
1.675     albertel 10953: sub rndseed_64bit5 {
                   10954:     my ($symb,$courseid,$domain,$username)=@_;
                   10955:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   10956:     return "$num1:$num2";
                   10957: }
                   10958: 
1.366     albertel 10959: sub rndseed_CODE_64bit {
                   10960:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 10961:     {
1.366     albertel 10962: 	use integer;
1.443     albertel 10963: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 10964: 	my $symbseed=numval2($symb);
1.491     albertel 10965: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   10966: 	my $CODEseed=numval(&getCODE());
1.443     albertel 10967: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 10968: 	my $num1=$symbseed+$CODEchck;
                   10969: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 10970: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   10971: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 10972: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   10973: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 10974: 	return "$num1:$num2";
1.366     albertel 10975:     }
                   10976: }
                   10977: 
1.575     albertel 10978: sub rndseed_CODE_64bit4 {
                   10979:     my ($symb,$courseid,$domain,$username)=@_;
                   10980:     {
                   10981: 	use integer;
                   10982: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   10983: 	my $symbseed=numval3($symb);
                   10984: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   10985: 	my $CODEseed=numval3(&getCODE());
                   10986: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10987: 	my $num1=$symbseed+$CODEchck;
                   10988: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 10989: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   10990: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 10991: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   10992: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   10993: 	return "$num1:$num2";
                   10994:     }
                   10995: }
                   10996: 
1.675     albertel 10997: sub rndseed_CODE_64bit5 {
                   10998:     my ($symb,$courseid,$domain,$username)=@_;
                   10999:     my $code = &getCODE();
                   11000:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   11001:     return "$num1:$num2";
                   11002: }
                   11003: 
1.366     albertel 11004: sub setup_random_from_rndseed {
                   11005:     my ($rndseed)=@_;
1.503     albertel 11006:     if ($rndseed =~/([,:])/) {
                   11007: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 11008: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   11009:     } else {
                   11010: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 11011:     }
1.36      albertel 11012: }
                   11013: 
1.474     albertel 11014: sub latest_receipt_algorithm_id {
1.835     albertel 11015:     return 'receipt3';
1.474     albertel 11016: }
                   11017: 
1.480     www      11018: sub recunique {
                   11019:     my $fucourseid=shift;
                   11020:     my $unique;
1.835     albertel 11021:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   11022: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11023: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      11024:     } else {
                   11025: 	$unique=$perlvar{'lonReceipt'};
                   11026:     }
                   11027:     return unpack("%32C*",$unique);
                   11028: }
                   11029: 
                   11030: sub recprefix {
                   11031:     my $fucourseid=shift;
                   11032:     my $prefix;
1.835     albertel 11033:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   11034: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11035: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      11036:     } else {
                   11037: 	$prefix=$perlvar{'lonHostID'};
                   11038:     }
                   11039:     return unpack("%32C*",$prefix);
                   11040: }
                   11041: 
1.76      www      11042: sub ireceipt {
1.474     albertel 11043:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 11044: 
                   11045:     my $return =&recprefix($fucourseid).'-';
                   11046: 
                   11047:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   11048: 	$env{'request.state'} eq 'construct') {
                   11049: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   11050: 	return $return;
                   11051:     }
                   11052: 
1.76      www      11053:     my $cuname=unpack("%32C*",$funame);
                   11054:     my $cudom=unpack("%32C*",$fudom);
                   11055:     my $cucourseid=unpack("%32C*",$fucourseid);
                   11056:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      11057:     my $cunique=&recunique($fucourseid);
1.474     albertel 11058:     my $cpart=unpack("%32S*",$part);
1.835     albertel 11059:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   11060: 
1.790     albertel 11061: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 11062: 			       
                   11063: 	$return.= ($cunique%$cuname+
                   11064: 		   $cunique%$cudom+
                   11065: 		   $cusymb%$cuname+
                   11066: 		   $cusymb%$cudom+
                   11067: 		   $cucourseid%$cuname+
                   11068: 		   $cucourseid%$cudom+
                   11069: 		   $cpart%$cuname+
                   11070: 		   $cpart%$cudom);
                   11071:     } else {
                   11072: 	$return.= ($cunique%$cuname+
                   11073: 		   $cunique%$cudom+
                   11074: 		   $cusymb%$cuname+
                   11075: 		   $cusymb%$cudom+
                   11076: 		   $cucourseid%$cuname+
                   11077: 		   $cucourseid%$cudom);
                   11078:     }
                   11079:     return $return;
1.76      www      11080: }
                   11081: 
                   11082: sub receipt {
1.474     albertel 11083:     my ($part)=@_;
1.790     albertel 11084:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 11085:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      11086: }
1.260     ng       11087: 
1.790     albertel 11088: sub whichuser {
                   11089:     my ($passedsymb)=@_;
                   11090:     my ($symb,$courseid,$domain,$name,$publicuser);
                   11091:     if (defined($env{'form.grade_symb'})) {
                   11092: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   11093: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   11094: 	if (!$allowed &&
                   11095: 	    exists($env{'request.course.sec'}) &&
                   11096: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   11097: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   11098: 			      '/'.$env{'request.course.sec'});
                   11099: 	}
                   11100: 	if ($allowed) {
                   11101: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   11102: 	    $courseid=$tmp_courseid;
                   11103: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   11104: 	    ($name)=&get_env_multiple('form.grade_username');
                   11105: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   11106: 	}
                   11107:     }
                   11108:     if (!$passedsymb) {
                   11109: 	$symb=&symbread();
                   11110:     } else {
                   11111: 	$symb=$passedsymb;
                   11112:     }
                   11113:     $courseid=$env{'request.course.id'};
                   11114:     $domain=$env{'user.domain'};
                   11115:     $name=$env{'user.name'};
                   11116:     if ($name eq 'public' && $domain eq 'public') {
                   11117: 	if (!defined($env{'form.username'})) {
                   11118: 	    $env{'form.username'}.=time.rand(10000000);
                   11119: 	}
                   11120: 	$name.=$env{'form.username'};
                   11121:     }
                   11122:     return ($symb,$courseid,$domain,$name,$publicuser);
                   11123: 
                   11124: }
                   11125: 
1.36      albertel 11126: # ------------------------------------------------------------ Serves up a file
1.472     albertel 11127: # returns either the contents of the file or 
                   11128: # -1 if the file doesn't exist
1.481     raeburn  11129: #
                   11130: # if the target is a file that was uploaded via DOCS, 
                   11131: # a check will be made to see if a current copy exists on the local server,
                   11132: # if it does this will be served, otherwise a copy will be retrieved from
                   11133: # the home server for the course and stored in /home/httpd/html/userfiles on
                   11134: # the local server.   
1.472     albertel 11135: 
1.36      albertel 11136: sub getfile {
1.538     albertel 11137:     my ($file) = @_;
1.609     banghart 11138:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 11139:     &repcopy($file);
                   11140:     return &readfile($file);
                   11141: }
                   11142: 
                   11143: sub repcopy_userfile {
                   11144:     my ($file)=@_;
1.1142    raeburn  11145:     my $londocroot = $perlvar{'lonDocRoot'};
                   11146:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  11147:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 11148:     my ($cdom,$cnum,$filename) = 
1.811     albertel 11149: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 11150:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   11151:     if (-e "$file") {
1.828     www      11152: # we already have a local copy, check it out
1.538     albertel 11153: 	my @fileinfo = stat($file);
1.828     www      11154: 	my $rtncode;
                   11155: 	my $info;
1.538     albertel 11156: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 11157: 	if ($lwpresp ne 'ok') {
1.828     www      11158: # there is no such file anymore, even though we had a local copy
1.482     albertel 11159: 	    if ($rtncode eq '404') {
1.538     albertel 11160: 		unlink($file);
1.482     albertel 11161: 	    }
                   11162: 	    return -1;
                   11163: 	}
                   11164: 	if ($info < $fileinfo[9]) {
1.828     www      11165: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  11166: 	    return 'ok';
1.828     www      11167: 	} else {
                   11168: # the file is outdated, get rid of it
                   11169: 	    unlink($file);
1.482     albertel 11170: 	}
1.828     www      11171:     }
                   11172: # one way or the other, at this point, we don't have the file
                   11173: # construct the correct path for the file
                   11174:     my @parts = ($cdom,$cnum); 
                   11175:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   11176: 	push @parts, split(/\//,$1);
                   11177:     }
                   11178:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   11179:     foreach my $part (@parts) {
                   11180: 	$path .= '/'.$part;
                   11181: 	if (!-e $path) {
                   11182: 	    mkdir($path,0770);
1.482     albertel 11183: 	}
                   11184:     }
1.828     www      11185: # now the path exists for sure
                   11186: # get a user agent
                   11187:     my $ua=new LWP::UserAgent;
                   11188:     my $transferfile=$file.'.in.transfer';
                   11189: # FIXME: this should flock
                   11190:     if (-e $transferfile) { return 'ok'; }
                   11191:     my $request;
                   11192:     $uri=~s/^\///;
1.980     raeburn  11193:     my $homeserver = &homeserver($cnum,$cdom);
                   11194:     my $protocol = $protocol{$homeserver};
                   11195:     $protocol = 'http' if ($protocol ne 'https');
                   11196:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      11197:     my $response=$ua->request($request,$transferfile);
                   11198: # did it work?
                   11199:     if ($response->is_error()) {
                   11200: 	unlink($transferfile);
                   11201: 	&logthis("Userfile repcopy failed for $uri");
                   11202: 	return -1;
                   11203:     }
                   11204: # worked, rename the transfer file
                   11205:     rename($transferfile,$file);
1.607     raeburn  11206:     return 'ok';
1.481     raeburn  11207: }
                   11208: 
1.517     albertel 11209: sub tokenwrapper {
                   11210:     my $uri=shift;
1.980     raeburn  11211:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 11212:     $uri=~s|^/||;
1.620     albertel 11213:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 11214:     my $token=$1;
1.552     albertel 11215:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   11216:     if ($udom && $uname && $file) {
                   11217: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  11218:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  11219:         my $homeserver = &homeserver($uname,$udom);
                   11220:         my $protocol = $protocol{$homeserver};
                   11221:         $protocol = 'http' if ($protocol ne 'https');
                   11222:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 11223:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   11224:                                '&tokenissued='.$perlvar{'lonHostID'};
                   11225:     } else {
                   11226:         return '/adm/notfound.html';
                   11227:     }
                   11228: }
                   11229: 
1.828     www      11230: # call with reqtype HEAD: get last modification time
                   11231: # call with reqtype GET: get the file contents
                   11232: # Do not call this with reqtype GET for large files! It loads everything into memory
                   11233: #
1.481     raeburn  11234: sub getuploaded {
                   11235:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   11236:     $uri=~s/^\///;
1.980     raeburn  11237:     my $homeserver = &homeserver($cnum,$cdom);
                   11238:     my $protocol = $protocol{$homeserver};
                   11239:     $protocol = 'http' if ($protocol ne 'https');
                   11240:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  11241:     my $ua=new LWP::UserAgent;
                   11242:     my $request=new HTTP::Request($reqtype,$uri);
                   11243:     my $response=$ua->request($request);
                   11244:     $$rtncode = $response->code;
1.482     albertel 11245:     if (! $response->is_success()) {
                   11246: 	return 'failed';
                   11247:     }      
                   11248:     if ($reqtype eq 'HEAD') {
1.486     www      11249: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 11250:     } elsif ($reqtype eq 'GET') {
                   11251: 	$$info = $response->content;
1.472     albertel 11252:     }
1.482     albertel 11253:     return 'ok';
1.36      albertel 11254: }
                   11255: 
1.481     raeburn  11256: sub readfile {
                   11257:     my $file = shift;
                   11258:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   11259:     my $fh;
                   11260:     open($fh,"<$file");
                   11261:     my $a='';
1.800     albertel 11262:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  11263:     return $a;
                   11264: }
                   11265: 
1.36      albertel 11266: sub filelocation {
1.590     banghart 11267:     my ($dir,$file) = @_;
                   11268:     my $location;
                   11269:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 11270: 
                   11271:     if ($file =~ m-^/adm/-) {
                   11272: 	$file=~s-^/adm/wrapper/-/-;
                   11273: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   11274:     }
1.882     albertel 11275: 
1.1139    www      11276:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  11277:         $location = $file;
1.609     banghart 11278:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 11279:         my ($udom,$uname,$filename)=
1.811     albertel 11280:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 11281:         my $home=&homeserver($uname,$udom);
                   11282:         my $is_me=0;
                   11283:         my @ids=&current_machine_ids();
                   11284:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   11285:         if ($is_me) {
1.1117    foxr     11286:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 11287:         } else {
                   11288:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   11289:   	      $udom.'/'.$uname.'/'.$filename;
                   11290:         }
1.882     albertel 11291:     } elsif ($file =~ m-^/adm/-) {
                   11292: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 11293:     } else {
                   11294:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      11295:         $file=~s:^/(res|priv)/:/:;
                   11296:         my $space=$1;
1.590     banghart 11297:         if ( !( $file =~ m:^/:) ) {
                   11298:             $location = $dir. '/'.$file;
                   11299:         } else {
1.1142    raeburn  11300:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 11301:         }
1.59      albertel 11302:     }
1.590     banghart 11303:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 11304:     while ($location=~m{/\.\./}) {
                   11305: 	if ($location =~ m{/[^/]+/\.\./}) {
                   11306: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   11307: 	} else {
                   11308: 	    $location=~ s{/\.\./}{/}g;
                   11309: 	}
                   11310:     } #remove dir/..
1.590     banghart 11311:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   11312:     return $location;
1.46      www      11313: }
1.36      albertel 11314: 
1.46      www      11315: sub hreflocation {
                   11316:     my ($dir,$file)=@_;
1.980     raeburn  11317:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 11318: 	$file=filelocation($dir,$file);
1.700     albertel 11319:     } elsif ($file=~m-^/adm/-) {
                   11320: 	$file=~s-^/adm/wrapper/-/-;
                   11321: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 11322:     }
                   11323:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   11324: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   11325:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  11326: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   11327: 	        {/uploaded/$1/$2/}x;
1.46      www      11328:     }
1.913     albertel 11329:     if ($file=~ m{^/userfiles/}) {
                   11330: 	$file =~ s{^/userfiles/}{/uploaded/};
                   11331:     }
1.462     albertel 11332:     return $file;
1.465     albertel 11333: }
                   11334: 
1.1139    www      11335: 
                   11336: 
                   11337: 
                   11338: 
1.465     albertel 11339: sub current_machine_domains {
1.853     albertel 11340:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   11341: }
                   11342: 
                   11343: sub machine_domains {
                   11344:     my ($hostname) = @_;
1.465     albertel 11345:     my @domains;
1.838     albertel 11346:     my %hostname = &all_hostnames();
1.465     albertel 11347:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  11348: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 11349: 	if ($hostname eq $name) {
1.844     albertel 11350: 	    push(@domains,&host_domain($id));
1.465     albertel 11351: 	}
                   11352:     }
                   11353:     return @domains;
                   11354: }
                   11355: 
                   11356: sub current_machine_ids {
1.853     albertel 11357:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   11358: }
                   11359: 
                   11360: sub machine_ids {
                   11361:     my ($hostname) = @_;
                   11362:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 11363:     my @ids;
1.888     albertel 11364:     my %name_to_host = &all_names();
1.889     albertel 11365:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   11366: 	return @{ $name_to_host{$hostname} };
                   11367:     }
                   11368:     return;
1.31      www      11369: }
                   11370: 
1.824     raeburn  11371: sub additional_machine_domains {
                   11372:     my @domains;
                   11373:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   11374:     while( my $line = <$fh>) {
                   11375:         $line =~ s/\s//g;
                   11376:         push(@domains,$line);
                   11377:     }
                   11378:     return @domains;
                   11379: }
                   11380: 
                   11381: sub default_login_domain {
                   11382:     my $domain = $perlvar{'lonDefDomain'};
                   11383:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   11384:     foreach my $posdom (&current_machine_domains(),
                   11385:                         &additional_machine_domains()) {
                   11386:         if (lc($posdom) eq lc($testdomain)) {
                   11387:             $domain=$posdom;
                   11388:             last;
                   11389:         }
                   11390:     }
                   11391:     return $domain;
                   11392: }
                   11393: 
1.31      www      11394: # ------------------------------------------------------------- Declutters URLs
                   11395: 
                   11396: sub declutter {
                   11397:     my $thisfn=shift;
1.569     albertel 11398:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 11399:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      11400:     $thisfn=~s/^\///;
1.697     albertel 11401:     $thisfn=~s|^adm/wrapper/||;
                   11402:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      11403:     $thisfn=~s/^res\///;
1.1172    bisitz   11404:     $thisfn=~s/^priv\///;
1.1032    raeburn  11405:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   11406:         $thisfn=~s/\?.+$//;
                   11407:     }
1.268     www      11408:     return $thisfn;
                   11409: }
                   11410: 
                   11411: # ------------------------------------------------------------- Clutter up URLs
                   11412: 
                   11413: sub clutter {
                   11414:     my $thisfn='/'.&declutter(shift);
1.887     albertel 11415:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 11416: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      11417:        $thisfn='/res'.$thisfn; 
                   11418:     }
1.1031    raeburn  11419:     if ($thisfn !~m|^/adm|) {
                   11420: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 11421: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 11422: 	} else {
                   11423: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   11424: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 11425: 	    if ($embstyle eq 'ssi'
                   11426: 		|| ($embstyle eq 'hdn')
                   11427: 		|| ($embstyle eq 'rat')
                   11428: 		|| ($embstyle eq 'prv')
                   11429: 		|| ($embstyle eq 'ign')) {
                   11430: 		#do nothing with these
                   11431: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 11432: 		|| ($embstyle eq 'emb')
                   11433: 		|| ($embstyle eq 'wrp')) {
                   11434: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 11435: 	    } elsif ($embstyle eq 'unk'
                   11436: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 11437: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 11438: 	    } else {
1.718     www      11439: #		&logthis("Got a blank emb style");
1.695     albertel 11440: 	    }
1.694     albertel 11441: 	}
                   11442:     }
1.31      www      11443:     return $thisfn;
1.12      www      11444: }
                   11445: 
1.787     albertel 11446: sub clutter_with_no_wrapper {
                   11447:     my $uri = &clutter(shift);
                   11448:     if ($uri =~ m-^/adm/-) {
                   11449: 	$uri =~ s-^/adm/wrapper/-/-;
                   11450: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   11451:     }
                   11452:     return $uri;
                   11453: }
                   11454: 
1.557     albertel 11455: sub freeze_escape {
                   11456:     my ($value)=@_;
                   11457:     if (ref($value)) {
                   11458: 	$value=&nfreeze($value);
                   11459: 	return '__FROZEN__'.&escape($value);
                   11460:     }
                   11461:     return &escape($value);
                   11462: }
                   11463: 
1.11      www      11464: 
1.557     albertel 11465: sub thaw_unescape {
                   11466:     my ($value)=@_;
                   11467:     if ($value =~ /^__FROZEN__/) {
                   11468: 	substr($value,0,10,undef);
                   11469: 	$value=&unescape($value);
                   11470: 	return &thaw($value);
                   11471:     }
                   11472:     return &unescape($value);
                   11473: }
                   11474: 
1.436     albertel 11475: sub correct_line_ends {
                   11476:     my ($result)=@_;
                   11477:     $$result =~s/\r\n/\n/mg;
                   11478:     $$result =~s/\r/\n/mg;
1.415     albertel 11479: }
1.1       albertel 11480: # ================================================================ Main Program
                   11481: 
1.184     www      11482: sub goodbye {
1.204     albertel 11483:    &logthis("Starting Shut down");
1.443     albertel 11484: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 11485:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 11486: #converted
1.599     albertel 11487: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 11488:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   11489: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   11490: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 11491: #1.1 only
1.870     albertel 11492: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   11493: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   11494: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   11495: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   11496:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 11497:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   11498:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      11499:    &flushcourselogs();
                   11500:    &logthis("Shutting down");
                   11501: }
                   11502: 
1.852     albertel 11503: sub get_dns {
1.869     albertel 11504:     my ($url,$func,$ignore_cache) = @_;
                   11505:     if (!$ignore_cache) {
                   11506: 	my ($content,$cached)=
                   11507: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   11508: 	if ($cached) {
                   11509: 	    &$func($content);
                   11510: 	    return;
                   11511: 	}
                   11512:     }
                   11513: 
                   11514:     my %alldns;
1.852     albertel 11515:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11516:     foreach my $dns (<$config>) {
                   11517: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  11518:         my $line = $1;
                   11519:         my ($host,$protocol) = split(/:/,$line);
                   11520:         if ($protocol ne 'https') {
                   11521:             $protocol = 'http';
                   11522:         }
                   11523: 	$alldns{$host} = $protocol;
1.869     albertel 11524:     }
                   11525:     while (%alldns) {
                   11526: 	my ($dns) = keys(%alldns);
1.852     albertel 11527: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  11528:         $ua->timeout(30);
1.979     raeburn  11529: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 11530: 	my $response=$ua->request($request);
1.979     raeburn  11531:         delete($alldns{$dns});
1.852     albertel 11532: 	next if ($response->is_error());
                   11533: 	my @content = split("\n",$response->content);
1.869     albertel 11534: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 11535: 	&$func(\@content);
1.869     albertel 11536: 	return;
1.852     albertel 11537:     }
                   11538:     close($config);
1.871     albertel 11539:     my $which = (split('/',$url))[3];
                   11540:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   11541:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 11542:     my @content = <$config>;
                   11543:     &$func(\@content);
                   11544:     return;
1.852     albertel 11545: }
1.327     albertel 11546: # ------------------------------------------------------------ Read domain file
                   11547: {
1.852     albertel 11548:     my $loaded;
1.846     albertel 11549:     my %domain;
                   11550: 
1.852     albertel 11551:     sub parse_domain_tab {
                   11552: 	my ($lines) = @_;
                   11553: 	foreach my $line (@$lines) {
                   11554: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      11555: 
1.846     albertel 11556: 	    chomp($line);
1.852     albertel 11557: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 11558: 	    my %this_domain;
                   11559: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   11560: 			       'lang_def', 'city', 'longi', 'lati',
                   11561: 			       'primary') {
                   11562: 		$this_domain{$field} = shift(@elements);
                   11563: 	    }
                   11564: 	    $domain{$name} = \%this_domain;
1.852     albertel 11565: 	}
                   11566:     }
1.864     albertel 11567: 
                   11568:     sub reset_domain_info {
                   11569: 	undef($loaded);
                   11570: 	undef(%domain);
                   11571:     }
                   11572: 
1.852     albertel 11573:     sub load_domain_tab {
1.869     albertel 11574: 	my ($ignore_cache) = @_;
                   11575: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 11576: 	my $fh;
                   11577: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   11578: 	    my @lines = <$fh>;
                   11579: 	    &parse_domain_tab(\@lines);
1.448     albertel 11580: 	}
1.852     albertel 11581: 	close($fh);
                   11582: 	$loaded = 1;
1.327     albertel 11583:     }
1.846     albertel 11584: 
                   11585:     sub domain {
1.852     albertel 11586: 	&load_domain_tab() if (!$loaded);
                   11587: 
1.846     albertel 11588: 	my ($name,$what) = @_;
                   11589: 	return if ( !exists($domain{$name}) );
                   11590: 
                   11591: 	if (!$what) {
                   11592: 	    return $domain{$name}{'description'};
                   11593: 	}
                   11594: 	return $domain{$name}{$what};
                   11595:     }
1.974     raeburn  11596: 
                   11597:     sub domain_info {
                   11598:         &load_domain_tab() if (!$loaded);
                   11599:         return %domain;
                   11600:     }
                   11601: 
1.327     albertel 11602: }
                   11603: 
                   11604: 
1.1       albertel 11605: # ------------------------------------------------------------- Read hosts file
                   11606: {
1.838     albertel 11607:     my %hostname;
1.844     albertel 11608:     my %hostdom;
1.845     albertel 11609:     my %libserv;
1.852     albertel 11610:     my $loaded;
1.888     albertel 11611:     my %name_to_host;
1.1074    raeburn  11612:     my %internetdom;
1.1107    raeburn  11613:     my %LC_dns_serv;
1.852     albertel 11614: 
                   11615:     sub parse_hosts_tab {
                   11616: 	my ($file) = @_;
                   11617: 	foreach my $configline (@$file) {
                   11618: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  11619:             chomp($configline);
                   11620: 	    if ($configline =~ /^\^/) {
                   11621:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   11622:                     $LC_dns_serv{$1} = 1;
                   11623:                 }
                   11624:                 next;
                   11625:             }
1.1074    raeburn  11626: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 11627: 	    $name=~s/\s//g;
                   11628: 	    if ($id && $domain && $role && $name) {
                   11629: 		$hostname{$id}=$name;
1.888     albertel 11630: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 11631: 		$hostdom{$id}=$domain;
                   11632: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  11633:                 if (defined($protocol)) {
                   11634:                     if ($protocol eq 'https') {
                   11635:                         $protocol{$id} = $protocol;
                   11636:                     } else {
                   11637:                         $protocol{$id} = 'http'; 
                   11638:                     }
1.968     raeburn  11639:                 } else {
1.969     raeburn  11640:                     $protocol{$id} = 'http';
1.968     raeburn  11641:                 }
1.1074    raeburn  11642:                 if (defined($intdom)) {
                   11643:                     $internetdom{$id} = $intdom;
                   11644:                 }
1.852     albertel 11645: 	    }
                   11646: 	}
                   11647:     }
1.864     albertel 11648:     
                   11649:     sub reset_hosts_info {
1.897     albertel 11650: 	&purge_remembered();
1.864     albertel 11651: 	&reset_domain_info();
                   11652: 	&reset_hosts_ip_info();
1.892     albertel 11653: 	undef(%name_to_host);
1.864     albertel 11654: 	undef(%hostname);
                   11655: 	undef(%hostdom);
                   11656: 	undef(%libserv);
                   11657: 	undef($loaded);
                   11658:     }
1.1       albertel 11659: 
1.852     albertel 11660:     sub load_hosts_tab {
1.869     albertel 11661: 	my ($ignore_cache) = @_;
                   11662: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 11663: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11664: 	my @config = <$config>;
                   11665: 	&parse_hosts_tab(\@config);
                   11666: 	close($config);
                   11667: 	$loaded=1;
1.1       albertel 11668:     }
1.852     albertel 11669: 
1.838     albertel 11670:     sub hostname {
1.852     albertel 11671: 	&load_hosts_tab() if (!$loaded);
                   11672: 
1.838     albertel 11673: 	my ($lonid) = @_;
                   11674: 	return $hostname{$lonid};
                   11675:     }
1.845     albertel 11676: 
1.838     albertel 11677:     sub all_hostnames {
1.852     albertel 11678: 	&load_hosts_tab() if (!$loaded);
                   11679: 
1.838     albertel 11680: 	return %hostname;
                   11681:     }
1.845     albertel 11682: 
1.888     albertel 11683:     sub all_names {
                   11684: 	&load_hosts_tab() if (!$loaded);
                   11685: 
                   11686: 	return %name_to_host;
                   11687:     }
                   11688: 
1.974     raeburn  11689:     sub all_host_domain {
                   11690:         &load_hosts_tab() if (!$loaded);
                   11691:         return %hostdom;
                   11692:     }
                   11693: 
1.845     albertel 11694:     sub is_library {
1.852     albertel 11695: 	&load_hosts_tab() if (!$loaded);
                   11696: 
1.845     albertel 11697: 	return exists($libserv{$_[0]});
                   11698:     }
                   11699: 
                   11700:     sub all_library {
1.852     albertel 11701: 	&load_hosts_tab() if (!$loaded);
                   11702: 
1.845     albertel 11703: 	return %libserv;
                   11704:     }
                   11705: 
1.1062    droeschl 11706:     sub unique_library {
                   11707: 	#2x reverse removes all hostnames that appear more than once
                   11708:         my %unique = reverse &all_library();
                   11709:         return reverse %unique;
                   11710:     }
                   11711: 
1.841     albertel 11712:     sub get_servers {
1.852     albertel 11713: 	&load_hosts_tab() if (!$loaded);
                   11714: 
1.841     albertel 11715: 	my ($domain,$type) = @_;
                   11716: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   11717: 	                                          : %hostname;
                   11718: 	my %result;
1.842     albertel 11719: 	if (ref($domain) eq 'ARRAY') {
                   11720: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 11721: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 11722: 		    $result{$host} = $hostname;
                   11723: 		}
                   11724: 	    }
                   11725: 	} else {
                   11726: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   11727: 		if ($hostdom{$host} eq $domain) {
                   11728: 		    $result{$host} = $hostname;
                   11729: 		}
1.841     albertel 11730: 	    }
                   11731: 	}
                   11732: 	return %result;
                   11733:     }
1.845     albertel 11734: 
1.1062    droeschl 11735:     sub get_unique_servers {
                   11736:         my %unique = reverse &get_servers(@_);
                   11737: 	return reverse %unique;
                   11738:     }
                   11739: 
1.844     albertel 11740:     sub host_domain {
1.852     albertel 11741: 	&load_hosts_tab() if (!$loaded);
                   11742: 
1.844     albertel 11743: 	my ($lonid) = @_;
                   11744: 	return $hostdom{$lonid};
                   11745:     }
                   11746: 
1.841     albertel 11747:     sub all_domains {
1.852     albertel 11748: 	&load_hosts_tab() if (!$loaded);
                   11749: 
1.841     albertel 11750: 	my %seen;
                   11751: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   11752: 	return @uniq;
                   11753:     }
1.1074    raeburn  11754: 
                   11755:     sub internet_dom {
                   11756:         &load_hosts_tab() if (!$loaded);
                   11757: 
                   11758:         my ($lonid) = @_;
                   11759:         return $internetdom{$lonid};
                   11760:     }
1.1107    raeburn  11761: 
                   11762:     sub is_LC_dns {
                   11763:         &load_hosts_tab() if (!$loaded);
                   11764: 
                   11765:         my ($hostname) = @_;
                   11766:         return exists($LC_dns_serv{$hostname});
                   11767:     }
                   11768: 
1.1       albertel 11769: }
                   11770: 
1.847     albertel 11771: { 
                   11772:     my %iphost;
1.856     albertel 11773:     my %name_to_ip;
                   11774:     my %lonid_to_ip;
1.869     albertel 11775: 
1.847     albertel 11776:     sub get_hosts_from_ip {
                   11777: 	my ($ip) = @_;
                   11778: 	my %iphosts = &get_iphost();
                   11779: 	if (ref($iphosts{$ip})) {
                   11780: 	    return @{$iphosts{$ip}};
                   11781: 	}
                   11782: 	return;
1.839     albertel 11783:     }
1.864     albertel 11784:     
                   11785:     sub reset_hosts_ip_info {
                   11786: 	undef(%iphost);
                   11787: 	undef(%name_to_ip);
                   11788: 	undef(%lonid_to_ip);
                   11789:     }
1.856     albertel 11790: 
                   11791:     sub get_host_ip {
                   11792: 	my ($lonid) = @_;
                   11793: 	if (exists($lonid_to_ip{$lonid})) {
                   11794: 	    return $lonid_to_ip{$lonid};
                   11795: 	}
                   11796: 	my $name=&hostname($lonid);
                   11797:    	my $ip = gethostbyname($name);
                   11798: 	return if (!$ip || length($ip) ne 4);
                   11799: 	$ip=inet_ntoa($ip);
                   11800: 	$name_to_ip{$name}   = $ip;
                   11801: 	$lonid_to_ip{$lonid} = $ip;
                   11802: 	return $ip;
                   11803:     }
1.847     albertel 11804:     
                   11805:     sub get_iphost {
1.869     albertel 11806: 	my ($ignore_cache) = @_;
1.894     albertel 11807: 
1.869     albertel 11808: 	if (!$ignore_cache) {
                   11809: 	    if (%iphost) {
                   11810: 		return %iphost;
                   11811: 	    }
                   11812: 	    my ($ip_info,$cached)=
                   11813: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   11814: 	    if ($cached) {
                   11815: 		%iphost      = %{$ip_info->[0]};
                   11816: 		%name_to_ip  = %{$ip_info->[1]};
                   11817: 		%lonid_to_ip = %{$ip_info->[2]};
                   11818: 		return %iphost;
                   11819: 	    }
                   11820: 	}
1.894     albertel 11821: 
                   11822: 	# get yesterday's info for fallback
                   11823: 	my %old_name_to_ip;
                   11824: 	my ($ip_info,$cached)=
                   11825: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   11826: 	if ($cached) {
                   11827: 	    %old_name_to_ip = %{$ip_info->[1]};
                   11828: 	}
                   11829: 
1.888     albertel 11830: 	my %name_to_host = &all_names();
                   11831: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 11832: 	    my $ip;
                   11833: 	    if (!exists($name_to_ip{$name})) {
                   11834: 		$ip = gethostbyname($name);
                   11835: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 11836: 		    if (defined($old_name_to_ip{$name})) {
                   11837: 			$ip = $old_name_to_ip{$name};
                   11838: 			&logthis("Can't find $name defaulting to old $ip");
                   11839: 		    } else {
                   11840: 			&logthis("Name $name no IP found");
                   11841: 			next;
                   11842: 		    }
                   11843: 		} else {
                   11844: 		    $ip=inet_ntoa($ip);
1.847     albertel 11845: 		}
                   11846: 		$name_to_ip{$name} = $ip;
                   11847: 	    } else {
                   11848: 		$ip = $name_to_ip{$name};
1.653     albertel 11849: 	    }
1.888     albertel 11850: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   11851: 		$lonid_to_ip{$id} = $ip;
                   11852: 	    }
                   11853: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 11854: 	}
1.869     albertel 11855: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   11856: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 11857: 				      48*60*60);
1.869     albertel 11858: 
1.847     albertel 11859: 	return %iphost;
1.598     albertel 11860:     }
                   11861: 
1.992     raeburn  11862:     #
                   11863:     #  Given a DNS returns the loncapa host name for that DNS 
                   11864:     # 
                   11865:     sub host_from_dns {
                   11866:         my ($dns) = @_;
                   11867:         my @hosts;
                   11868:         my $ip;
                   11869: 
1.993     raeburn  11870:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  11871:             $ip = $name_to_ip{$dns};
                   11872:         }
                   11873:         if (!$ip) {
                   11874:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   11875:             if (length($ip) == 4) { 
                   11876: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   11877:             }
                   11878:         }
                   11879:         if ($ip) {
                   11880: 	    @hosts = get_hosts_from_ip($ip);
                   11881: 	    return $hosts[0];
                   11882:         }
                   11883:         return undef;
1.986     foxr     11884:     }
1.992     raeburn  11885: 
1.1074    raeburn  11886:     sub get_internet_names {
                   11887:         my ($lonid) = @_;
                   11888:         return if ($lonid eq '');
                   11889:         my ($idnref,$cached)=
                   11890:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   11891:         if ($cached) {
                   11892:             return $idnref;
                   11893:         }
                   11894:         my $ip = &get_host_ip($lonid);
                   11895:         my @hosts = &get_hosts_from_ip($ip);
                   11896:         my %iphost = &get_iphost();
                   11897:         my (@idns,%seen);
                   11898:         foreach my $id (@hosts) {
                   11899:             my $dom = &host_domain($id);
                   11900:             my $prim_id = &domain($dom,'primary');
                   11901:             my $prim_ip = &get_host_ip($prim_id);
                   11902:             next if ($seen{$prim_ip});
                   11903:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   11904:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   11905:                     my $intdom = &internet_dom($id);
                   11906:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   11907:                         push(@idns,$intdom);
                   11908:                     }
                   11909:                 }
                   11910:             }
                   11911:             $seen{$prim_ip} = 1;
                   11912:         }
                   11913:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
                   11914:     }
                   11915: 
1.986     foxr     11916: }
                   11917: 
1.1079    raeburn  11918: sub all_loncaparevs {
                   11919:     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);
                   11920: }
                   11921: 
1.862     albertel 11922: BEGIN {
                   11923: 
                   11924: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   11925:     unless ($readit) {
                   11926: {
                   11927:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   11928:     %perlvar = (%perlvar,%{$configvars});
                   11929: }
                   11930: 
                   11931: 
1.1       albertel 11932: # ------------------------------------------------------ Read spare server file
                   11933: {
1.448     albertel 11934:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 11935: 
                   11936:     while (my $configline=<$config>) {
                   11937:        chomp($configline);
1.284     matthew  11938:        if ($configline) {
1.784     albertel 11939: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 11940: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 11941: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 11942:        }
                   11943:     }
1.448     albertel 11944:     close($config);
1.1       albertel 11945: }
1.11      www      11946: # ------------------------------------------------------------ Read permissions
                   11947: {
1.448     albertel 11948:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      11949: 
                   11950:     while (my $configline=<$config>) {
1.448     albertel 11951: 	chomp($configline);
                   11952: 	if ($configline) {
                   11953: 	    my ($role,$perm)=split(/ /,$configline);
                   11954: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   11955: 	}
1.11      www      11956:     }
1.448     albertel 11957:     close($config);
1.11      www      11958: }
                   11959: 
                   11960: # -------------------------------------------- Read plain texts for permissions
                   11961: {
1.448     albertel 11962:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      11963: 
                   11964:     while (my $configline=<$config>) {
1.448     albertel 11965: 	chomp($configline);
                   11966: 	if ($configline) {
1.742     raeburn  11967: 	    my ($short,@plain)=split(/:/,$configline);
                   11968:             %{$prp{$short}} = ();
                   11969: 	    if (@plain > 0) {
                   11970:                 $prp{$short}{'std'} = $plain[0];
                   11971:                 for (my $i=1; $i<@plain; $i++) {
                   11972:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   11973:                 }
                   11974:             }
1.448     albertel 11975: 	}
1.135     www      11976:     }
1.448     albertel 11977:     close($config);
1.135     www      11978: }
                   11979: 
                   11980: # ---------------------------------------------------------- Read package table
                   11981: {
1.448     albertel 11982:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      11983: 
                   11984:     while (my $configline=<$config>) {
1.483     albertel 11985: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 11986: 	chomp($configline);
                   11987: 	my ($short,$plain)=split(/:/,$configline);
                   11988: 	my ($pack,$name)=split(/\&/,$short);
                   11989: 	if ($plain ne '') {
                   11990: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   11991: 	    $packagetab{$short}=$plain; 
                   11992: 	}
1.11      www      11993:     }
1.448     albertel 11994:     close($config);
1.329     matthew  11995: }
                   11996: 
1.1073    raeburn  11997: # ---------------------------------------------------------- Read loncaparev table
                   11998: {
                   11999:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   12000:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   12001:             while (my $configline=<$config>) {
                   12002:                 chomp($configline);
                   12003:                 my ($hostid,$loncaparev)=split(/:/,$configline);
                   12004:                 $loncaparevs{$hostid}=$loncaparev;
                   12005:             }
                   12006:             close($config);
                   12007:         }
                   12008:     }
                   12009: }
                   12010: 
1.1074    raeburn  12011: # ---------------------------------------------------------- Read serverhostID table
                   12012: {
                   12013:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   12014:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   12015:             while (my $configline=<$config>) {
                   12016:                 chomp($configline);
                   12017:                 my ($name,$id)=split(/:/,$configline);
                   12018:                 $serverhomeIDs{$name}=$id;
                   12019:             }
                   12020:             close($config);
                   12021:         }
                   12022:     }
                   12023: }
                   12024: 
1.1079    raeburn  12025: {
                   12026:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   12027:     if (-e $file) {
                   12028:         my $parser = HTML::LCParser->new($file);
                   12029:         while (my $token = $parser->get_token()) {
                   12030:             if ($token->[0] eq 'S') {
                   12031:                 my $item = $token->[1];
                   12032:                 my $name = $token->[2]{'name'};
                   12033:                 my $value = $token->[2]{'value'};
                   12034:                 if ($item ne '' && $name ne '' && $value ne '') {
                   12035:                     my $release = $parser->get_text();
                   12036:                     $release =~ s/(^\s*|\s*$ )//gx;
                   12037:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   12038:                 }
                   12039:             }
                   12040:         }
                   12041:     }
1.1073    raeburn  12042: }
                   12043: 
1.1138    raeburn  12044: # ---------------------------------------------------------- Read managers table
                   12045: {
                   12046:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   12047:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   12048:             while (my $configline=<$config>) {
                   12049:                 chomp($configline);
                   12050:                 next if ($configline =~ /^\#/);
                   12051:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   12052:                     $managerstab{$configline} = 1;
                   12053:                 }
                   12054:             }
                   12055:             close($config);
                   12056:         }
                   12057:     }
                   12058: }
                   12059: 
1.329     matthew  12060: # ------------- set up temporary directory
                   12061: {
1.1117    foxr     12062:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  12063: 
1.11      www      12064: }
                   12065: 
1.794     albertel 12066: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   12067: 				'compress_threshold'=> 20_000,
                   12068:  			        });
1.185     www      12069: 
1.281     www      12070: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      12071: $dumpcount=0;
1.958     www      12072: $locknum=0;
1.22      www      12073: 
1.163     harris41 12074: &logtouch();
1.672     albertel 12075: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      12076: $readit=1;
1.564     albertel 12077:     {
                   12078: 	use integer;
                   12079: 	my $test=(2**32)+1;
1.568     albertel 12080: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 12081: 	&logthis(" Detected 64bit platform ($_64bit)");
                   12082:     }
1.195     www      12083: }
1.1       albertel 12084: }
1.179     www      12085: 
1.1       albertel 12086: 1;
1.191     harris41 12087: __END__
                   12088: 
1.243     albertel 12089: =pod
                   12090: 
1.191     harris41 12091: =head1 NAME
                   12092: 
1.243     albertel 12093: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 12094: 
                   12095: =head1 SYNOPSIS
                   12096: 
1.243     albertel 12097: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 12098: 
                   12099:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   12100: 
1.243     albertel 12101: Common parameters:
                   12102: 
                   12103: =over 4
                   12104: 
                   12105: =item *
                   12106: 
                   12107: $uname : an internal username (if $cname expecting a course Id specifically)
                   12108: 
                   12109: =item *
                   12110: 
                   12111: $udom : a domain (if $cdom expecting a course's domain specifically)
                   12112: 
                   12113: =item *
                   12114: 
                   12115: $symb : a resource instance identifier
                   12116: 
                   12117: =item *
                   12118: 
                   12119: $namespace : the name of a .db file that contains the data needed or
                   12120: being set.
                   12121: 
                   12122: =back
                   12123: 
1.394     bowersj2 12124: =head1 OVERVIEW
1.191     harris41 12125: 
1.394     bowersj2 12126: lonnet provides subroutines which interact with the
                   12127: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   12128: about classes, users, and resources.
1.243     albertel 12129: 
                   12130: For many of these objects you can also use this to store data about
                   12131: them or modify them in various ways.
1.191     harris41 12132: 
1.394     bowersj2 12133: =head2 Symbs
1.191     harris41 12134: 
1.394     bowersj2 12135: To identify a specific instance of a resource, LON-CAPA uses symbols
                   12136: or "symbs"X<symb>. These identifiers are built from the URL of the
                   12137: map, the resource number of the resource in the map, and the URL of
                   12138: the resource itself. The latter is somewhat redundant, but might help
                   12139: if maps change.
                   12140: 
                   12141: An example is
                   12142: 
                   12143:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   12144: 
                   12145: The respective map entry is
                   12146: 
                   12147:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   12148:   title="Problem 2">
                   12149:  </resource>
                   12150: 
                   12151: Symbs are used by the random number generator, as well as to store and
                   12152: restore data specific to a certain instance of for example a problem.
                   12153: 
                   12154: =head2 Storing And Retrieving Data
                   12155: 
                   12156: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   12157: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   12158: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   12159: is is the non-critical message twin of cstore. These functions are for
                   12160: handlers to store a perl hash to a user's permanent data space in an
                   12161: easy manner, and to retrieve it again on another call. It is expected
                   12162: that a handler would use this once at the beginning to retrieve data,
                   12163: and then again once at the end to send only the new data back.
                   12164: 
                   12165: The data is stored in the user's data directory on the user's
                   12166: homeserver under the ID of the course.
                   12167: 
                   12168: The hash that is returned by restore will have all of the previous
                   12169: value for all of the elements of the hash.
                   12170: 
                   12171: Example:
                   12172: 
                   12173:  #creating a hash
                   12174:  my %hash;
                   12175:  $hash{'foo'}='bar';
                   12176: 
                   12177:  #storing it
                   12178:  &Apache::lonnet::cstore(\%hash);
                   12179: 
                   12180:  #changing a value
                   12181:  $hash{'foo'}='notbar';
                   12182: 
                   12183:  #adding a new value
                   12184:  $hash{'bar'}='foo';
                   12185:  &Apache::lonnet::cstore(\%hash);
                   12186: 
                   12187:  #retrieving the hash
                   12188:  my %history=&Apache::lonnet::restore();
                   12189: 
                   12190:  #print the hash
                   12191:  foreach my $key (sort(keys(%history))) {
                   12192:    print("\%history{$key} = $history{$key}");
                   12193:  }
                   12194: 
                   12195: Will print out:
1.191     harris41 12196: 
1.394     bowersj2 12197:  %history{1:foo} = bar
                   12198:  %history{1:keys} = foo:timestamp
                   12199:  %history{1:timestamp} = 990455579
                   12200:  %history{2:bar} = foo
                   12201:  %history{2:foo} = notbar
                   12202:  %history{2:keys} = foo:bar:timestamp
                   12203:  %history{2:timestamp} = 990455580
                   12204:  %history{bar} = foo
                   12205:  %history{foo} = notbar
                   12206:  %history{timestamp} = 990455580
                   12207:  %history{version} = 2
                   12208: 
                   12209: Note that the special hash entries C<keys>, C<version> and
                   12210: C<timestamp> were added to the hash. C<version> will be equal to the
                   12211: total number of versions of the data that have been stored. The
                   12212: C<timestamp> attribute will be the UNIX time the hash was
                   12213: stored. C<keys> is available in every historical section to list which
                   12214: keys were added or changed at a specific historical revision of a
                   12215: hash.
                   12216: 
                   12217: B<Warning>: do not store the hash that restore returns directly. This
                   12218: will cause a mess since it will restore the historical keys as if the
                   12219: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 12220: 
1.394     bowersj2 12221: Calling convention:
1.191     harris41 12222: 
1.394     bowersj2 12223:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   12224:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 12225: 
1.394     bowersj2 12226: For more detailed information, see lonnet specific documentation.
1.191     harris41 12227: 
1.394     bowersj2 12228: =head1 RETURN MESSAGES
1.191     harris41 12229: 
1.394     bowersj2 12230: =over 4
1.191     harris41 12231: 
1.394     bowersj2 12232: =item * B<con_lost>: unable to contact remote host
1.191     harris41 12233: 
1.394     bowersj2 12234: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   12235: when the connection is brought back up
1.191     harris41 12236: 
1.394     bowersj2 12237: =item * B<con_failed>: unable to contact remote host and unable to save message
                   12238: for later delivery
1.191     harris41 12239: 
1.967     bisitz   12240: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 12241: 
1.394     bowersj2 12242: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 12243: that was requested
1.191     harris41 12244: 
1.243     albertel 12245: =back
1.191     harris41 12246: 
1.243     albertel 12247: =head1 PUBLIC SUBROUTINES
1.191     harris41 12248: 
1.243     albertel 12249: =head2 Session Environment Functions
1.191     harris41 12250: 
1.243     albertel 12251: =over 4
1.191     harris41 12252: 
1.394     bowersj2 12253: =item * 
                   12254: X<appenv()>
1.949     raeburn  12255: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 12256: the user envirnoment file, and will be restored for each access this
1.620     albertel 12257: user makes during this session, also modifies the %env for the current
1.949     raeburn  12258: process. Optional rolesarrayref - if defined contains a reference to an array
                   12259: of roles which are exempt from the restriction on modifying user.role entries 
                   12260: in the user's environment.db and in %env.    
1.191     harris41 12261: 
                   12262: =item *
1.394     bowersj2 12263: X<delenv()>
1.987     raeburn  12264: B<delenv($delthis,$regexp)>: removes all items from the session
                   12265: environment file that begin with $delthis. If the 
                   12266: optional second arg - $regexp - is true, $delthis is treated as a 
                   12267: regular expression, otherwise \Q$delthis\E is used. 
                   12268: The values are also deleted from the current processes %env.
1.191     harris41 12269: 
1.795     albertel 12270: =item * get_env_multiple($name) 
                   12271: 
                   12272: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   12273: values may be defined and end up as an array ref.
                   12274: 
                   12275: returns an array of values
                   12276: 
1.243     albertel 12277: =back
                   12278: 
                   12279: =head2 User Information
1.191     harris41 12280: 
1.243     albertel 12281: =over 4
1.191     harris41 12282: 
                   12283: =item *
1.394     bowersj2 12284: X<queryauthenticate()>
                   12285: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 12286: authentication scheme
                   12287: 
                   12288: =item *
1.394     bowersj2 12289: X<authenticate()>
1.1073    raeburn  12290: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 12291: authenticate user from domain's lib servers (first use the current
                   12292: one). C<$upass> should be the users password.
1.1073    raeburn  12293: $checkdefauth is optional (value is 1 if a check should be made to
                   12294:    authenticate user using default authentication method, and allow
                   12295:    account creation if username does not have account in the domain).
                   12296: $clientcancheckhost is optional (value is 1 if checking whether the
                   12297:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 12298: 
                   12299: =item *
1.394     bowersj2 12300: X<homeserver()>
                   12301: B<homeserver($uname,$udom)>: find the server which has
                   12302: the user's directory and files (there must be only one), this caches
                   12303: the answer, and also caches if there is a borken connection.
1.191     harris41 12304: 
                   12305: =item *
1.394     bowersj2 12306: X<idget()>
                   12307: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   12308: (IDs are a unique resource in a domain, there must be only 1 ID per
                   12309: username, and only 1 username per ID in a specific domain) (returns
                   12310: hash: id=>name,id=>name)
1.191     harris41 12311: 
                   12312: =item *
1.394     bowersj2 12313: X<idrget()>
                   12314: B<idrget($udom,@unames)>: find the IDs behind a list of
                   12315: usernames (returns hash: name=>id,name=>id)
1.191     harris41 12316: 
                   12317: =item *
1.394     bowersj2 12318: X<idput()>
                   12319: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 12320: 
                   12321: =item *
1.394     bowersj2 12322: X<rolesinit()>
1.1169    droeschl 12323: B<rolesinit($udom,$username)>: get user privileges.
                   12324: returns user role, first access and timer interval hashes
1.243     albertel 12325: 
                   12326: =item *
1.1171    droeschl 12327: X<privileged()>
                   12328: B<privileged($username,$domain)>: returns a true if user has a
                   12329: privileged and active role (i.e. su or dc), false otherwise.
                   12330: 
                   12331: =item *
1.551     albertel 12332: X<getsection()>
                   12333: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 12334: course $cname, return section name/number or '' for "not in course"
                   12335: and '-1' for "no section"
                   12336: 
                   12337: =item *
1.394     bowersj2 12338: X<userenvironment()>
                   12339: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 12340: passed in @what from the requested user's environment, returns a hash
                   12341: 
1.858     raeburn  12342: =item * 
                   12343: X<userlog_query()>
1.859     albertel 12344: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   12345: activity.log file. %filters defines filters applied when parsing the
                   12346: log file. These can be start or end timestamps, or the type of action
                   12347: - log to look for Login or Logout events, check for Checkin or
                   12348: Checkout, role for role selection. The response is in the form
                   12349: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   12350: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  12351: 
1.243     albertel 12352: =back
                   12353: 
                   12354: =head2 User Roles
                   12355: 
                   12356: =over 4
                   12357: 
                   12358: =item *
                   12359: 
1.810     raeburn  12360: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 12361:  F: full access
                   12362:  U,I,K: authentication modes (cxx only)
                   12363:  '': forbidden
                   12364:  1: user needs to choose course
                   12365:  2: browse allowed
1.766     albertel 12366:  A: passphrase authentication needed
1.243     albertel 12367: 
                   12368: =item *
                   12369: 
1.1172.2.13! raeburn  12370: constructaccess($url,$setpriv) : check for access to construction space URL
        !          12371: 
        !          12372: See if the owner domain and name in the URL match those in the
        !          12373: expected environment.  If so, return three element list
        !          12374: ($ownername,$ownerdomain,$ownerhome).
        !          12375: 
        !          12376: Otherwise return the null string.
        !          12377: 
        !          12378: If second argument 'setpriv' is true, it assigns the privileges,
        !          12379: and returns the same three element list, unless the owner has
        !          12380: blocked "ad hoc" Domain Coordinator access to the Author Space,
        !          12381: in which case the null string is returned.
        !          12382: 
        !          12383: =item *
        !          12384: 
1.243     albertel 12385: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   12386: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   12387: and course level
                   12388: 
                   12389: =item *
                   12390: 
1.988     raeburn  12391: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   12392: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  12393: $type is Course (default) or Community.
1.988     raeburn  12394: If $forcedefault evaluates to true, text returned will be default 
                   12395: text for $type. Otherwise, if this is a course, the text returned 
                   12396: will be a custom name for the role (if defined in the course's 
                   12397: environment).  If no custom name is defined the default is returned.
                   12398:    
1.832     raeburn  12399: =item *
                   12400: 
1.935     raeburn  12401: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  12402: All arguments are optional. Returns a hash of a roles, either for
                   12403: co-author/assistant author roles for a user's Construction Space
1.906     albertel 12404: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  12405: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   12406: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   12407: For each key, value is set to colon-separated start and end times for
                   12408: the role.  If no username and domain are specified, will default to
1.934     raeburn  12409: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  12410: of role statuses (active, future or previous), roles 
                   12411: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   12412: to restrict the list of roles reported. If no array ref is 
                   12413: provided for types, will default to return only active roles.
1.834     albertel 12414: 
1.1172.2.13! raeburn  12415: =item *
        !          12416: 
        !          12417: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
        !          12418: user: $uname:$udom has a role in the course: $cdom_$cnum.
        !          12419: 
        !          12420: Additional optional arguments are: $type (if role checking is to be restricted
        !          12421: to certain user status types -- previous (expired roles), active (currently
        !          12422: available roles) or future (roles available in the future), and
        !          12423: $hideprivileged -- if true will not report course roles for users who
        !          12424: have active Domain Coordinator or Super User roles.
        !          12425: 
1.243     albertel 12426: =back
                   12427: 
                   12428: =head2 User Modification
                   12429: 
                   12430: =over 4
                   12431: 
                   12432: =item *
                   12433: 
1.957     raeburn  12434: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 12435: user for the level given by URL.  Optional start and end dates (leave empty
                   12436: string or zero for "no date")
1.191     harris41 12437: 
                   12438: =item *
                   12439: 
1.243     albertel 12440: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   12441: change a users, password, possible return values are: ok,
                   12442: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   12443: refused
1.191     harris41 12444: 
                   12445: =item *
                   12446: 
1.243     albertel 12447: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 12448: 
                   12449: =item *
                   12450: 
1.1058    raeburn  12451: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   12452:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   12453: 
                   12454: will update user information (firstname,middlename,lastname,generation,
                   12455: permanentemail), and if forceid is true, student/employee ID also.
                   12456: A user's institutional affiliation(s) can also be updated.
                   12457: User information fields will not be overwritten with empty entries 
                   12458: unless the field is included in the $candelete array reference.
                   12459: This array is included when a single user is modified via "Manage Users",
                   12460: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 12461: 
                   12462: =item *
                   12463: 
1.286     matthew  12464: modifystudent
                   12465: 
1.957     raeburn  12466: modify a student's enrollment and identification information.
1.286     matthew  12467: The course id is resolved based on the current users environment.  
                   12468: This means the envoking user must be a course coordinator or otherwise
                   12469: associated with a course.
                   12470: 
1.297     matthew  12471: This call is essentially a wrapper for lonnet::modifyuser and
                   12472: lonnet::modify_student_enrollment
1.286     matthew  12473: 
                   12474: Inputs: 
                   12475: 
                   12476: =over 4
                   12477: 
1.957     raeburn  12478: =item B<$udom> Student's loncapa domain
1.286     matthew  12479: 
1.957     raeburn  12480: =item B<$uname> Student's loncapa login name
1.286     matthew  12481: 
1.964     bisitz   12482: =item B<$uid> Student/Employee ID
1.286     matthew  12483: 
1.957     raeburn  12484: =item B<$umode> Student's authentication mode
1.286     matthew  12485: 
1.957     raeburn  12486: =item B<$upass> Student's password
1.286     matthew  12487: 
1.957     raeburn  12488: =item B<$first> Student's first name
1.286     matthew  12489: 
1.957     raeburn  12490: =item B<$middle> Student's middle name
1.286     matthew  12491: 
1.957     raeburn  12492: =item B<$last> Student's last name
1.286     matthew  12493: 
1.957     raeburn  12494: =item B<$gene> Student's generation
1.286     matthew  12495: 
1.957     raeburn  12496: =item B<$usec> Student's section in course
1.286     matthew  12497: 
                   12498: =item B<$end> Unix time of the roles expiration
                   12499: 
                   12500: =item B<$start> Unix time of the roles start date
                   12501: 
                   12502: =item B<$forceid> If defined, allow $uid to be changed
                   12503: 
                   12504: =item B<$desiredhome> server to use as home server for student
                   12505: 
1.957     raeburn  12506: =item B<$email> Student's permanent e-mail address
                   12507: 
                   12508: =item B<$type> Type of enrollment (auto or manual)
                   12509: 
1.963     raeburn  12510: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   12511: 
                   12512: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  12513: 
1.963     raeburn  12514: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  12515: 
1.963     raeburn  12516: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  12517: 
1.963     raeburn  12518: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  12519: 
1.286     matthew  12520: =back
1.297     matthew  12521: 
                   12522: =item *
                   12523: 
                   12524: modify_student_enrollment
                   12525: 
                   12526: Change a students enrollment status in a class.  The environment variable
                   12527: 'role.request.course' must be defined for this function to proceed.
                   12528: 
                   12529: Inputs:
                   12530: 
                   12531: =over 4
                   12532: 
                   12533: =item $udom, students domain
                   12534: 
                   12535: =item $uname, students name
                   12536: 
                   12537: =item $uid, students user id
                   12538: 
                   12539: =item $first, students first name
                   12540: 
                   12541: =item $middle
                   12542: 
                   12543: =item $last
                   12544: 
                   12545: =item $gene
                   12546: 
                   12547: =item $usec
                   12548: 
                   12549: =item $end
                   12550: 
                   12551: =item $start
                   12552: 
1.957     raeburn  12553: =item $type
                   12554: 
                   12555: =item $locktype
                   12556: 
                   12557: =item $cid
                   12558: 
                   12559: =item $selfenroll
                   12560: 
                   12561: =item $context
                   12562: 
1.297     matthew  12563: =back
                   12564: 
1.191     harris41 12565: 
                   12566: =item *
                   12567: 
1.243     albertel 12568: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   12569: custom role; give a custom role to a user for the level given by URL.  Specify
                   12570: name and domain of role author, and role name
1.191     harris41 12571: 
                   12572: =item *
                   12573: 
1.243     albertel 12574: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 12575: 
                   12576: =item *
                   12577: 
1.243     albertel 12578: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   12579: 
                   12580: =back
                   12581: 
                   12582: =head2 Course Infomation
                   12583: 
                   12584: =over 4
1.191     harris41 12585: 
                   12586: =item *
                   12587: 
1.1118    foxr     12588: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 12589: specified course id, including all environment settings for the
                   12590: course, the description of the course will be in the hash under the
                   12591: key 'description'
1.191     harris41 12592: 
1.1118    foxr     12593: $options is an optional parameter that if supplied is a hash reference that controls
                   12594: what how this function works.  It has the following key/values:
                   12595: 
                   12596: =over 4
                   12597: 
                   12598: =item freshen_cache
                   12599: 
                   12600: If defined, and the environment cache for the course is valid, it is 
                   12601: returned in the returned hash.
                   12602: 
                   12603: =item one_time
                   12604: 
                   12605: If defined, the last cache time is set to _now_
                   12606: 
                   12607: =item user
                   12608: 
                   12609: If defined, the supplied username is used instead of the current user.
                   12610: 
                   12611: 
                   12612: =back
                   12613: 
1.191     harris41 12614: =item *
                   12615: 
1.624     albertel 12616: resdata($name,$domain,$type,@which) : request for current parameter
                   12617: setting for a specific $type, where $type is either 'course' or 'user',
                   12618: @what should be a list of parameters to ask about. This routine caches
                   12619: answers for 5 minutes.
1.243     albertel 12620: 
1.877     foxr     12621: =item *
                   12622: 
                   12623: get_courseresdata($courseid, $domain) : dump the entire course resource
                   12624: data base, returning a hash that is keyed by the resource name and has
                   12625: values that are the resource value.  I believe that the timestamps and
                   12626: versions are also returned.
                   12627: 
1.243     albertel 12628: =back
                   12629: 
                   12630: =head2 Course Modification
                   12631: 
                   12632: =over 4
1.191     harris41 12633: 
                   12634: =item *
                   12635: 
1.243     albertel 12636: writecoursepref($courseid,%prefs) : write preferences (environment
                   12637: database) for a course
1.191     harris41 12638: 
                   12639: =item *
                   12640: 
1.1011    raeburn  12641: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   12642: 
                   12643: =item *
                   12644: 
1.1038    raeburn  12645: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 12646: 
1.1167    droeschl 12647: =item *
                   12648: 
                   12649: is_course($courseid), is_course($cdom, $cnum)
                   12650: 
                   12651: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   12652: two component version $cdom, $cnum. It checks if the specified course exists.
                   12653: 
                   12654: Returns:
                   12655:     undef if the course doesn't exist, otherwise
                   12656:     in scalar context the combined courseid.
                   12657:     in list context the two components of the course identifier, domain and 
                   12658:     courseid.    
                   12659: 
1.243     albertel 12660: =back
                   12661: 
                   12662: =head2 Resource Subroutines
                   12663: 
                   12664: =over 4
1.191     harris41 12665: 
                   12666: =item *
                   12667: 
1.243     albertel 12668: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 12669: 
                   12670: =item *
                   12671: 
1.243     albertel 12672: repcopy($filename) : subscribes to the requested file, and attempts to
                   12673: replicate from the owning library server, Might return
1.607     raeburn  12674: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   12675: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 12676: resource. Expects the local filesystem pathname
                   12677: (/home/httpd/html/res/....)
                   12678: 
                   12679: =back
                   12680: 
                   12681: =head2 Resource Information
                   12682: 
                   12683: =over 4
1.191     harris41 12684: 
                   12685: =item *
                   12686: 
1.243     albertel 12687: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   12688: a vairety of different possible values, $varname should be a request
                   12689: string, and the other parameters can be used to specify who and what
                   12690: one is asking about.
                   12691: 
                   12692: Possible values for $varname are environment.lastname (or other item
                   12693: from the envirnment hash), user.name (or someother aspect about the
                   12694: user), resource.0.maxtries (or some other part and parameter of a
                   12695: resource)
1.204     albertel 12696: 
                   12697: =item *
                   12698: 
1.243     albertel 12699: directcondval($number) : get current value of a condition; reads from a state
                   12700: string
1.204     albertel 12701: 
                   12702: =item *
                   12703: 
1.243     albertel 12704: condval($condidx) : value of condition index based on state
1.204     albertel 12705: 
                   12706: =item *
                   12707: 
1.243     albertel 12708: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   12709: resource's metadata, $what should be either a specific key, or either
                   12710: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   12711: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   12712: 
                   12713: this function automatically caches all requests
1.191     harris41 12714: 
                   12715: =item *
                   12716: 
1.243     albertel 12717: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   12718: network of library servers; returns file handle of where SQL and regex results
                   12719: will be stored for query
1.191     harris41 12720: 
                   12721: =item *
                   12722: 
1.243     albertel 12723: symbread($filename) : return symbolic list entry (filename argument optional);
                   12724: returns the data handle
1.191     harris41 12725: 
                   12726: =item *
                   12727: 
1.1172.2.11  raeburn  12728: symbverify($symb,$thisfn,$ecstate) : verifies that $symb actually exists
                   12729: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 12730: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  12731: on failure, user must be in a course, as it assumes the existence of
                   12732: the course initial hash, and uses $env('request.course.id'}.  The third
                   12733: arg is an optional reference to a scalar.  If this arg is passed in the
                   12734: call to symbverify, it will be set to 1 if the symb has been set to be 
                   12735: encrypted; otherwise it will be null.
1.243     albertel 12736: 
1.191     harris41 12737: =item *
                   12738: 
1.243     albertel 12739: symbclean($symb) : removes versions numbers from a symb, returns the
                   12740: cleaned symb
1.191     harris41 12741: 
                   12742: =item *
                   12743: 
1.243     albertel 12744: is_on_map($uri) : checks if the $uri is somewhere on the current
                   12745: course map, user must be in a course for it to work.
1.191     harris41 12746: 
                   12747: =item *
                   12748: 
1.243     albertel 12749: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 12750: 
                   12751: =item *
                   12752: 
1.243     albertel 12753: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   12754: a random seed, all arguments are optional, if they aren't sent it uses the
                   12755: environment to derive them. Note: if symb isn't sent and it can't get one
                   12756: from &symbread it will use the current time as its return value
1.191     harris41 12757: 
                   12758: =item *
                   12759: 
1.243     albertel 12760: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   12761: unfakeable, receipt
1.191     harris41 12762: 
                   12763: =item *
                   12764: 
1.620     albertel 12765: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 12766: 
                   12767: =item *
                   12768: 
1.243     albertel 12769: countacc($url) : count the number of accesses to a given URL
1.191     harris41 12770: 
                   12771: =item *
                   12772: 
1.243     albertel 12773: 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 12774: 
                   12775: =item *
                   12776: 
1.243     albertel 12777: 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 12778: 
                   12779: =item *
                   12780: 
1.243     albertel 12781: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 12782: 
                   12783: =item *
                   12784: 
1.243     albertel 12785: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   12786: forcing spreadsheet to reevaluate the resource scores next time.
                   12787: 
1.1172.2.13! raeburn  12788: =item *
        !          12789: 
        !          12790: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
        !          12791: when viewing in course context.
        !          12792: 
        !          12793:  input: six args -- filename (decluttered), course number, course domain,
        !          12794:                     url, symb (if registered) and group (if this is a
        !          12795:                     group item -- e.g., bulletin board, group page etc.).
        !          12796: 
        !          12797:  output: array of five scalars --
        !          12798:          $cfile -- url for file editing if editable on current server
        !          12799:          $home -- homeserver of resource (i.e., for author if published,
        !          12800:                                           or course if uploaded.).
        !          12801:          $switchserver --  1 if server switch will be needed.
        !          12802:          $forceedit -- 1 if icon/link should be to go to edit mode
        !          12803:          $forceview -- 1 if icon/link should be to go to view mode
        !          12804: 
        !          12805: =item *
        !          12806: 
        !          12807: is_course_upload($file,$cnum,$cdom)
        !          12808: 
        !          12809: Used in course context to determine if current file was uploaded to
        !          12810: the course (i.e., would be found in /userfiles/docs on the course's
        !          12811: homeserver.
        !          12812: 
        !          12813:   input: 3 args -- filename (decluttered), course number and course domain.
        !          12814:   output: boolean -- 1 if file was uploaded.
        !          12815: 
1.243     albertel 12816: =back
                   12817: 
                   12818: =head2 Storing/Retreiving Data
                   12819: 
                   12820: =over 4
1.191     harris41 12821: 
                   12822: =item *
                   12823: 
1.243     albertel 12824: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   12825: for this url; hashref needs to be given and should be a \%hashname; the
                   12826: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 12827: be derived from the env
1.191     harris41 12828: 
                   12829: =item *
                   12830: 
1.243     albertel 12831: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   12832: uses critical subroutine
1.191     harris41 12833: 
                   12834: =item *
                   12835: 
1.243     albertel 12836: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   12837: all args are optional
1.191     harris41 12838: 
                   12839: =item *
                   12840: 
1.717     albertel 12841: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   12842: dumps the complete (or key matching regexp) namespace into a hash
                   12843: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   12844: normally &store()ed into
                   12845: 
                   12846: $range should be either an integer '100' (give me the first 100
                   12847:                                            matching records)
                   12848:               or be  two integers sperated by a - with no spaces
                   12849:                  '30-50' (give me the 30th through the 50th matching
                   12850:                           records)
                   12851: 
                   12852: 
                   12853: =item *
                   12854: 
                   12855: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   12856: replaces a &store() version of data with a replacement set of data
                   12857: for a particular resource in a namespace passed in the $storehash hash 
                   12858: reference
                   12859: 
                   12860: =item *
                   12861: 
1.243     albertel 12862: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   12863: works very similar to store/cstore, but all data is stored in a
                   12864: temporary location and can be reset using tmpreset, $storehash should
                   12865: be a hash reference, returns nothing on success
1.191     harris41 12866: 
                   12867: =item *
                   12868: 
1.243     albertel 12869: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   12870: similar to restore, but all data is stored in a temporary location and
                   12871: can be reset using tmpreset. Returns a hash of values on success,
                   12872: error string otherwise.
1.191     harris41 12873: 
                   12874: =item *
                   12875: 
1.243     albertel 12876: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   12877: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 12878: 
                   12879: =item *
                   12880: 
1.243     albertel 12881: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   12882: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 12883: 
                   12884: =item *
                   12885: 
1.243     albertel 12886: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   12887: namesp ($udom and $uname are optional)
1.191     harris41 12888: 
                   12889: =item *
                   12890: 
1.702     albertel 12891: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 12892: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 12893: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  12894: 
1.702     albertel 12895: $range should be either an integer '100' (give me the first 100
                   12896:                                            matching records)
                   12897:               or be  two integers sperated by a - with no spaces
                   12898:                  '30-50' (give me the 30th through the 50th matching
                   12899:                           records)
1.449     matthew  12900: =item *
                   12901: 
                   12902: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   12903: $store can be a scalar, an array reference, or if the amount to be 
                   12904: incremented is > 1, a hash reference.
                   12905: 
                   12906: ($udom and $uname are optional)
1.191     harris41 12907: 
                   12908: =item *
                   12909: 
1.243     albertel 12910: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   12911: ($udom and $uname are optional)
1.191     harris41 12912: 
                   12913: =item *
                   12914: 
1.243     albertel 12915: cput($namespace,$storehash,$udom,$uname) : critical put
                   12916: ($udom and $uname are optional)
1.191     harris41 12917: 
                   12918: =item *
                   12919: 
1.748     albertel 12920: newput($namespace,$storehash,$udom,$uname) :
                   12921: 
                   12922: Attempts to store the items in the $storehash, but only if they don't
                   12923: currently exist, if this succeeds you can be certain that you have 
                   12924: successfully created a new key value pair in the $namespace db.
                   12925: 
                   12926: 
                   12927: Args:
                   12928:  $namespace: name of database to store values to
                   12929:  $storehash: hashref to store to the db
                   12930:  $udom: (optional) domain of user containing the db
                   12931:  $uname: (optional) name of user caontaining the db
                   12932: 
                   12933: Returns:
                   12934:  'ok' -> succeeded in storing all keys of $storehash
                   12935:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   12936:                         least <key> already existed in the db (other
                   12937:                         requested keys may also already exist)
1.967     bisitz   12938:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 12939:  'con_lost' -> unable to contact request server
                   12940:  'refused' -> action was not allowed by remote machine
                   12941: 
                   12942: 
                   12943: =item *
                   12944: 
1.243     albertel 12945: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   12946: reference filled in from namesp (encrypts the return communication)
                   12947: ($udom and $uname are optional)
1.191     harris41 12948: 
                   12949: =item *
                   12950: 
1.243     albertel 12951: log($udom,$name,$home,$message) : write to permanent log for user; use
                   12952: critical subroutine
                   12953: 
1.806     raeburn  12954: =item *
                   12955: 
1.860     raeburn  12956: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   12957: array reference filled in from namespace found in domain level on either
                   12958: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  12959: 
                   12960: =item *
                   12961: 
1.860     raeburn  12962: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   12963: domain level either on specified domain server ($uhome) or primary domain 
                   12964: server ($udom and $uhome are optional)
1.806     raeburn  12965: 
1.943     raeburn  12966: =item * 
                   12967: 
                   12968: get_domain_defaults($target_domain) : returns hash with defaults for
                   12969: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   12970: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   12971: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   12972: Values are retrieved from cache (if current), or from domain's configuration.db
                   12973: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   12974: or lonTabs/domain.tab. 
                   12975: 
                   12976: %domdefaults = &get_auth_defaults($target_domain);
                   12977: 
1.243     albertel 12978: =back
                   12979: 
                   12980: =head2 Network Status Functions
                   12981: 
                   12982: =over 4
1.191     harris41 12983: 
                   12984: =item *
                   12985: 
1.1137    raeburn  12986: dirlist() : return directory list based on URI (first arg).
                   12987: 
                   12988: Inputs: 1 required, 5 optional.
                   12989: 
                   12990: =over
                   12991: 
                   12992: =item 
                   12993: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   12994: 
                   12995: =item
                   12996: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   12997: 
                   12998: =item
                   12999: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   13000: 
                   13001: =item
                   13002: $getpropath - boolean: 1 if prepend path using &propath(). 
                   13003: 
                   13004: =item
                   13005: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   13006: 
                   13007: =item 
                   13008: $alternateRoot - path to prepend in place of path from $uri.
                   13009: 
                   13010: =back
                   13011: 
                   13012: Returns: Array of up to two items.
                   13013: 
                   13014: =over
                   13015: 
                   13016: a reference to an array of files/subdirectories
                   13017: 
                   13018: =over
                   13019: 
                   13020: Each element in the array of files/subdirectories is a & separated list of
                   13021: item name and the result of running stat on the item.  If dirlist was requested
                   13022: for a file instead of a directory, the item name will be ''. For a directory 
                   13023: listing, if the item is a metadata file, the element will end &N&M 
                   13024: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   13025: default copyright set (1).  
                   13026: 
                   13027: =back
                   13028: 
                   13029: a scalar containing error condition (if encountered).
                   13030: 
                   13031: =over
                   13032: 
                   13033: =item 
                   13034: no_host (no homeserver identified for $username:$domain).
                   13035: 
                   13036: =item 
                   13037: no_such_host (server contacted for listing not identified as valid host).
                   13038: 
                   13039: =item 
                   13040: con_lost (connection to remote server failed).
                   13041: 
                   13042: =item 
                   13043: refused (invalid $username:$domain received on lond side).
                   13044: 
                   13045: =item 
                   13046: no_such_dir (directory at specified path on lond side does not exist). 
                   13047: 
                   13048: =item 
                   13049: empty (directory at specified path on lond side is empty).
                   13050: 
                   13051: =over
                   13052: 
                   13053: This is currently not encountered because the &ls3, &ls2, 
                   13054: &ls (_handler) routines on the lond side do not filter out
                   13055: . and .. from a directory listing. 
                   13056: 
                   13057: =back
                   13058: 
                   13059: =back
                   13060: 
                   13061: =back
1.191     harris41 13062: 
                   13063: =item *
                   13064: 
1.243     albertel 13065: spareserver() : find server with least workload from spare.tab
                   13066: 
1.986     foxr     13067: 
                   13068: =item *
                   13069: 
                   13070: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   13071: if there is no corresponding loncapa host.
                   13072: 
1.243     albertel 13073: =back
                   13074: 
1.986     foxr     13075: 
1.243     albertel 13076: =head2 Apache Request
                   13077: 
                   13078: =over 4
1.191     harris41 13079: 
                   13080: =item *
                   13081: 
1.243     albertel 13082: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   13083: localhost, posts hash
                   13084: 
                   13085: =back
                   13086: 
                   13087: =head2 Data to String to Data
                   13088: 
                   13089: =over 4
1.191     harris41 13090: 
                   13091: =item *
                   13092: 
1.243     albertel 13093: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   13094: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 13095: 
                   13096: =item *
                   13097: 
1.243     albertel 13098: hashref2str($hashref) : convert a hashref into a string complete with
                   13099: escaping and '=' and '&' separators, supports elements that are
                   13100: arrayrefs and hashrefs
1.191     harris41 13101: 
                   13102: =item *
                   13103: 
1.243     albertel 13104: arrayref2str($arrayref) : convert an arrayref into a string complete
                   13105: with escaping and '&' separators, supports elements that are arrayrefs
                   13106: and hashrefs
1.191     harris41 13107: 
                   13108: =item *
                   13109: 
1.243     albertel 13110: str2hash($string) : convert string to hash using unescaping and
                   13111: splitting on '=' and '&', supports elements that are arrayrefs and
                   13112: hashrefs
1.191     harris41 13113: 
                   13114: =item *
                   13115: 
1.243     albertel 13116: str2array($string) : convert string to hash using unescaping and
                   13117: splitting on '&', supports elements that are arrayrefs and hashrefs
                   13118: 
                   13119: =back
                   13120: 
                   13121: =head2 Logging Routines
                   13122: 
                   13123: 
                   13124: These routines allow one to make log messages in the lonnet.log and
                   13125: lonnet.perm logfiles.
1.191     harris41 13126: 
1.1119    foxr     13127: =over 4
                   13128: 
1.191     harris41 13129: =item *
                   13130: 
1.243     albertel 13131: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 13132: 
                   13133: =item *
                   13134: 
1.243     albertel 13135: logthis() : append message to the normal lonnet.log file, it gets
                   13136: preiodically rolled over and deleted.
1.191     harris41 13137: 
                   13138: =item *
                   13139: 
1.243     albertel 13140: logperm() : append a permanent message to lonnet.perm.log, this log
                   13141: file never gets deleted by any automated portion of the system, only
                   13142: messages of critical importance should go in here.
                   13143: 
1.1119    foxr     13144: 
1.243     albertel 13145: =back
                   13146: 
                   13147: =head2 General File Helper Routines
                   13148: 
                   13149: =over 4
1.191     harris41 13150: 
                   13151: =item *
                   13152: 
1.481     raeburn  13153: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   13154: (a) files in /uploaded
                   13155:   (i) If a local copy of the file exists - 
                   13156:       compares modification date of local copy with last-modified date for 
                   13157:       definitive version stored on home server for course. If local copy is 
                   13158:       stale, requests a new version from the home server and stores it. 
                   13159:       If the original has been removed from the home server, then local copy 
                   13160:       is unlinked.
                   13161:   (ii) If local copy does not exist -
                   13162:       requests the file from the home server and stores it. 
                   13163:   
                   13164:   If $caller is 'uploadrep':  
                   13165:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   13166:     for request for files originally uploaded via DOCS. 
                   13167:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   13168:   
                   13169:   Otherwise:
                   13170:      This indicates a call from the content generation phase of the request.
                   13171:      -  returns the entire contents of the file or -1.
                   13172:      
                   13173: (b) files in /res
                   13174:    - returns the entire contents of a file or -1; 
                   13175:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 13176: 
1.712     albertel 13177: 
                   13178: =item *
                   13179: 
                   13180: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   13181:                   reference
                   13182: 
                   13183: returns either a stat() list of data about the file or an empty list
                   13184: if the file doesn't exist or couldn't find out about it (connection
                   13185: problems or user unknown)
                   13186: 
1.191     harris41 13187: =item *
                   13188: 
1.243     albertel 13189: filelocation($dir,$file) : returns file system location of a file
                   13190: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   13191: directory that relative $file lookups are to looked in ($dir of /a/dir
                   13192: and a file of ../bob will become /a/bob)
1.191     harris41 13193: 
                   13194: =item *
                   13195: 
                   13196: hreflocation($dir,$file) : returns file system location or a URL; same as
                   13197: filelocation except for hrefs
                   13198: 
                   13199: =item *
                   13200: 
                   13201: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   13202: 
1.243     albertel 13203: =back
                   13204: 
1.608     albertel 13205: =head2 Usererfile file routines (/uploaded*)
                   13206: 
                   13207: =over 4
                   13208: 
                   13209: =item *
                   13210: 
                   13211: userfileupload(): main rotine for putting a file in a user or course's
                   13212:                   filespace, arguments are,
                   13213: 
1.620     albertel 13214:  formname - required - this is the name of the element in $env where the
1.608     albertel 13215:            filename, and the contents of the file to create/modifed exist
1.620     albertel 13216:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   13217:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  13218:  context - if coursedoc, store the file in the course of the active role
                   13219:              of the current user; 
                   13220:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   13221:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 13222:  subdir - required - subdirectory to put the file in under ../userfiles/
                   13223:          if undefined, it will be placed in "unknown"
                   13224: 
                   13225:  (This routine calls clean_filename() to remove any dangerous
                   13226:  characters from the filename, and then calls finuserfileupload() to
                   13227:  complete the transaction)
                   13228: 
                   13229:  returns either the url of the uploaded file (/uploaded/....) if successful
                   13230:  and /adm/notfound.html if unsuccessful
                   13231: 
                   13232: =item *
                   13233: 
                   13234: clean_filename(): routine for cleaing a filename up for storage in
                   13235:                  userfile space, argument is:
                   13236: 
                   13237:  filename - proposed filename
                   13238: 
                   13239: returns: the new clean filename
                   13240: 
                   13241: =item *
                   13242: 
1.1090    raeburn  13243: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 13244: userspace, probably shouldn't be called directly
                   13245: 
                   13246:   docuname: username or courseid of destination for the file
                   13247:   docudom: domain of user/course of destination for the file
                   13248:   formname: same as for userfileupload()
1.1090    raeburn  13249:   fname: filename (including subdirectories) for the file
                   13250:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   13251:   allfiles: reference to hash used to store objects found by parser
                   13252:   codebase: reference to hash used for codebases of java objects found by parser
                   13253:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   13254:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   13255:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   13256:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   13257:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   13258:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  13259:   mimetype: reference to scalar to accommodate mime type determined
                   13260:             from File::MMagic if $parser = parse.
1.608     albertel 13261: 
                   13262:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  13263:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   13264:  was 'overwrite').
                   13265:  
1.608     albertel 13266: 
                   13267: =item *
                   13268: 
                   13269: renameuserfile(): renames an existing userfile to a new name
                   13270: 
                   13271:   Args:
                   13272:    docuname: username or courseid of destination for the file
                   13273:    docudom: domain of user/course of destination for the file
                   13274:    old: current file name (including any subdirs under userfiles)
                   13275:    new: desired file name (including any subdirs under userfiles)
                   13276: 
                   13277: =item *
                   13278: 
                   13279: mkdiruserfile(): creates a directory is a userfiles dir
                   13280: 
                   13281:   Args:
                   13282:    docuname: username or courseid of destination for the file
                   13283:    docudom: domain of user/course of destination for the file
                   13284:    dir: dir to create (including any subdirs under userfiles)
                   13285: 
                   13286: =item *
                   13287: 
                   13288: removeuserfile(): removes a file that exists in userfiles
                   13289: 
                   13290:   Args:
                   13291:    docuname: username or courseid of destination for the file
                   13292:    docudom: domain of user/course of destination for the file
                   13293:    fname: filname to delete (including any subdirs under userfiles)
                   13294: 
                   13295: =item *
                   13296: 
                   13297: removeuploadedurl(): convience function for removeuserfile()
                   13298: 
                   13299:   Args:
                   13300:    url:  a full /uploaded/... url to delete
                   13301: 
1.747     albertel 13302: =item * 
                   13303: 
                   13304: get_portfile_permissions():
                   13305:   Args:
                   13306:     domain: domain of user or course contain the portfolio files
                   13307:     user: name of user or num of course contain the portfolio files
                   13308:   Returns:
                   13309:     hashref of a dump of the proper file_permissions.db
                   13310:    
                   13311: 
                   13312: =item * 
                   13313: 
                   13314: get_access_controls():
                   13315: 
                   13316: Args:
                   13317:   current_permissions: the hash ref returned from get_portfile_permissions()
                   13318:   group: (optional) the group you want the files associated with
                   13319:   file: (optional) the file you want access info on
                   13320: 
                   13321: Returns:
1.749     raeburn  13322:     a hash (keys are file names) of hashes containing
                   13323:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   13324:         values are XML containing access control settings (see below) 
1.747     albertel 13325: 
                   13326: Internal notes:
                   13327: 
1.749     raeburn  13328:  access controls are stored in file_permissions.db as key=value pairs.
                   13329:     key -> path to file/file_name\0uniqueID:scope_end_start
                   13330:         where scope -> public,guest,course,group,domains or users.
                   13331:               end -> UNIX time for end of access (0 -> no end date)
                   13332:               start -> UNIX time for start of access
                   13333: 
                   13334:     value -> XML description of access control
                   13335:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   13336:             <start></start>
                   13337:             <end></end>
                   13338: 
                   13339:             <password></password>  for scope type = guest
                   13340: 
                   13341:             <domain></domain>     for scope type = course or group
                   13342:             <number></number>
                   13343:             <roles id="">
                   13344:              <role></role>
                   13345:              <access></access>
                   13346:              <section></section>
                   13347:              <group></group>
                   13348:             </roles>
                   13349: 
                   13350:             <dom></dom>         for scope type = domains
                   13351: 
                   13352:             <users>             for scope type = users
                   13353:              <user>
                   13354:               <uname></uname>
                   13355:               <udom></udom>
                   13356:              </user>
                   13357:             </users>
                   13358:            </scope> 
                   13359:               
                   13360:  Access data is also aggregated for each file in an additional key=value pair:
                   13361:  key -> path to file/file_name\0accesscontrol 
                   13362:  value -> reference to hash
                   13363:           hash contains key = value pairs
                   13364:           where key = uniqueID:scope_end_start
                   13365:                 value = UNIX time record was last updated
                   13366: 
                   13367:           Used to improve speed of look-ups of access controls for each file.  
                   13368:  
                   13369:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   13370: 
1.1172.2.13! raeburn  13371: =item *
        !          13372: 
1.749     raeburn  13373: modify_access_controls():
                   13374: 
                   13375: Modifies access controls for a portfolio file
                   13376: Args
                   13377: 1. file name
                   13378: 2. reference to hash of required changes,
                   13379: 3. domain
                   13380: 4. username
                   13381:   where domain,username are the domain of the portfolio owner 
                   13382:   (either a user or a course) 
                   13383: 
                   13384: Returns:
                   13385: 1. result of additions or updates ('ok' or 'error', with error message). 
                   13386: 2. result of deletions ('ok' or 'error', with error message).
                   13387: 3. reference to hash of any new or updated access controls.
                   13388: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   13389:    key = integer (inbound ID)
1.1172.2.13! raeburn  13390:    value = uniqueID
        !          13391: 
        !          13392: =item *
        !          13393: 
        !          13394: get_timebased_id():
        !          13395: 
        !          13396: Attempts to get a unique timestamp-based suffix for use with items added to a
        !          13397: course via the Course Editor (e.g., folders, composite pages,
        !          13398: group bulletin boards).
        !          13399: 
        !          13400: Args: (first three required; six others optional)
        !          13401: 
        !          13402: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
        !          13403:    docssequence, or name of group
        !          13404: 
        !          13405: 2. keyid (alphanumeric): name of temporary locking key in hash,
        !          13406:    e.g., num, boardids
        !          13407: 
        !          13408: 3. namespace: name of gdbm file used to store suffixes already assigned;
        !          13409:    file will be named nohist_namespace.db
        !          13410: 
        !          13411: 4. cdom: domain of course; default is current course domain from %env
        !          13412: 
        !          13413: 5. cnum: course number; default is current course number from %env
        !          13414: 
        !          13415: 6. idtype: set to concat if an additional digit is to be appended to the
        !          13416:    unix timestamp to form the suffix, if the plain timestamp is already
        !          13417:    in use.  Default is to not do this, but simply increment the unix
        !          13418:    timestamp by 1 until a unique key is obtained.
        !          13419: 
        !          13420: 7. who: holder of locking key; defaults to user:domain for user.
        !          13421: 
        !          13422: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
        !          13423:    retrying); default is 3.
        !          13424: 
        !          13425: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
        !          13426: 
        !          13427: Returns:
        !          13428: 
        !          13429: 1. suffix obtained (numeric)
        !          13430: 
        !          13431: 2. result of deleting locking key (ok if deleted, or lock never obtained)
        !          13432: 
        !          13433: 3. error: contains (localized) error message if an error occurred.
        !          13434: 
1.747     albertel 13435: 
1.608     albertel 13436: =back
                   13437: 
1.243     albertel 13438: =head2 HTTP Helper Routines
                   13439: 
                   13440: =over 4
                   13441: 
1.191     harris41 13442: =item *
                   13443: 
                   13444: escape() : unpack non-word characters into CGI-compatible hex codes
                   13445: 
                   13446: =item *
                   13447: 
                   13448: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   13449: 
1.243     albertel 13450: =back
                   13451: 
                   13452: =head1 PRIVATE SUBROUTINES
                   13453: 
                   13454: =head2 Underlying communication routines (Shouldn't call)
                   13455: 
                   13456: =over 4
                   13457: 
                   13458: =item *
                   13459: 
                   13460: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   13461: 
                   13462: =item *
                   13463: 
                   13464: reply() : uses subreply to send a message to remote machine, logs all failures
                   13465: 
                   13466: =item *
                   13467: 
                   13468: critical() : passes a critical message to another server; if cannot
                   13469: get through then place message in connection buffer directory and
                   13470: returns con_delayed, if incapable of saving message, returns
                   13471: con_failed
                   13472: 
                   13473: =item *
                   13474: 
                   13475: reconlonc() : tries to reconnect lonc client processes.
                   13476: 
                   13477: =back
                   13478: 
                   13479: =head2 Resource Access Logging
                   13480: 
                   13481: =over 4
                   13482: 
                   13483: =item *
                   13484: 
                   13485: flushcourselogs() : flush (save) buffer logs and access logs
                   13486: 
                   13487: =item *
                   13488: 
                   13489: courselog($what) : save message for course in hash
                   13490: 
                   13491: =item *
                   13492: 
                   13493: courseacclog($what) : save message for course using &courselog().  Perform
                   13494: special processing for specific resource types (problems, exams, quizzes, etc).
                   13495: 
1.191     harris41 13496: =item *
                   13497: 
                   13498: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   13499: as a PerlChildExitHandler
1.243     albertel 13500: 
                   13501: =back
                   13502: 
                   13503: =head2 Other
                   13504: 
                   13505: =over 4
                   13506: 
                   13507: =item *
                   13508: 
                   13509: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 13510: 
                   13511: =back
                   13512: 
                   13513: =cut
1.877     foxr     13514: 

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