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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.15! raeburn     4: # $Id: lonnet.pm,v 1.1172.2.14 2012/12/21 17:01:04 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 {
1.1172.2.15! raeburn  2711:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
        !          2712:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
        !          2713:                     return;
        !          2714:                 }
        !          2715:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  2716: #
                   2717: # No edit allowed where CC has switched to student role.
                   2718: #
                   2719:                 return;
                   2720:             }
                   2721:         }
                   2722:     }
                   2723: 
                   2724:     if ($file ne '') {
                   2725:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   2726:             if (&is_course_upload($file,$cnum,$cdom)) {
                   2727:                 $uploaded = 1;
                   2728:                 $incourse = 1;
                   2729:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   2730:                     $cfile = &hreflocation('',$file);
                   2731:                     if ($env{'form.forceedit'}) {
                   2732:                         $forceview = 1;
                   2733:                     } else {
                   2734:                         $forceedit = 1;
                   2735:                     }
                   2736:                 }
                   2737:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   2738:                 $incourse = 1;
                   2739:                 if ($env{'form.forceedit'}) {
                   2740:                     $forceview = 1;
                   2741:                 } else {
                   2742:                     $forceedit = 1;
                   2743:                 }
                   2744:                 $cfile = $resurl;
                   2745:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   2746:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   2747:                     $incourse = 1;
                   2748:                     if ($env{'form.forceedit'}) {
                   2749:                         $forceview = 1;
                   2750:                     } else {
                   2751:                         $forceedit = 1;
                   2752:                     }
                   2753:                     $cfile = $resurl;
                   2754:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   2755:                     $incourse = 1;
                   2756:                     $cfile = $resurl.'/smpedit';
                   2757:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   2758:                     $incourse = 1;
                   2759:                     if ($env{'form.forceedit'}) {
                   2760:                         $forceview = 1;
                   2761:                     } else {
                   2762:                         $forceedit = 1;
                   2763:                     }
                   2764:                     $cfile = $resurl;
1.1172.2.15! raeburn  2765:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
        !          2766:                     $incourse = 1;
        !          2767:                     if ($env{'form.forceedit'}) {
        !          2768:                         $forceview = 1;
        !          2769:                     } else {
        !          2770:                         $forceedit = 1;
        !          2771:                     }
        !          2772:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  2773:                 }
                   2774:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   2775:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   2776:                 if (&is_on_map($template)) {
                   2777:                     $incourse = 1;
                   2778:                     $forceview = 1;
                   2779:                     $cfile = $template;
                   2780:                 }
                   2781:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   2782:                     $incourse = 1;
                   2783:                     if ($env{'form.forceedit'}) {
                   2784:                         $forceview = 1;
                   2785:                     } else {
                   2786:                         $forceedit = 1;
                   2787:                     }
                   2788:                     $cfile = $resurl;
                   2789:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   2790:                 $incourse = 1;
                   2791:                 $forceview = 1;
                   2792:                 if ($symb) {
                   2793:                     my ($map,$id,$res)=&decode_symb($symb);
                   2794:                     $env{'request.symb'} = $symb;
                   2795:                     $cfile = &clutter($res);
                   2796:                 } else {
                   2797:                     $cfile = $env{'form.suppurl'};
                   2798:                     $cfile =~ s{^http://}{};
                   2799:                     $cfile = '/adm/wrapper/ext/'.$cfile;
                   2800:                 }
                   2801:             }
                   2802:         }
                   2803:         if ($uploaded || $incourse) {
                   2804:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  2805:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  2806:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   2807:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   2808:             # Check that the user has permission to edit this resource
                   2809:             my $setpriv = 1;
                   2810:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   2811:             if (defined($cfudom)) {
                   2812:                 $home=&homeserver($cfuname,$cfudom);
                   2813:                 $cfile=$file;
                   2814:             }
                   2815:         }
                   2816:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   2817:             (($home ne '') && ($home ne 'no_host'))) {
                   2818:             my @ids=&current_machine_ids();
                   2819:             unless (grep(/^\Q$home\E$/,@ids)) {
                   2820:                 $switchserver=1;
                   2821:             }
                   2822:         }
                   2823:     }
                   2824:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   2825: }
                   2826: 
                   2827: sub is_course_upload {
                   2828:     my ($file,$cnum,$cdom) = @_;
                   2829:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   2830:     $uploadpath =~ s{^\/}{};
                   2831:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   2832:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   2833:         return 1;
                   2834:     }
                   2835:     return;
                   2836: }
                   2837: 
                   2838: sub in_course {
                   2839:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   2840:     if ($hideprivileged) {
                   2841:         my $skipuser;
                   2842:         if (&privileged($uname,$udom)) {
                   2843:             $skipuser = 1;
                   2844:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   2845:             if ($coursehash{'nothideprivileged'}) {
                   2846:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2847:                     my $user;
                   2848:                     if ($item =~ /:/) {
                   2849:                         $user = $item;
                   2850:                     } else {
                   2851:                         $user = join(':',split(/[\@]/,$item));
                   2852:                     }
                   2853:                     if ($user eq $uname.':'.$udom) {
                   2854:                         undef($skipuser);
                   2855:                         last;
                   2856:                     }
                   2857:                 }
                   2858:             }
                   2859:             if ($skipuser) {
                   2860:                 return 0;
                   2861:             }
                   2862:         }
                   2863:     }
                   2864:     $type ||= 'any';
                   2865:     if (!defined($cdom) || !defined($cnum)) {
                   2866:         my $cid  = $env{'request.course.id'};
                   2867:         $cdom = $env{'course.'.$cid.'.domain'};
                   2868:         $cnum = $env{'course.'.$cid.'.num'};
                   2869:     }
                   2870:     my $typesref;
                   2871:     if (($type eq 'any') || ($type eq 'all')) {
                   2872:         $typesref = ['active','previous','future'];
                   2873:     } elsif ($type eq 'previous' || $type eq 'future') {
                   2874:         $typesref = [$type];
                   2875:     }
                   2876:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   2877:                               $typesref,undef,[$cdom]);
                   2878:     my ($tmp) = keys(%roles);
                   2879:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   2880:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   2881:     if (@course_roles > 0) {
                   2882:         return 1;
                   2883:     }
                   2884:     return 0;
                   2885: }
                   2886: 
1.478     albertel 2887: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2888: # input: action, courseID, current domain, intended
1.637     raeburn  2889: #        path to file, source of file, instruction to parse file for objects,
                   2890: #        ref to hash for embedded objects,
                   2891: #        ref to hash for codebase of java objects.
1.1095    raeburn  2892: #        reference to scalar to accommodate mime type determined
                   2893: #          from File::MMagic if $parser = parse.
1.637     raeburn  2894: #
1.485     raeburn  2895: # output: url to file (if action was uploaddoc), 
                   2896: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2897: #
1.478     albertel 2898: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2899: # course.
1.477     raeburn  2900: #
1.478     albertel 2901: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2902: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2903: #          course's home server.
1.477     raeburn  2904: #
1.478     albertel 2905: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2906: #          be copied from $source (current location) to 
                   2907: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2908: #         and will then be copied to
                   2909: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2910: #         course's home server.
1.485     raeburn  2911: #
1.481     raeburn  2912: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2913: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2914: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2915: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2916: #         in course's home server.
1.637     raeburn  2917: #
1.477     raeburn  2918: 
                   2919: sub process_coursefile {
1.1095    raeburn  2920:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   2921:         $mimetype)=@_;
1.477     raeburn  2922:     my $fetchresult;
1.638     albertel 2923:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2924:     if ($action eq 'propagate') {
1.638     albertel 2925:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2926: 			     $home);
1.481     raeburn  2927:     } else {
1.477     raeburn  2928:         my $fpath = '';
                   2929:         my $fname = $file;
1.478     albertel 2930:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2931:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2932:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2933:         if ($action eq 'copy') {
                   2934:             if ($source eq '') {
                   2935:                 $fetchresult = 'no source file';
                   2936:                 return $fetchresult;
                   2937:             } else {
                   2938:                 my $destination = $filepath.'/'.$fname;
                   2939:                 rename($source,$destination);
                   2940:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2941:                                  $home);
1.481     raeburn  2942:             }
                   2943:         } elsif ($action eq 'uploaddoc') {
                   2944:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2945:             print $fh $env{'form.'.$source};
1.481     raeburn  2946:             close($fh);
1.637     raeburn  2947:             if ($parser eq 'parse') {
1.1024    raeburn  2948:                 my $mm = new File::MMagic;
1.1095    raeburn  2949:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   2950:                 if ($type eq 'text/html') {
1.1024    raeburn  2951:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   2952:                     unless ($parse_result eq 'ok') {
                   2953:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2954:                     }
1.637     raeburn  2955:                 }
1.1095    raeburn  2956:                 if (ref($mimetype)) {
                   2957:                     $$mimetype = $type;
                   2958:                 } 
1.637     raeburn  2959:             }
1.477     raeburn  2960:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2961:                                  $home);
1.481     raeburn  2962:             if ($fetchresult eq 'ok') {
                   2963:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2964:             } else {
                   2965:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2966:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2967:                 return '/adm/notfound.html';
                   2968:             }
1.477     raeburn  2969:         }
                   2970:     }
1.485     raeburn  2971:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2972:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2973:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2974:     }
                   2975:     return $fetchresult;
                   2976: }
                   2977: 
1.637     raeburn  2978: sub build_filepath {
                   2979:     my ($fpath) = @_;
                   2980:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2981:     unless ($fpath eq '') {
                   2982:         my @parts=split('/',$fpath);
                   2983:         foreach my $part (@parts) {
                   2984:             $filepath.= '/'.$part;
                   2985:             if ((-e $filepath)!=1) {
                   2986:                 mkdir($filepath,0777);
                   2987:             }
                   2988:         }
                   2989:     }
                   2990:     return $filepath;
                   2991: }
                   2992: 
                   2993: sub store_edited_file {
1.638     albertel 2994:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  2995:     my $file = $primary_url;
                   2996:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   2997:     my $fpath = '';
                   2998:     my $fname = $file;
                   2999:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3000:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3001:     my $filepath = &build_filepath($fpath);
                   3002:     open(my $fh,'>'.$filepath.'/'.$fname);
                   3003:     print $fh $content;
                   3004:     close($fh);
1.638     albertel 3005:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3006:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3007: 			  $home);
1.637     raeburn  3008:     if ($$fetchresult eq 'ok') {
                   3009:         return '/uploaded/'.$fpath.'/'.$fname;
                   3010:     } else {
1.638     albertel 3011:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3012: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3013:         return '/adm/notfound.html';
                   3014:     }
                   3015: }
                   3016: 
1.531     albertel 3017: sub clean_filename {
1.831     albertel 3018:     my ($fname,$args)=@_;
1.315     www      3019: # Replace Windows backslashes by forward slashes
1.257     www      3020:     $fname=~s/\\/\//g;
1.831     albertel 3021:     if (!$args->{'keep_path'}) {
                   3022:         # Get rid of everything but the actual filename
                   3023: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3024:     }
1.315     www      3025: # Replace spaces by underscores
                   3026:     $fname=~s/\s+/\_/g;
                   3027: # Replace all other weird characters by nothing
1.831     albertel 3028:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3029: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3030: # numbers
                   3031:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3032:     return $fname;
                   3033: }
1.1051    raeburn  3034: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3035: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3036: # image with the same aspect ratio as the original, but with dimensions which do 
                   3037: # not exceed $resizewidth and $resizeheight.
                   3038:  
1.984     neumanie 3039: sub resizeImage {
1.1051    raeburn  3040:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3041:     my $ima = Image::Magick->new;
                   3042:     my $resized;
                   3043:     if (-e $img_path) {
                   3044:         $ima->Read($img_path);
                   3045:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3046:             my $width = $ima->Get('width');
                   3047:             my $height = $ima->Get('height');
                   3048:             if ($width > $resizewidth) {
                   3049: 	        my $factor = $width/$resizewidth;
                   3050:                 my $newheight = $height/$factor;
                   3051:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3052:                 $resized = 1;
                   3053:             }
                   3054:         }
                   3055:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3056:             my $width = $ima->Get('width');
                   3057:             my $height = $ima->Get('height');
                   3058:             if ($height > $resizeheight) {
                   3059:                 my $factor = $height/$resizeheight;
                   3060:                 my $newwidth = $width/$factor;
                   3061:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3062:                 $resized = 1;
                   3063:             }
                   3064:         }
                   3065:         if ($resized) {
                   3066:             $ima->Write($img_path);
                   3067:         }
                   3068:     }
                   3069:     return;
1.977     amueller 3070: }
                   3071: 
1.608     albertel 3072: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3073: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3074: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3075: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3076: #                                    canceloverwrite, or ''. 
                   3077: #                   if 'coursedoc': upload to the current course
                   3078: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3079: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3080: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3081: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3082: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3083: #        $allfiles - reference to hash for embedded objects
                   3084: #        $codebase - reference to hash for codebase of java objects
                   3085: #        $desuname - username for permanent storage of uploaded file
                   3086: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3087: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3088: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3089: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3090: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3091: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3092: #                    from File::MMagic.
1.858     raeburn  3093: # 
1.686     albertel 3094: # output: url of file in userspace, or error: <message> 
                   3095: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3096: 
1.531     albertel 3097: sub userfileupload {
1.1090    raeburn  3098:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3099:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3100:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3101:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3102:     $fname=&clean_filename($fname);
1.1090    raeburn  3103:     # See if there is anything left
1.257     www      3104:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3105:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3106:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3107:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3108:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3109:         my $now = time;
1.1090    raeburn  3110:         my $filepath;
1.1095    raeburn  3111:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3112:              $filepath = 'tmp/helprequests/'.$now;
                   3113:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3114:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3115:                          '_'.$env{'user.domain'}.'/pending';
                   3116:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3117:             my ($docuname,$docudom);
                   3118:             if ($destudom) {
                   3119:                 $docudom = $destudom;
                   3120:             } else {
                   3121:                 $docudom = $env{'user.domain'};
                   3122:             }
                   3123:             if ($destuname) {
                   3124:                 $docuname = $destuname;
                   3125:             } else {
                   3126:                 $docuname = $env{'user.name'};
                   3127:             }
                   3128:             if (exists($env{'form.group'})) {
                   3129:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3130:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3131:             }
                   3132:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3133:             if ($context eq 'canceloverwrite') {
                   3134:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3135:                 if (-e  $tempfile) {
                   3136:                     my @info = stat($tempfile);
                   3137:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3138:                         unlink($tempfile);
                   3139:                     }
                   3140:                 }
                   3141:                 return;
1.523     raeburn  3142:             }
                   3143:         }
1.1090    raeburn  3144:         # Create the directory if not present
1.741     raeburn  3145:         my @parts=split(/\//,$filepath);
                   3146:         my $fullpath = $perlvar{'lonDaemons'};
                   3147:         for (my $i=0;$i<@parts;$i++) {
                   3148:             $fullpath .= '/'.$parts[$i];
                   3149:             if ((-e $fullpath)!=1) {
                   3150:                 mkdir($fullpath,0777);
                   3151:             }
                   3152:         }
                   3153:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   3154:         print $fh $env{'form.'.$formname};
                   3155:         close($fh);
1.1090    raeburn  3156:         if ($context eq 'existingfile') {
                   3157:             my @info = stat($fullpath.'/'.$fname);
                   3158:             return ($fullpath.'/'.$fname,$info[9]);
                   3159:         } else {
                   3160:             return $fullpath.'/'.$fname;
                   3161:         }
1.523     raeburn  3162:     }
1.995     raeburn  3163:     if ($subdir eq 'scantron') {
                   3164:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3165:     } else {
1.995     raeburn  3166:         $fname="$subdir/$fname";
                   3167:     }
1.1090    raeburn  3168:     if ($context eq 'coursedoc') {
1.638     albertel 3169: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3170: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3171:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3172:             return &finishuserfileupload($docuname,$docudom,
                   3173: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3174: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3175:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3176:         } else {
1.620     albertel 3177:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 3178:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3179: 				       $fname,$formname,$parser,
1.1095    raeburn  3180: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3181:         }
1.719     banghart 3182:     } elsif (defined($destuname)) {
                   3183:         my $docuname=$destuname;
                   3184:         my $docudom=$destudom;
1.860     raeburn  3185: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3186: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3187:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3188:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3189:     } else {
1.638     albertel 3190:         my $docuname=$env{'user.name'};
                   3191:         my $docudom=$env{'user.domain'};
1.714     raeburn  3192:         if (exists($env{'form.group'})) {
                   3193:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3194:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3195:         }
1.860     raeburn  3196: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3197: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3198:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3199:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3200:     }
1.271     www      3201: }
                   3202: 
                   3203: sub finishuserfileupload {
1.860     raeburn  3204:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3205:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3206:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3207:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3208:   
1.860     raeburn  3209:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3210:     $file=$fname;
                   3211:     if ($fname=~m|/|) {
                   3212:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3213: 	$path.=$fnamepath.'/';
                   3214:     }
1.259     www      3215:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3216:     my $count;
                   3217:     for ($count=4;$count<=$#parts;$count++) {
                   3218:         $filepath.="/$parts[$count]";
                   3219:         if ((-e $filepath)!=1) {
                   3220: 	    mkdir($filepath,0777);
                   3221:         }
                   3222:     }
1.984     neumanie 3223: 
1.258     www      3224: # Save the file
                   3225:     {
1.701     albertel 3226: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   3227: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3228: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3229: 	    return '/adm/notfound.html';
                   3230: 	}
1.1090    raeburn  3231:         if ($context eq 'overwrite') {
1.1117    foxr     3232:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3233:             my $target = $filepath.'/'.$file;
                   3234:             if (-e $source) {
                   3235:                 my @info = stat($source);
                   3236:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3237:                     unless (&File::Copy::move($source,$target)) {
                   3238:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3239:                         return "Moving from $source failed";
                   3240:                     }
                   3241:                 } else {
                   3242:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3243:                 }
                   3244:             } else {
                   3245:                 return "Temporary file: $source missing";
                   3246:             }
                   3247:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3248: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3249: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3250: 	    return '/adm/notfound.html';
                   3251: 	}
1.570     albertel 3252: 	close(FH);
1.1051    raeburn  3253:         if ($resizewidth && $resizeheight) {
                   3254:             my $mm = new File::MMagic;
                   3255:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3256:             if ($mime_type =~ m{^image/}) {
                   3257: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3258:             }  
1.977     amueller 3259: 	}
1.258     www      3260:     }
1.1152    raeburn  3261:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3262:         if (ref($mimetype)) {
                   3263:             if ($$mimetype eq '') {
                   3264:                 my $mm = new File::MMagic;
                   3265:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3266:                 $$mimetype = $type;
                   3267:             }
                   3268:         }
                   3269:     }
1.637     raeburn  3270:     if ($parser eq 'parse') {
1.1152    raeburn  3271:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3272:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3273:                                                        $allfiles,$codebase);
                   3274:             unless ($parse_result eq 'ok') {
                   3275:                 &logthis('Failed to parse '.$filepath.$file.
                   3276: 	   	         ' for embedded media: '.$parse_result); 
                   3277:             }
1.637     raeburn  3278:         }
                   3279:     }
1.860     raeburn  3280:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3281:         my $input = $filepath.'/'.$file;
                   3282:         my $output = $filepath.'/'.'tn-'.$file;
                   3283:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3284:         system("convert -sample $thumbsize $input $output");
                   3285:         if (-e $filepath.'/'.'tn-'.$file) {
                   3286:             $fetchthumb  = 1; 
                   3287:         }
                   3288:     }
1.858     raeburn  3289:  
1.259     www      3290: # Notify homeserver to grep it
                   3291: #
1.984     neumanie 3292:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3293:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3294:     if ($fetchresult eq 'ok') {
1.860     raeburn  3295:         if ($fetchthumb) {
                   3296:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3297:             if ($thumbresult ne 'ok') {
                   3298:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3299:                          $docuhome.': '.$thumbresult);
                   3300:             }
                   3301:         }
1.259     www      3302: #
1.258     www      3303: # Return the URL to it
1.494     albertel 3304:         return '/uploaded/'.$path.$file;
1.263     www      3305:     } else {
1.494     albertel 3306:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3307: 		 ': '.$fetchresult);
1.263     www      3308:         return '/adm/notfound.html';
1.858     raeburn  3309:     }
1.493     albertel 3310: }
                   3311: 
1.637     raeburn  3312: sub extract_embedded_items {
1.961     raeburn  3313:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3314:     my @state = ();
1.1164    raeburn  3315:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3316:     my %javafiles = (
                   3317:                       codebase => '',
                   3318:                       code => '',
                   3319:                       archive => ''
                   3320:                     );
                   3321:     my %mediafiles = (
                   3322:                       src => '',
                   3323:                       movie => '',
                   3324:                      );
1.648     raeburn  3325:     my $p;
                   3326:     if ($content) {
                   3327:         $p = HTML::LCParser->new($content);
                   3328:     } else {
1.961     raeburn  3329:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3330:     }
1.641     albertel 3331:     while (my $t=$p->get_token()) {
1.640     albertel 3332: 	if ($t->[0] eq 'S') {
                   3333: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3334: 	    push(@state, $tagname);
1.648     raeburn  3335:             if (lc($tagname) eq 'allow') {
                   3336:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3337:             }
1.640     albertel 3338: 	    if (lc($tagname) eq 'img') {
                   3339: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3340: 	    }
1.886     albertel 3341: 	    if (lc($tagname) eq 'a') {
                   3342: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   3343: 	    }
1.645     raeburn  3344:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3345:                 my $src;
1.645     raeburn  3346:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3347:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3348:                 } else {
1.1164    raeburn  3349:                     if ($attr->{'src'} ne '') {
                   3350:                         $src = $attr->{'src'};
                   3351:                         &add_filetype($allfiles,$src,'src');
                   3352:                     }
                   3353:                 }
                   3354:                 my $text = $p->get_trimmed_text();
                   3355:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3356:                     my @swfargs = split(/,/,$1);
                   3357:                     foreach my $item (@swfargs) {
                   3358:                         $item =~ s/["']//g;
                   3359:                         $item =~ s/^\s+//;
                   3360:                         $item =~ s/\s+$//;
                   3361:                     }
                   3362:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3363:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3364:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3365:                         } else {
                   3366:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3367:                         }
                   3368:                     }
1.645     raeburn  3369:                 }
                   3370:             }
                   3371:             if (lc($tagname) eq 'link') {
                   3372:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3373:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3374:                 }
                   3375:             }
1.640     albertel 3376: 	    if (lc($tagname) eq 'object' ||
                   3377: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3378: 		foreach my $item (keys(%javafiles)) {
                   3379: 		    $javafiles{$item} = '';
                   3380: 		}
1.1164    raeburn  3381:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3382:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3383:                 }
1.640     albertel 3384: 	    }
                   3385: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3386: 		my $name = lc($attr->{'name'});
                   3387: 		foreach my $item (keys(%javafiles)) {
                   3388: 		    if ($name eq $item) {
                   3389: 			$javafiles{$item} = $attr->{'value'};
                   3390: 			last;
                   3391: 		    }
                   3392: 		}
1.1164    raeburn  3393:                 my $pathfrom;
1.640     albertel 3394: 		foreach my $item (keys(%mediafiles)) {
                   3395: 		    if ($name eq $item) {
1.1164    raeburn  3396:                         $pathfrom = $attr->{'value'};
                   3397:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3398: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3399: 			last;
                   3400: 		    }
                   3401: 		}
1.1164    raeburn  3402:                 if ($name eq 'flashvars') {
                   3403:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3404:                 }
                   3405:                 if ($pathfrom ne '') {
                   3406:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3407:                                          $pathfrom);
                   3408:                 }
1.640     albertel 3409: 	    }
                   3410: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3411: 		foreach my $item (keys(%javafiles)) {
                   3412: 		    if ($attr->{$item}) {
                   3413: 			$javafiles{$item} = $attr->{$item};
                   3414: 			last;
                   3415: 		    }
                   3416: 		}
                   3417: 		foreach my $item (keys(%mediafiles)) {
                   3418: 		    if ($attr->{$item}) {
                   3419: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3420: 			last;
                   3421: 		    }
                   3422: 		}
1.1164    raeburn  3423:                 if (lc($tagname) eq 'embed') {
                   3424:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3425:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3426:                                              $attr->{'src'});
                   3427:                     }
                   3428:                 }
1.640     albertel 3429: 	    }
1.1164    raeburn  3430:             if ($t->[4] =~ m{/>$}) {
                   3431:                 pop(@state);  
                   3432:             }
1.640     albertel 3433: 	} elsif ($t->[0] eq 'E') {
                   3434: 	    my ($tagname) = ($t->[1]);
                   3435: 	    if ($javafiles{'codebase'} ne '') {
                   3436: 		$javafiles{'codebase'} .= '/';
                   3437: 	    }  
                   3438: 	    if (lc($tagname) eq 'applet' ||
                   3439: 		lc($tagname) eq 'object' ||
                   3440: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3441: 		) {
                   3442: 		foreach my $item (keys(%javafiles)) {
                   3443: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3444: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3445: 			&add_filetype($allfiles,$file,$item);
                   3446: 		    }
                   3447: 		}
                   3448: 	    } 
                   3449: 	    pop @state;
                   3450: 	}
                   3451:     }
1.1164    raeburn  3452:     foreach my $id (sort(keys(%flashvars))) {
                   3453:         if ($shockwave{$id} ne '') {
                   3454:             my @pairs = split(/\&/,$flashvars{$id});
                   3455:             foreach my $pair (@pairs) {
                   3456:                 my ($key,$value) = split(/\=/,$pair);
                   3457:                 if ($key eq 'thumb') {
                   3458:                     &add_filetype($allfiles,$value,$key);
                   3459:                 } elsif ($key eq 'content') {
                   3460:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3461:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3462:                     if ($ext ne '') {
                   3463:                         &add_filetype($allfiles,$path.$value,$ext);
                   3464:                     }
                   3465:                 }
                   3466:             }
                   3467:         }
                   3468:     }
1.637     raeburn  3469:     return 'ok';
                   3470: }
                   3471: 
1.639     albertel 3472: sub add_filetype {
                   3473:     my ($allfiles,$file,$type)=@_;
                   3474:     if (exists($allfiles->{$file})) {
                   3475: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3476: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3477: 	}
                   3478:     } else {
                   3479: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3480:     }
                   3481: }
                   3482: 
1.1164    raeburn  3483: sub embedded_dependency {
                   3484:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3485:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3486:         if (($identifier ne '') &&
                   3487:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3488:             ($pathfrom ne '')) {
                   3489:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3490:             foreach my $dep (@{$related->{$identifier}}) {
                   3491:                 &add_filetype($allfiles,$path.$dep,'object');
                   3492:             }
                   3493:         }
                   3494:     }
                   3495:     return;
                   3496: }
                   3497: 
1.493     albertel 3498: sub removeuploadedurl {
1.984     neumanie 3499:     my ($url)=@_;	
                   3500:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3501:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3502: }
                   3503: 
                   3504: sub removeuserfile {
                   3505:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3506:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3507:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3508:     if ($result eq 'ok') {	
1.798     raeburn  3509:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3510:             my $metafile = $fname.'.meta';
                   3511:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3512: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3513:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3514:             my $sqlresult = 
1.823     albertel 3515:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3516:                                         'portfolio_metadata',$group,
                   3517:                                         'delete');
1.798     raeburn  3518:         }
                   3519:     }
                   3520:     return $result;
1.257     www      3521: }
1.15      www      3522: 
1.530     albertel 3523: sub mkdiruserfile {
                   3524:     my ($docuname,$docudom,$dir)=@_;
                   3525:     my $home=&homeserver($docuname,$docudom);
                   3526:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3527: }
                   3528: 
1.531     albertel 3529: sub renameuserfile {
                   3530:     my ($docuname,$docudom,$old,$new)=@_;
                   3531:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3532:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3533:                         &escape("$old").':'.&escape("$new"),$home);
                   3534:     if ($result eq 'ok') {
                   3535:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3536:             my $oldmeta = $old.'.meta';
                   3537:             my $newmeta = $new.'.meta';
                   3538:             my $metaresult = 
                   3539:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3540: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3541:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3542:             my $sqlresult = 
1.823     albertel 3543:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3544:                                         'portfolio_metadata',$group,
                   3545:                                         'delete');
1.798     raeburn  3546:         }
                   3547:     }
                   3548:     return $result;
1.531     albertel 3549: }
                   3550: 
1.14      www      3551: # ------------------------------------------------------------------------- Log
                   3552: 
                   3553: sub log {
                   3554:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3555:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3556: }
                   3557: 
                   3558: # ------------------------------------------------------------------ Course Log
1.352     www      3559: #
                   3560: # This routine flushes several buffers of non-mission-critical nature
                   3561: #
1.157     www      3562: 
                   3563: sub flushcourselogs {
1.352     www      3564:     &logthis('Flushing log buffers');
                   3565: #
                   3566: # course logs
                   3567: # This is a log of all transactions in a course, which can be used
                   3568: # for data mining purposes
                   3569: #
                   3570: # It also collects the courseid database, which lists last transaction
                   3571: # times and course titles for all courseids
                   3572: #
                   3573:     my %courseidbuffer=();
1.921     raeburn  3574:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3575:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3576: 		          &escape($courselogs{$crsid}),
                   3577: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3578: 	    delete $courselogs{$crsid};
                   3579:         } else {
                   3580:             &logthis('Failed to flush log buffer for '.$crsid);
                   3581:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3582:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3583:                         " exceeded maximum size, deleting.</font>");
                   3584:                delete $courselogs{$crsid};
                   3585:             }
1.352     www      3586:         }
1.920     raeburn  3587:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3588:             'description' => $coursedescrbuf{$crsid},
                   3589:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3590:             'type'        => $coursetypebuf{$crsid},
                   3591:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3592:         };
1.191     harris41 3593:     }
1.352     www      3594: #
                   3595: # Write course id database (reverse lookup) to homeserver of courses 
                   3596: # Is used in pickcourse
                   3597: #
1.840     albertel 3598:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3599:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3600:                                     $courseidbuffer{$crs_home},
                   3601:                                     $crs_home,'timeonly');
1.352     www      3602:     }
                   3603: #
                   3604: # File accesses
                   3605: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3606: #
1.449     matthew  3607:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3608:         if ($entry =~ /___count$/) {
                   3609:             my ($dom,$name);
1.807     albertel 3610:             ($dom,$name,undef)=
1.811     albertel 3611: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3612:             if (! defined($dom) || $dom eq '' || 
                   3613:                 ! defined($name) || $name eq '') {
1.620     albertel 3614:                 my $cid = $env{'request.course.id'};
                   3615:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3616:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3617:             }
1.450     matthew  3618:             my $value = $accesshash{$entry};
                   3619:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   3620:             my %temphash=($url => $value);
1.449     matthew  3621:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   3622:             if ($result eq 'ok') {
                   3623:                 delete $accesshash{$entry};
                   3624:             }
                   3625:         } else {
1.811     albertel 3626:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      3627:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  3628:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3629:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3630:                 delete $accesshash{$entry};
                   3631:             }
1.185     www      3632:         }
1.191     harris41 3633:     }
1.352     www      3634: #
                   3635: # Roles
                   3636: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   3637: #
1.800     albertel 3638:     foreach my $entry (keys(%userrolehash)) {
1.351     www      3639:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      3640: 	    split(/\:/,$entry);
                   3641:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      3642:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      3643:                 $rudom,$runame) eq 'ok') {
                   3644: 	    delete $userrolehash{$entry};
                   3645:         }
                   3646:     }
1.662     raeburn  3647: #
                   3648: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   3649: #
                   3650:     my %domrolebuffer = ();
1.1000    raeburn  3651:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 3652:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  3653:         if ($domrolebuffer{$rudom}) {
                   3654:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   3655:                       '='.&escape($domainrolehash{$entry});
                   3656:         } else {
                   3657:             $domrolebuffer{$rudom}.=&escape($entry).
                   3658:                       '='.&escape($domainrolehash{$entry});
                   3659:         }
                   3660:         delete $domainrolehash{$entry};
                   3661:     }
                   3662:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 3663: 	my %servers = &get_servers($dom,'library');
                   3664: 	foreach my $tryserver (keys(%servers)) {
                   3665: 	    unless (&reply('domroleput:'.$dom.':'.
                   3666: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   3667: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   3668: 	    }
1.662     raeburn  3669:         }
                   3670:     }
1.186     www      3671:     $dumpcount++;
1.157     www      3672: }
                   3673: 
                   3674: sub courselog {
                   3675:     my $what=shift;
1.158     www      3676:     $what=time.':'.$what;
1.620     albertel 3677:     unless ($env{'request.course.id'}) { return ''; }
                   3678:     $coursedombuf{$env{'request.course.id'}}=
                   3679:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3680:     $coursenumbuf{$env{'request.course.id'}}=
                   3681:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   3682:     $coursehombuf{$env{'request.course.id'}}=
                   3683:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   3684:     $coursedescrbuf{$env{'request.course.id'}}=
                   3685:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   3686:     $courseinstcodebuf{$env{'request.course.id'}}=
                   3687:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   3688:     $courseownerbuf{$env{'request.course.id'}}=
                   3689:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  3690:     $coursetypebuf{$env{'request.course.id'}}=
                   3691:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 3692:     if (defined $courselogs{$env{'request.course.id'}}) {
                   3693: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      3694:     } else {
1.620     albertel 3695: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      3696:     }
1.620     albertel 3697:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      3698: 	&flushcourselogs();
                   3699:     }
1.158     www      3700: }
                   3701: 
                   3702: sub courseacclog {
                   3703:     my $fnsymb=shift;
1.620     albertel 3704:     unless ($env{'request.course.id'}) { return ''; }
                   3705:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      3706:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      3707:         $what.=':POST';
1.583     matthew  3708:         # FIXME: Probably ought to escape things....
1.800     albertel 3709: 	foreach my $key (keys(%env)) {
                   3710:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  3711:                 my $formitem = $1;
                   3712:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   3713:                     $what.=':'.$formitem.'='.$env{$key};
                   3714:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   3715:                     $what.=':'.$formitem.'='.$env{$key};
                   3716:                 }
1.158     www      3717:             }
1.191     harris41 3718:         }
1.583     matthew  3719:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   3720:         # FIXME: We should not be depending on a form parameter that someone
                   3721:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 3722:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  3723:             $what.= ':POST';
                   3724:             # FIXME: Probably ought to escape things....
                   3725:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   3726:                                  'crsdiscuss') {
1.620     albertel 3727:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  3728:             }
                   3729:         }
1.158     www      3730:     }
                   3731:     &courselog($what);
1.149     www      3732: }
                   3733: 
1.185     www      3734: sub countacc {
                   3735:     my $url=&declutter(shift);
1.458     matthew  3736:     return if (! defined($url) || $url eq '');
1.620     albertel 3737:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      3738: #
                   3739: # Mark that this url was used in this course
                   3740: #
1.620     albertel 3741:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      3742: #
                   3743: # Increase the access count for this resource in this child process
                   3744: #
1.281     www      3745:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  3746:     $accesshash{$key}++;
1.185     www      3747: }
1.349     www      3748: 
1.361     www      3749: sub linklog {
                   3750:     my ($from,$to)=@_;
                   3751:     $from=&declutter($from);
                   3752:     $to=&declutter($to);
                   3753:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   3754:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   3755: }
1.1160    www      3756: 
                   3757: sub statslog {
                   3758:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   3759:     if ($users<2) { return; }
                   3760:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   3761:             'course'       => $env{'request.course.id'},
                   3762:             'sections'     => '"all"',
                   3763:             'num_students' => $users,
                   3764:             'part'         => $part,
                   3765:             'symb'         => $symb,
                   3766:             'mean_tries'   => $av_attempts,
                   3767:             'deg_of_diff'  => $degdiff});
                   3768:     foreach my $key (keys(%dynstore)) {
                   3769:         $accesshash{$key}=$dynstore{$key};
                   3770:     }
                   3771: }
1.361     www      3772:   
1.349     www      3773: sub userrolelog {
                   3774:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 3775:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      3776:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3777:        $userrolehash
                   3778:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      3779:                     =$tend.':'.$tstart;
1.662     raeburn  3780:     }
1.1169    droeschl 3781:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 3782:        $userrolehash
                   3783:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   3784:                     =$tend.':'.$tstart;
                   3785:     }
1.1169    droeschl 3786:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662     raeburn  3787:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3788:        $domainrolehash
                   3789:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3790:                     = $tend.':'.$tstart;
                   3791:     }
1.351     www      3792: }
                   3793: 
1.957     raeburn  3794: sub courserolelog {
                   3795:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  3796:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3797:         my $cdom = $1;
                   3798:         my $cnum = $2;
                   3799:         my $sec = $3;
                   3800:         my $namespace = 'rolelog';
                   3801:         my %storehash = (
                   3802:                            role    => $trole,
                   3803:                            start   => $tstart,
                   3804:                            end     => $tend,
                   3805:                            selfenroll => $selfenroll,
                   3806:                            context    => $context,
                   3807:                         );
                   3808:         if ($trole eq 'gr') {
                   3809:             $namespace = 'groupslog';
                   3810:             $storehash{'group'} = $sec;
                   3811:         } else {
                   3812:             $storehash{'section'} = $sec;
                   3813:         }
                   3814:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   3815:                    $domain,$cnum,$cdom);
                   3816:         if (($trole ne 'st') || ($sec ne '')) {
                   3817:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  3818:         }
                   3819:     }
                   3820:     return;
                   3821: }
                   3822: 
1.1172.2.9  raeburn  3823: sub domainrolelog {
                   3824:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   3825:     if ($area =~ m{^/($match_domain)/$}) {
                   3826:         my $cdom = $1;
                   3827:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   3828:         my $namespace = 'rolelog';
                   3829:         my %storehash = (
                   3830:                            role    => $trole,
                   3831:                            start   => $tstart,
                   3832:                            end     => $tend,
                   3833:                            context => $context,
                   3834:                         );
                   3835:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   3836:                    $domain,$domconfiguser,$cdom);
                   3837:     }
                   3838:     return;
                   3839: 
                   3840: }
                   3841: 
                   3842: sub coauthorrolelog {
                   3843:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   3844:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   3845:         my $audom = $1;
                   3846:         my $auname = $2;
                   3847:         my $namespace = 'rolelog';
                   3848:         my %storehash = (
                   3849:                            role    => $trole,
                   3850:                            start   => $tstart,
                   3851:                            end     => $tend,
                   3852:                            context => $context,
                   3853:                         );
                   3854:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   3855:                    $domain,$auname,$audom);
                   3856:     }
                   3857:     return;
                   3858: }
                   3859: 
1.351     www      3860: sub get_course_adv_roles {
1.948     raeburn  3861:     my ($cid,$codes) = @_;
1.620     albertel 3862:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      3863:     my %coursehash=&coursedescription($cid);
1.988     raeburn  3864:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      3865:     my %nothide=();
1.800     albertel 3866:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  3867:         if ($user !~ /:/) {
                   3868: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   3869:         } else {
                   3870:             $nothide{$user}=1;
                   3871:         }
1.470     www      3872:     }
1.351     www      3873:     my %returnhash=();
                   3874:     my %dumphash=
                   3875:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   3876:     my $now=time;
1.997     raeburn  3877:     my %privileged;
1.1000    raeburn  3878:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 3879: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      3880:         if (($tstart) && ($tstart<0)) { next; }
                   3881:         if (($tend) && ($tend<$now)) { next; }
                   3882:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 3883:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 3884: 	if ($username eq '' || $domain eq '') { next; }
1.997     raeburn  3885:         unless (ref($privileged{$domain}) eq 'HASH') {
                   3886:             my %dompersonnel =
1.998     raeburn  3887:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997     raeburn  3888:             $privileged{$domain} = {};
                   3889:             foreach my $server (keys(%dompersonnel)) {
1.999     raeburn  3890:                 if (ref($dompersonnel{$server}) eq 'HASH') {
1.997     raeburn  3891:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3892:                         my ($trole,$uname,$udom) = split(/:/,$user);
                   3893:                         $privileged{$udom}{$uname} = 1;
                   3894:                     }
                   3895:                 }
                   3896:             }
                   3897:         }
                   3898:         if ((exists($privileged{$domain}{$username})) && 
                   3899:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 3900: 	if ($role eq 'cr') { next; }
1.948     raeburn  3901:         if ($codes) {
                   3902:             if ($section) { $role .= ':'.$section; }
                   3903:             if ($returnhash{$role}) {
                   3904:                 $returnhash{$role}.=','.$username.':'.$domain;
                   3905:             } else {
                   3906:                 $returnhash{$role}=$username.':'.$domain;
                   3907:             }
1.351     www      3908:         } else {
1.988     raeburn  3909:             my $key=&plaintext($role,$crstype);
1.973     bisitz   3910:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  3911:             if ($returnhash{$key}) {
                   3912: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   3913:             } else {
                   3914:                 $returnhash{$key}=$username.':'.$domain;
                   3915:             }
1.351     www      3916:         }
1.948     raeburn  3917:     }
1.400     www      3918:     return %returnhash;
                   3919: }
                   3920: 
                   3921: sub get_my_roles {
1.937     raeburn  3922:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 3923:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   3924:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  3925:     my (%dumphash,%nothide);
1.1086    raeburn  3926:     if ($context eq 'userroles') {
1.1166    raeburn  3927:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  3928:     } else {
                   3929:         %dumphash=
1.400     www      3930:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  3931:         if ($hidepriv) {
                   3932:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   3933:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3934:                 if ($user !~ /:/) {
                   3935:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   3936:                 } else {
                   3937:                     $nothide{$user} = 1;
                   3938:                 }
                   3939:             }
                   3940:         }
1.858     raeburn  3941:     }
1.400     www      3942:     my %returnhash=();
                   3943:     my $now=time;
1.999     raeburn  3944:     my %privileged;
1.800     albertel 3945:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  3946:         my ($role,$tend,$tstart);
                   3947:         if ($context eq 'userroles') {
1.1149    raeburn  3948:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  3949: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   3950:         } else {
                   3951:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   3952:         }
1.400     www      3953:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  3954:         my $status = 'active';
1.939     raeburn  3955:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  3956:             $status = 'previous';
                   3957:         } 
                   3958:         if (($tstart) && ($now<$tstart)) {
                   3959:             $status = 'future';
                   3960:         }
                   3961:         if (ref($types) eq 'ARRAY') {
                   3962:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   3963:                 next;
                   3964:             } 
                   3965:         } else {
                   3966:             if ($status ne 'active') {
                   3967:                 next;
                   3968:             }
                   3969:         }
1.867     raeburn  3970:         my ($rolecode,$username,$domain,$section,$area);
                   3971:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  3972:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  3973:             (undef,$domain,$username,$section) = split(/\//,$area);
                   3974:         } else {
                   3975:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   3976:         }
1.832     raeburn  3977:         if (ref($roledoms) eq 'ARRAY') {
                   3978:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   3979:                 next;
                   3980:             }
                   3981:         }
                   3982:         if (ref($roles) eq 'ARRAY') {
                   3983:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  3984:                 if ($role =~ /^cr\//) {
                   3985:                     if (!grep(/^cr$/,@{$roles})) {
                   3986:                         next;
                   3987:                     }
1.1104    raeburn  3988:                 } elsif ($role =~ /^gr\//) {
                   3989:                     if (!grep(/^gr$/,@{$roles})) {
                   3990:                         next;
                   3991:                     }
1.922     raeburn  3992:                 } else {
                   3993:                     next;
                   3994:                 }
1.832     raeburn  3995:             }
1.867     raeburn  3996:         }
1.937     raeburn  3997:         if ($hidepriv) {
1.999     raeburn  3998:             if ($context eq 'userroles') {
                   3999:                 if ((&privileged($username,$domain)) &&
                   4000:                     (!$nothide{$username.':'.$domain})) {
                   4001:                     next;
                   4002:                 }
                   4003:             } else {
                   4004:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   4005:                     my %dompersonnel =
                   4006:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   4007:                     $privileged{$domain} = {};
                   4008:                     if (keys(%dompersonnel)) {
                   4009:                         foreach my $server (keys(%dompersonnel)) {
                   4010:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   4011:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   4012:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   4013:                                     $privileged{$udom}{$uname} = $trole;
                   4014:                                 }
                   4015:                             }
                   4016:                         }
                   4017:                     }
                   4018:                 }
                   4019:                 if (exists($privileged{$domain}{$username})) {
                   4020:                     if (!$nothide{$username.':'.$domain}) {
                   4021:                         next;
                   4022:                     }
                   4023:                 }
1.937     raeburn  4024:             }
                   4025:         }
1.933     raeburn  4026:         if ($withsec) {
                   4027:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4028:                 $tstart.':'.$tend;
                   4029:         } else {
                   4030:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4031:         }
1.832     raeburn  4032:     }
1.373     www      4033:     return %returnhash;
1.399     www      4034: }
                   4035: 
                   4036: # ----------------------------------------------------- Frontpage Announcements
                   4037: #
                   4038: #
                   4039: 
                   4040: sub postannounce {
                   4041:     my ($server,$text)=@_;
1.844     albertel 4042:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4043:     unless ($text=~/\w/) { $text=''; }
                   4044:     return &reply('setannounce:'.&escape($text),$server);
                   4045: }
                   4046: 
                   4047: sub getannounce {
1.448     albertel 4048: 
                   4049:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4050: 	my $announcement='';
1.800     albertel 4051: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4052: 	close($fh);
1.399     www      4053: 	if ($announcement=~/\w/) { 
                   4054: 	    return 
                   4055:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4056:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4057: 	} else {
                   4058: 	    return '';
                   4059: 	}
                   4060:     } else {
                   4061: 	return '';
                   4062:     }
1.351     www      4063: }
1.353     www      4064: 
                   4065: # ---------------------------------------------------------- Course ID routines
                   4066: # Deal with domain's nohist_courseid.db files
                   4067: #
                   4068: 
                   4069: sub courseidput {
1.921     raeburn  4070:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4071:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4072:     my $outcome;
                   4073:     if ($caller eq 'timeonly') {
                   4074:         my $cids = '';
                   4075:         foreach my $item (keys(%$storehash)) {
                   4076:             $cids.=&escape($item).'&';
                   4077:         }
                   4078:         $cids=~s/\&$//;
                   4079:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4080:                           $coursehome);       
                   4081:     } else {
                   4082:         my $items = '';
                   4083:         foreach my $item (keys(%$storehash)) {
                   4084:             $items.= &escape($item).'='.
                   4085:                      &freeze_escape($$storehash{$item}).'&';
                   4086:         }
                   4087:         $items=~s/\&$//;
                   4088:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4089:                           $coursehome);
1.918     raeburn  4090:     }
                   4091:     if ($outcome eq 'unknown_cmd') {
                   4092:         my $what;
                   4093:         foreach my $cid (keys(%$storehash)) {
                   4094:             $what .= &escape($cid).'=';
1.921     raeburn  4095:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4096:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4097:             }
                   4098:             $what =~ s/\:$/&/;
                   4099:         }
                   4100:         $what =~ s/\&$//;  
                   4101:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4102:     } else {
                   4103:         return $outcome;
                   4104:     }
1.353     www      4105: }
                   4106: 
                   4107: sub courseiddump {
1.921     raeburn  4108:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4109:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4110:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071    raeburn  4111:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  4112:     my $as_hash = 1;
                   4113:     my %returnhash;
                   4114:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4115:     my %libserv = &all_library();
                   4116:     foreach my $tryserver (keys(%libserv)) {
                   4117:         if ( (  $hostidflag == 1 
                   4118: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4119: 	     || (!defined($hostidflag)) ) {
                   4120: 
1.918     raeburn  4121: 	    if (($domfilter eq '') ||
                   4122: 		(&host_domain($tryserver) eq $domfilter)) {
                   4123:                 my $rep = 
                   4124:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4125:                          $sincefilter.':'.&escape($descfilter).':'.
                   4126:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   4127:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  4128:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  4129:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008    raeburn  4130:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029    raeburn  4131:                          &escape($cc_clone).':'.$cloneonly.':'.
                   4132:                          &escape($createdbefore).':'.&escape($createdafter).':'.
1.1071    raeburn  4133:                          &escape($creationcontext).':'.$domcloner,
                   4134:                          $tryserver);
1.918     raeburn  4135:                 my @pairs=split(/\&/,$rep);
                   4136:                 foreach my $item (@pairs) {
                   4137:                     my ($key,$value)=split(/\=/,$item,2);
                   4138:                     $key = &unescape($key);
                   4139:                     next if ($key =~ /^error: 2 /);
                   4140:                     my $result = &thaw_unescape($value);
                   4141:                     if (ref($result) eq 'HASH') {
                   4142:                         $returnhash{$key}=$result;
                   4143:                     } else {
1.921     raeburn  4144:                         my @responses = split(/:/,$value);
                   4145:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4146:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4147:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4148:                         }
1.1008    raeburn  4149:                     }
1.353     www      4150:                 }
                   4151:             }
                   4152:         }
                   4153:     }
                   4154:     return %returnhash;
                   4155: }
                   4156: 
1.1055    raeburn  4157: sub courselastaccess {
                   4158:     my ($cdom,$cnum,$hostidref) = @_;
                   4159:     my %returnhash;
                   4160:     if ($cdom && $cnum) {
                   4161:         my $chome = &homeserver($cnum,$cdom);
                   4162:         if ($chome ne 'no_host') {
                   4163:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4164:             &extract_lastaccess(\%returnhash,$rep);
                   4165:         }
                   4166:     } else {
                   4167:         if (!$cdom) { $cdom=''; }
                   4168:         my %libserv = &all_library();
                   4169:         foreach my $tryserver (keys(%libserv)) {
                   4170:             if (ref($hostidref) eq 'ARRAY') {
                   4171:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4172:             } 
                   4173:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4174:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4175:                 &extract_lastaccess(\%returnhash,$rep);
                   4176:             }
                   4177:         }
                   4178:     }
                   4179:     return %returnhash;
                   4180: }
                   4181: 
                   4182: sub extract_lastaccess {
                   4183:     my ($returnhash,$rep) = @_;
                   4184:     if (ref($returnhash) eq 'HASH') {
                   4185:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4186:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4187:                  $rep eq '') {
                   4188:             my @pairs=split(/\&/,$rep);
                   4189:             foreach my $item (@pairs) {
                   4190:                 my ($key,$value)=split(/\=/,$item,2);
                   4191:                 $key = &unescape($key);
                   4192:                 next if ($key =~ /^error: 2 /);
                   4193:                 $returnhash->{$key} = &thaw_unescape($value);
                   4194:             }
                   4195:         }
                   4196:     }
                   4197:     return;
                   4198: }
                   4199: 
1.658     raeburn  4200: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4201: 
                   4202: sub dcmailput {
1.685     raeburn  4203:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4204:     my $status = &Apache::lonnet::critical(
1.740     www      4205:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4206:        &escape($message),$server);
1.662     raeburn  4207:     return $status;
                   4208: }
                   4209: 
1.658     raeburn  4210: sub dcmaildump {
                   4211:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4212:     my %returnhash=();
1.846     albertel 4213: 
                   4214:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4215:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4216:                                                          &escape($enddate).':';
                   4217: 	my @esc_senders=map { &escape($_)} @$senders;
                   4218: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4219: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4220:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4221:             if (($key) && ($value)) {
                   4222:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4223:             }
                   4224:         }
                   4225:     }
                   4226:     return %returnhash;
                   4227: }
1.662     raeburn  4228: # ---------------------------------------------------------- Domain roles
                   4229: 
                   4230: sub get_domain_roles {
                   4231:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4232:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4233:         $startdate = '.';
                   4234:     }
1.1018    raeburn  4235:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4236:         $enddate = '.';
                   4237:     }
1.922     raeburn  4238:     my $rolelist;
                   4239:     if (ref($roles) eq 'ARRAY') {
                   4240:         $rolelist = join(':',@{$roles});
                   4241:     }
1.662     raeburn  4242:     my %personnel = ();
1.841     albertel 4243: 
                   4244:     my %servers = &get_servers($dom,'library');
                   4245:     foreach my $tryserver (keys(%servers)) {
                   4246: 	%{$personnel{$tryserver}}=();
                   4247: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4248: 					    &escape($startdate).':'.
                   4249: 					    &escape($enddate).':'.
                   4250: 					    &escape($rolelist), $tryserver))) {
                   4251: 	    my ($key,$value) = split(/\=/,$line,2);
                   4252: 	    if (($key) && ($value)) {
                   4253: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4254: 	    }
                   4255: 	}
1.662     raeburn  4256:     }
                   4257:     return %personnel;
                   4258: }
1.658     raeburn  4259: 
1.1057    www      4260: # ----------------------------------------------------------- Interval timing 
1.149     www      4261: 
1.1153    www      4262: {
                   4263: # Caches needed for speedup of navmaps
                   4264: # We don't want to cache this for very long at all (5 seconds at most)
                   4265: # 
                   4266: # The user for whom we cache
                   4267: my $cachedkey='';
                   4268: # The cached times for this user
                   4269: my %cachedtimes=();
                   4270: # When this was last done
                   4271: my $cachedtime=();
                   4272: 
                   4273: sub load_all_first_access {
1.1154    raeburn  4274:     my ($uname,$udom)=@_;
1.1156    www      4275:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2  raeburn  4276:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  4277:         return;
                   4278:     }
                   4279:     $cachedtime=time;
                   4280:     $cachedkey=$uname.':'.$udom;
                   4281:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4282: }
                   4283: 
1.504     albertel 4284: sub get_first_access {
1.1162    raeburn  4285:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 4286:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4287:     if ($argsymb) { $symb=$argsymb; }
                   4288:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4289:     if ($argmap) { $map = $argmap; }
1.926     albertel 4290:     if ($type eq 'course') {
                   4291: 	$res='course';
                   4292:     } elsif ($type eq 'map') {
1.588     albertel 4293: 	$res=&symbread($map);
                   4294:     } else {
                   4295: 	$res=$symb;
                   4296:     }
1.1153    www      4297:     &load_all_first_access($uname,$udom);
                   4298:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4299: }
                   4300: 
                   4301: sub set_first_access {
1.1162    raeburn  4302:     my ($type,$interval)=@_;
1.790     albertel 4303:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4304:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4305:     if ($type eq 'course') {
                   4306: 	$res='course';
                   4307:     } elsif ($type eq 'map') {
1.588     albertel 4308: 	$res=&symbread($map);
                   4309:     } else {
                   4310: 	$res=$symb;
                   4311:     }
1.1153    www      4312:     $cachedkey='';
1.1162    raeburn  4313:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4314:     if (!$firstaccess) {
1.1162    raeburn  4315:         my $start = time;
                   4316: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4317:                           $udom,$uname);
                   4318:         if ($putres eq 'ok') {
                   4319:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4320:                  $udom,$uname); 
                   4321:             &appenv(
                   4322:                      {
                   4323:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4324:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4325:                      }
                   4326:                   );
                   4327:         }
                   4328:         return $putres;
1.505     albertel 4329:     }
                   4330:     return 'already_set';
1.504     albertel 4331: }
1.1153    www      4332: }
1.110     www      4333: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4334: 
                   4335: sub expirespread {
                   4336:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4337:     my $cid=$env{'request.course.id'}; 
1.110     www      4338:     if ($cid) {
                   4339:        my $now=time;
                   4340:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4341:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4342:                             $env{'course.'.$cid.'.num'}.
1.110     www      4343: 	        	    ':nohist_expirationdates:'.
                   4344:                             &escape($key).'='.$now,
1.620     albertel 4345:                             $env{'course.'.$cid.'.home'})
1.110     www      4346:     }
                   4347:     return 'ok';
1.14      www      4348: }
                   4349: 
1.109     www      4350: # ----------------------------------------------------- Devalidate Spreadsheets
                   4351: 
                   4352: sub devalidate {
1.325     www      4353:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4354:     my $cid=$env{'request.course.id'}; 
1.109     www      4355:     if ($cid) {
1.391     matthew  4356:         # delete the stored spreadsheets for
                   4357:         # - the student level sheet of this user in course's homespace
                   4358:         # - the assessment level sheet for this resource 
                   4359:         #   for this user in user's homespace
1.553     albertel 4360: 	# - current conditional state info
1.325     www      4361: 	my $key=$uname.':'.$udom.':';
1.109     www      4362:         my $status=
1.299     matthew  4363: 	    &del('nohist_calculatedsheets',
1.391     matthew  4364: 		 [$key.'studentcalc:'],
1.620     albertel 4365: 		 $env{'course.'.$cid.'.domain'},
                   4366: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4367: 		.' '.
                   4368: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4369: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4370:         unless ($status eq 'ok ok') {
                   4371:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4372:                     $uname.' at '.$udom.' for '.
1.109     www      4373: 		    $symb.': '.$status);
1.133     albertel 4374:         }
1.553     albertel 4375: 	&delenv('user.state.'.$cid);
1.109     www      4376:     }
                   4377: }
                   4378: 
1.265     albertel 4379: sub get_scalar {
                   4380:     my ($string,$end) = @_;
                   4381:     my $value;
                   4382:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4383: 	$value = $1;
                   4384:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4385: 	$value = $1;
                   4386:     }
                   4387:     return &unescape($value);
                   4388: }
                   4389: 
                   4390: sub array2str {
                   4391:   my (@array) = @_;
                   4392:   my $result=&arrayref2str(\@array);
                   4393:   $result=~s/^__ARRAY_REF__//;
                   4394:   $result=~s/__END_ARRAY_REF__$//;
                   4395:   return $result;
                   4396: }
                   4397: 
1.204     albertel 4398: sub arrayref2str {
                   4399:   my ($arrayref) = @_;
1.265     albertel 4400:   my $result='__ARRAY_REF__';
1.204     albertel 4401:   foreach my $elem (@$arrayref) {
1.265     albertel 4402:     if(ref($elem) eq 'ARRAY') {
                   4403:       $result.=&arrayref2str($elem).'&';
                   4404:     } elsif(ref($elem) eq 'HASH') {
                   4405:       $result.=&hashref2str($elem).'&';
                   4406:     } elsif(ref($elem)) {
                   4407:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4408:     } else {
                   4409:       $result.=&escape($elem).'&';
                   4410:     }
                   4411:   }
                   4412:   $result=~s/\&$//;
1.265     albertel 4413:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4414:   return $result;
                   4415: }
                   4416: 
1.168     albertel 4417: sub hash2str {
1.204     albertel 4418:   my (%hash) = @_;
                   4419:   my $result=&hashref2str(\%hash);
1.265     albertel 4420:   $result=~s/^__HASH_REF__//;
                   4421:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4422:   return $result;
                   4423: }
                   4424: 
                   4425: sub hashref2str {
                   4426:   my ($hashref)=@_;
1.265     albertel 4427:   my $result='__HASH_REF__';
1.800     albertel 4428:   foreach my $key (sort(keys(%$hashref))) {
                   4429:     if (ref($key) eq 'ARRAY') {
                   4430:       $result.=&arrayref2str($key).'=';
                   4431:     } elsif (ref($key) eq 'HASH') {
                   4432:       $result.=&hashref2str($key).'=';
                   4433:     } elsif (ref($key)) {
1.265     albertel 4434:       $result.='=';
1.800     albertel 4435:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 4436:     } else {
1.1132    raeburn  4437: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 4438:     }
                   4439: 
1.800     albertel 4440:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   4441:       $result.=&arrayref2str($hashref->{$key}).'&';
                   4442:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   4443:       $result.=&hashref2str($hashref->{$key}).'&';
                   4444:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4445:        $result.='&';
1.800     albertel 4446:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4447:     } else {
1.800     albertel 4448:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4449:     }
                   4450:   }
1.168     albertel 4451:   $result=~s/\&$//;
1.265     albertel 4452:   $result .= '__END_HASH_REF__';
1.168     albertel 4453:   return $result;
                   4454: }
                   4455: 
                   4456: sub str2hash {
1.265     albertel 4457:     my ($string)=@_;
                   4458:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4459:     return %$hash;
                   4460: }
                   4461: 
                   4462: sub str2hashref {
1.168     albertel 4463:   my ($string) = @_;
1.265     albertel 4464: 
                   4465:   my %hash;
                   4466: 
                   4467:   if($string !~ /^__HASH_REF__/) {
                   4468:       if (! ($string eq '' || !defined($string))) {
                   4469: 	  $hash{'error'}='Not hash reference';
                   4470:       }
                   4471:       return (\%hash, $string);
                   4472:   }
                   4473: 
                   4474:   $string =~ s/^__HASH_REF__//;
                   4475: 
                   4476:   while($string !~ /^__END_HASH_REF__/) {
                   4477:       #key
                   4478:       my $key='';
                   4479:       if($string =~ /^__HASH_REF__/) {
                   4480:           ($key, $string)=&str2hashref($string);
                   4481:           if(defined($key->{'error'})) {
                   4482:               $hash{'error'}='Bad data';
                   4483:               return (\%hash, $string);
                   4484:           }
                   4485:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4486:           ($key, $string)=&str2arrayref($string);
                   4487:           if($key->[0] eq 'Array reference error') {
                   4488:               $hash{'error'}='Bad data';
                   4489:               return (\%hash, $string);
                   4490:           }
                   4491:       } else {
                   4492:           $string =~ s/^(.*?)=//;
1.267     albertel 4493: 	  $key=&unescape($1);
1.265     albertel 4494:       }
                   4495:       $string =~ s/^=//;
                   4496: 
                   4497:       #value
                   4498:       my $value='';
                   4499:       if($string =~ /^__HASH_REF__/) {
                   4500:           ($value, $string)=&str2hashref($string);
                   4501:           if(defined($value->{'error'})) {
                   4502:               $hash{'error'}='Bad data';
                   4503:               return (\%hash, $string);
                   4504:           }
                   4505:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4506:           ($value, $string)=&str2arrayref($string);
                   4507:           if($value->[0] eq 'Array reference error') {
                   4508:               $hash{'error'}='Bad data';
                   4509:               return (\%hash, $string);
                   4510:           }
                   4511:       } else {
                   4512: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4513:       }
                   4514:       $string =~ s/^&//;
                   4515: 
                   4516:       $hash{$key}=$value;
1.204     albertel 4517:   }
1.265     albertel 4518: 
                   4519:   $string =~ s/^__END_HASH_REF__//;
                   4520: 
                   4521:   return (\%hash, $string);
1.204     albertel 4522: }
                   4523: 
                   4524: sub str2array {
1.265     albertel 4525:     my ($string)=@_;
                   4526:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4527:     return @$array;
                   4528: }
                   4529: 
                   4530: sub str2arrayref {
1.204     albertel 4531:   my ($string) = @_;
1.265     albertel 4532:   my @array;
                   4533: 
                   4534:   if($string !~ /^__ARRAY_REF__/) {
                   4535:       if (! ($string eq '' || !defined($string))) {
                   4536: 	  $array[0]='Array reference error';
                   4537:       }
                   4538:       return (\@array, $string);
                   4539:   }
                   4540: 
                   4541:   $string =~ s/^__ARRAY_REF__//;
                   4542: 
                   4543:   while($string !~ /^__END_ARRAY_REF__/) {
                   4544:       my $value='';
                   4545:       if($string =~ /^__HASH_REF__/) {
                   4546:           ($value, $string)=&str2hashref($string);
                   4547:           if(defined($value->{'error'})) {
                   4548:               $array[0] ='Array reference error';
                   4549:               return (\@array, $string);
                   4550:           }
                   4551:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4552:           ($value, $string)=&str2arrayref($string);
                   4553:           if($value->[0] eq 'Array reference error') {
                   4554:               $array[0] ='Array reference error';
                   4555:               return (\@array, $string);
                   4556:           }
                   4557:       } else {
                   4558: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   4559:       }
                   4560:       $string =~ s/^&//;
                   4561: 
                   4562:       push(@array, $value);
1.191     harris41 4563:   }
1.265     albertel 4564: 
                   4565:   $string =~ s/^__END_ARRAY_REF__//;
                   4566: 
                   4567:   return (\@array, $string);
1.168     albertel 4568: }
                   4569: 
1.167     albertel 4570: # -------------------------------------------------------------------Temp Store
                   4571: 
1.168     albertel 4572: sub tmpreset {
                   4573:   my ($symb,$namespace,$domain,$stuname) = @_;
                   4574:   if (!$symb) {
                   4575:     $symb=&symbread();
1.620     albertel 4576:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4577:   }
                   4578:   $symb=escape($symb);
                   4579: 
1.620     albertel 4580:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 4581:   $namespace=~s/\//\_/g;
                   4582:   $namespace=~s/\W//g;
                   4583: 
1.620     albertel 4584:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4585:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4586:   if ($domain eq 'public' && $stuname eq 'public') {
                   4587:       $stuname=$ENV{'REMOTE_ADDR'};
                   4588:   }
1.1117    foxr     4589:   my $path=LONCAPA::tempdir();
1.168     albertel 4590:   my %hash;
                   4591:   if (tie(%hash,'GDBM_File',
                   4592: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4593: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  4594:     foreach my $key (keys(%hash)) {
1.180     albertel 4595:       if ($key=~ /:$symb/) {
1.168     albertel 4596: 	delete($hash{$key});
                   4597:       }
                   4598:     }
                   4599:   }
                   4600: }
                   4601: 
1.167     albertel 4602: sub tmpstore {
1.168     albertel 4603:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4604: 
                   4605:   if (!$symb) {
                   4606:     $symb=&symbread();
1.620     albertel 4607:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4608:   }
                   4609:   $symb=escape($symb);
                   4610: 
                   4611:   if (!$namespace) {
                   4612:     # I don't think we would ever want to store this for a course.
                   4613:     # it seems this will only be used if we don't have a course.
1.620     albertel 4614:     #$namespace=$env{'request.course.id'};
1.168     albertel 4615:     #if (!$namespace) {
1.620     albertel 4616:       $namespace=$env{'request.state'};
1.168     albertel 4617:     #}
                   4618:   }
                   4619:   $namespace=~s/\//\_/g;
                   4620:   $namespace=~s/\W//g;
1.620     albertel 4621:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4622:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4623:   if ($domain eq 'public' && $stuname eq 'public') {
                   4624:       $stuname=$ENV{'REMOTE_ADDR'};
                   4625:   }
1.168     albertel 4626:   my $now=time;
                   4627:   my %hash;
1.1117    foxr     4628:   my $path=LONCAPA::tempdir();
1.168     albertel 4629:   if (tie(%hash,'GDBM_File',
                   4630: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4631: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 4632:     $hash{"version:$symb"}++;
                   4633:     my $version=$hash{"version:$symb"};
                   4634:     my $allkeys=''; 
                   4635:     foreach my $key (keys(%$storehash)) {
                   4636:       $allkeys.=$key.':';
1.591     albertel 4637:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 4638:     }
                   4639:     $hash{"$version:$symb:timestamp"}=$now;
                   4640:     $allkeys.='timestamp';
                   4641:     $hash{"$version:keys:$symb"}=$allkeys;
                   4642:     if (untie(%hash)) {
                   4643:       return 'ok';
                   4644:     } else {
                   4645:       return "error:$!";
                   4646:     }
                   4647:   } else {
                   4648:     return "error:$!";
                   4649:   }
                   4650: }
1.167     albertel 4651: 
1.168     albertel 4652: # -----------------------------------------------------------------Temp Restore
1.167     albertel 4653: 
1.168     albertel 4654: sub tmprestore {
                   4655:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 4656: 
1.168     albertel 4657:   if (!$symb) {
                   4658:     $symb=&symbread();
1.620     albertel 4659:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4660:   }
                   4661:   $symb=escape($symb);
                   4662: 
1.620     albertel 4663:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 4664: 
1.620     albertel 4665:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4666:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4667:   if ($domain eq 'public' && $stuname eq 'public') {
                   4668:       $stuname=$ENV{'REMOTE_ADDR'};
                   4669:   }
1.168     albertel 4670:   my %returnhash;
                   4671:   $namespace=~s/\//\_/g;
                   4672:   $namespace=~s/\W//g;
                   4673:   my %hash;
1.1117    foxr     4674:   my $path=LONCAPA::tempdir();
1.168     albertel 4675:   if (tie(%hash,'GDBM_File',
                   4676: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4677: 	  &GDBM_READER(),0640)) {
1.168     albertel 4678:     my $version=$hash{"version:$symb"};
                   4679:     $returnhash{'version'}=$version;
                   4680:     my $scope;
                   4681:     for ($scope=1;$scope<=$version;$scope++) {
                   4682:       my $vkeys=$hash{"$scope:keys:$symb"};
                   4683:       my @keys=split(/:/,$vkeys);
                   4684:       my $key;
                   4685:       $returnhash{"$scope:keys"}=$vkeys;
                   4686:       foreach $key (@keys) {
1.591     albertel 4687: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   4688: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 4689:       }
                   4690:     }
1.168     albertel 4691:     if (!(untie(%hash))) {
                   4692:       return "error:$!";
                   4693:     }
                   4694:   } else {
                   4695:     return "error:$!";
                   4696:   }
                   4697:   return %returnhash;
1.167     albertel 4698: }
                   4699: 
1.9       www      4700: # ----------------------------------------------------------------------- Store
                   4701: 
                   4702: sub store {
1.124     www      4703:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4704:     my $home='';
                   4705: 
1.168     albertel 4706:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4707: 
1.213     www      4708:     $symb=&symbclean($symb);
1.122     albertel 4709:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4710: 
1.620     albertel 4711:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4712:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4713: 
                   4714:     &devalidate($symb,$stuname,$domain);
1.109     www      4715: 
                   4716:     $symb=escape($symb);
1.187     www      4717:     if (!$namespace) { 
1.620     albertel 4718:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4719:           return ''; 
                   4720:        } 
                   4721:     }
1.620     albertel 4722:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4723: 
                   4724:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4725:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   4726: 
1.12      www      4727:     my $namevalue='';
1.800     albertel 4728:     foreach my $key (keys(%$storehash)) {
                   4729:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4730:     }
1.12      www      4731:     $namevalue=~s/\&$//;
1.187     www      4732:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      4733:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      4734: }
                   4735: 
1.47      www      4736: # -------------------------------------------------------------- Critical Store
                   4737: 
                   4738: sub cstore {
1.124     www      4739:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4740:     my $home='';
                   4741: 
1.168     albertel 4742:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4743: 
1.213     www      4744:     $symb=&symbclean($symb);
1.122     albertel 4745:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4746: 
1.620     albertel 4747:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4748:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4749: 
                   4750:     &devalidate($symb,$stuname,$domain);
1.109     www      4751: 
                   4752:     $symb=escape($symb);
1.187     www      4753:     if (!$namespace) { 
1.620     albertel 4754:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4755:           return ''; 
                   4756:        } 
                   4757:     }
1.620     albertel 4758:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4759: 
                   4760:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4761:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 4762: 
1.47      www      4763:     my $namevalue='';
1.800     albertel 4764:     foreach my $key (keys(%$storehash)) {
                   4765:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4766:     }
1.47      www      4767:     $namevalue=~s/\&$//;
1.187     www      4768:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      4769:     return critical
                   4770:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      4771: }
                   4772: 
1.9       www      4773: # --------------------------------------------------------------------- Restore
                   4774: 
                   4775: sub restore {
1.124     www      4776:     my ($symb,$namespace,$domain,$stuname) = @_;
                   4777:     my $home='';
                   4778: 
1.168     albertel 4779:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4780: 
1.122     albertel 4781:     if (!$symb) {
                   4782:       unless ($symb=escape(&symbread())) { return ''; }
                   4783:     } else {
1.213     www      4784:       $symb=&escape(&symbclean($symb));
1.122     albertel 4785:     }
1.188     www      4786:     if (!$namespace) { 
1.620     albertel 4787:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      4788:           return ''; 
                   4789:        } 
                   4790:     }
1.620     albertel 4791:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4792:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   4793:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 4794:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   4795: 
1.12      www      4796:     my %returnhash=();
1.800     albertel 4797:     foreach my $line (split(/\&/,$answer)) {
                   4798: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 4799:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 4800:     }
1.75      www      4801:     my $version;
                   4802:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 4803:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   4804:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 4805:        }
1.75      www      4806:     }
1.13      www      4807:     return %returnhash;
1.34      www      4808: }
                   4809: 
                   4810: # ---------------------------------------------------------- Course Description
1.1118    foxr     4811: #
                   4812: #  
1.34      www      4813: 
                   4814: sub coursedescription {
1.731     albertel 4815:     my ($courseid,$args)=@_;
1.34      www      4816:     $courseid=~s/^\///;
1.49      www      4817:     $courseid=~s/\_/\//g;
1.34      www      4818:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 4819:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 4820:     my $normalid=$cdomain.'_'.$cnum;
                   4821:     # need to always cache even if we get errors otherwise we keep 
                   4822:     # trying and trying and trying to get the course description.
                   4823:     my %envhash=();
                   4824:     my %returnhash=();
1.731     albertel 4825:     
                   4826:     my $expiretime=600;
                   4827:     if ($env{'request.course.id'} eq $normalid) {
                   4828: 	$expiretime=120;
                   4829:     }
                   4830: 
                   4831:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   4832:     if (!$args->{'freshen_cache'}
                   4833: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   4834: 	foreach my $key (keys(%env)) {
                   4835: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   4836: 	    my ($setting) = $1;
                   4837: 	    $returnhash{$setting} = $env{$key};
                   4838: 	}
                   4839: 	return %returnhash;
                   4840:     }
                   4841: 
1.1118    foxr     4842:     # get the data again
                   4843: 
1.731     albertel 4844:     if (!$args->{'one_time'}) {
                   4845: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   4846:     }
1.811     albertel 4847: 
1.34      www      4848:     if ($chome ne 'no_host') {
1.302     albertel 4849:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 4850:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     4851: 	   my $username = $env{'user.name'}; # Defult username
                   4852: 	   if(defined $args->{'user'}) {
                   4853: 	       $username = $args->{'user'};
                   4854: 	   }
1.129     albertel 4855:            $returnhash{'home'}= $chome;
                   4856: 	   $returnhash{'domain'} = $cdomain;
                   4857: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  4858:            if (!defined($returnhash{'type'})) {
                   4859:                $returnhash{'type'} = 'Course';
                   4860:            }
1.130     albertel 4861:            while (my ($name,$value) = each %returnhash) {
1.53      www      4862:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 4863:            }
1.270     www      4864:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     4865:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     4866: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      4867:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   4868:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   4869:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      4870:        }
                   4871:     }
1.731     albertel 4872:     if (!$args->{'one_time'}) {
1.949     raeburn  4873: 	&appenv(\%envhash);
1.731     albertel 4874:     }
1.302     albertel 4875:     return %returnhash;
1.461     www      4876: }
                   4877: 
1.1080    raeburn  4878: sub update_released_required {
                   4879:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   4880:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   4881:         $cid = $env{'request.course.id'};
                   4882:         $cdom = $env{'course.'.$cid.'.domain'};
                   4883:         $cnum = $env{'course.'.$cid.'.num'};
                   4884:         $chome = $env{'course.'.$cid.'.home'};
                   4885:     }
                   4886:     if ($needsrelease) {
                   4887:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   4888:         my $needsupdate;
                   4889:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   4890:             $needsupdate = 1;
                   4891:         } else {
                   4892:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   4893:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   4894:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   4895:                 $needsupdate = 1;
                   4896:             }
                   4897:         }
                   4898:         if ($needsupdate) {
                   4899:             my %needshash = (
                   4900:                              'internal.releaserequired' => $needsrelease,
                   4901:                             );
                   4902:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   4903:             if ($putresult eq 'ok') {
                   4904:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   4905:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   4906:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   4907:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   4908:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   4909:                 }
                   4910:             }
                   4911:         }
                   4912:     }
                   4913:     return;
                   4914: }
                   4915: 
1.461     www      4916: # -------------------------------------------------See if a user is privileged
                   4917: 
                   4918: sub privileged {
                   4919:     my ($username,$domain)=@_;
1.1170    droeschl 4920: 
                   4921:     my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   4922:     my $now = time;
                   4923: 
                   4924:     for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
                   4925:             my ($trole, $tend, $tstart) = split(/_/, $role);
                   4926:             if (($trole eq 'dc') || ($trole eq 'su')) {
                   4927:                 return 1 unless ($tend && $tend < $now) 
                   4928:                     or ($tstart && $tstart > $now);
                   4929:             }
1.461     www      4930: 	}
1.1170    droeschl 4931: 
1.461     www      4932:     return 0;
1.9       www      4933: }
1.1       albertel 4934: 
1.103     harris41 4935: # -------------------------------------------------------- Get user privileges
1.11      www      4936: 
                   4937: sub rolesinit {
1.1169    droeschl 4938:     my ($domain, $username) = @_;
                   4939:     my %userroles = ('user.login.time' => time);
                   4940:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   4941: 
                   4942:     # firstaccess and timerinterval are related to timed maps/resources. 
                   4943:     # also, blocking can be triggered by an activating timer
                   4944:     # it's saved in the user's %env.
                   4945:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   4946:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   4947:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   4948:         %timerintchk, %timerintenv);
                   4949: 
1.1162    raeburn  4950:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 4951:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  4952:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   4953:     }
1.1169    droeschl 4954: 
1.1162    raeburn  4955:     foreach my $key (keys(%timerinterval)) {
                   4956:         my ($cid,$rest) = split(/\0/,$key);
                   4957:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   4958:     }
1.1169    droeschl 4959: 
1.11      www      4960:     my %allroles=();
1.1162    raeburn  4961:     my %allgroups=();
1.11      www      4962: 
1.1169    droeschl 4963:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
                   4964:         my $role = $rolesdump{$area};
                   4965:         $area =~ s/\_\w\w$//;
                   4966: 
                   4967:         my ($trole, $tend, $tstart, $group_privs);
                   4968: 
                   4969:         if ($role =~ /^cr/) {
                   4970:         # Custom role, defined by a user 
                   4971:         # e.g., user.role.cr/msu/smith/mynewrole
                   4972:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   4973:                 $trole = $1;
                   4974:                 ($tend, $tstart) = split('_', $2);
                   4975:             } else {
                   4976:                 $trole = $role;
                   4977:             }
                   4978:         } elsif ($role =~ m|^gr/|) {
                   4979:         # Role of member in a group, defined within a course/community
                   4980:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   4981:             ($trole, $tend, $tstart) = split(/_/, $role);
                   4982:             next if $tstart eq '-1';
                   4983:             ($trole, $group_privs) = split(/\//, $trole);
                   4984:             $group_privs = &unescape($group_privs);
                   4985:         } else {
                   4986:         # Just a normal role, defined in roles.tab
                   4987:             ($trole, $tend, $tstart) = split(/_/,$role);
                   4988:         }
                   4989: 
                   4990:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   4991:                  $username);
                   4992:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   4993: 
                   4994:         # role expired or not available yet?
                   4995:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   4996:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   4997: 
                   4998:         next if $area eq '' or $trole eq '';
                   4999: 
                   5000:         my $spec = "$trole.$area";
                   5001:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5002: 
                   5003:         if ($trole =~ /^cr\//) {
                   5004:         # Custom role, defined by a user
                   5005:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5006:         } elsif ($trole eq 'gr') {
                   5007:         # Role of a member in a group, defined within a course/community
                   5008:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5009:             next;
                   5010:         } else {
                   5011:         # Normal role, defined in roles.tab
                   5012:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5013:         }
                   5014: 
                   5015:         my $cid = $tdomain.'_'.$trest;
                   5016:         unless ($firstaccchk{$cid}) {
                   5017:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5018:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5019:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5020:                         $coursetimerstarts{$cid}{$item}; 
                   5021:                 }
                   5022:             }
                   5023:             $firstaccchk{$cid} = 1;
                   5024:         }
                   5025:         unless ($timerintchk{$cid}) {
                   5026:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5027:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5028:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5029:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5030:                 }
1.12      www      5031:             }
1.1169    droeschl 5032:             $timerintchk{$cid} = 1;
1.191     harris41 5033:         }
1.11      www      5034:     }
1.1169    droeschl 5035: 
                   5036:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
                   5037:         \%allroles, \%allgroups);
                   5038:     $env{'user.adv'} = $userroles{'user.adv'};
                   5039: 
1.1162    raeburn  5040:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5041: }
                   5042: 
1.567     raeburn  5043: sub set_arearole {
                   5044:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   5045: # log the associated role with the area
                   5046:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 5047:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5048: }
                   5049: 
                   5050: sub custom_roleprivs {
                   5051:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5052:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   5053:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 5054:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5055:         my ($rdummy,$roledef)=
                   5056:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5057:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5058:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5059:             if (defined($syspriv)) {
1.1043    raeburn  5060:                 if ($trest =~ /^$match_community$/) {
                   5061:                     $syspriv =~ s/bre\&S//; 
                   5062:                 }
1.567     raeburn  5063:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5064:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5065:             }
                   5066:             if ($tdomain ne '') {
                   5067:                 if (defined($dompriv)) {
                   5068:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5069:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5070:                 }
                   5071:                 if (($trest ne '') && (defined($coursepriv))) {
                   5072:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5073:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5074:                 }
                   5075:             }
                   5076:         }
                   5077:     }
                   5078: }
                   5079: 
1.678     raeburn  5080: sub group_roleprivs {
                   5081:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   5082:     my $access = 1;
                   5083:     my $now = time;
                   5084:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   5085:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   5086:     if ($access) {
1.811     albertel 5087:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  5088:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   5089:     }
                   5090: }
1.567     raeburn  5091: 
                   5092: sub standard_roleprivs {
                   5093:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   5094:     if (defined($pr{$trole.':s'})) {
                   5095:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   5096:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   5097:     }
                   5098:     if ($tdomain ne '') {
                   5099:         if (defined($pr{$trole.':d'})) {
                   5100:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5101:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5102:         }
                   5103:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   5104:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   5105:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   5106:         }
                   5107:     }
                   5108: }
                   5109: 
                   5110: sub set_userprivs {
1.1064    raeburn  5111:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  5112:     my $author=0;
                   5113:     my $adv=0;
1.678     raeburn  5114:     my %grouproles = ();
                   5115:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  5116:         my @groupkeys; 
1.1000    raeburn  5117:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  5118:             push(@groupkeys,$role);
                   5119:         }
                   5120:         if (ref($groups_roles) eq 'HASH') {
                   5121:             foreach my $key (keys(%{$groups_roles})) {
                   5122:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   5123:                     push(@groupkeys,$key);
                   5124:                 }
                   5125:             }
                   5126:         }
                   5127:         if (@groupkeys > 0) {
                   5128:             foreach my $role (@groupkeys) {
                   5129:                 my ($trole,$area,$sec,$extendedarea);
                   5130:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   5131:                     $trole = $1;
                   5132:                     $area = $2;
                   5133:                     $sec = $3;
                   5134:                     $extendedarea = $area.$sec;
                   5135:                     if (exists($$allgroups{$area})) {
                   5136:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   5137:                             my $spec = $trole.'.'.$extendedarea;
                   5138:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  5139:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  5140:                         }
1.678     raeburn  5141:                     }
                   5142:                 }
                   5143:             }
                   5144:         }
                   5145:     }
1.800     albertel 5146:     foreach my $group (keys(%grouproles)) {
                   5147:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  5148:     }
1.800     albertel 5149:     foreach my $role (keys(%{$allroles})) {
                   5150:         my %thesepriv;
1.941     raeburn  5151:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 5152:         foreach my $item (split(/:/,$$allroles{$role})) {
                   5153:             if ($item ne '') {
                   5154:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  5155:                 if ($restrictions eq '') {
                   5156:                     $thesepriv{$privilege}='F';
                   5157:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   5158:                     $thesepriv{$privilege}.=$restrictions;
                   5159:                 }
                   5160:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   5161:             }
                   5162:         }
                   5163:         my $thesestr='';
1.1104    raeburn  5164:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 5165: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   5166: 	}
                   5167:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  5168:     }
                   5169:     return ($author,$adv);
                   5170: }
                   5171: 
1.994     raeburn  5172: sub role_status {
1.1104    raeburn  5173:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  5174:     my @pwhere = ();
                   5175:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   5176:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   5177:         unless (!defined($$role) || $$role eq '') {
                   5178:             $$where=join('.',@pwhere);
                   5179:             $$trolecode=$$role.'.'.$$where;
                   5180:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   5181:             $$tstatus='is';
1.1104    raeburn  5182:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  5183:                 $$tstatus='future';
1.1034    raeburn  5184:                 if ($$tstart<$now) {
                   5185:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  5186:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  5187:                             my (%allroles,%allgroups,$group_privs,
                   5188:                                 %groups_roles,@rolecodes);
1.1002    raeburn  5189:                             my %userroles = (
                   5190:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   5191:                             );
1.1064    raeburn  5192:                             @rolecodes = ('cm'); 
1.1002    raeburn  5193:                             my $spec=$$role.'.'.$$where;
                   5194:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   5195:                             if ($$role =~ /^cr\//) {
                   5196:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  5197:                                 push(@rolecodes,'cr');
1.1002    raeburn  5198:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  5199:                                 push(@rolecodes,$$role);
1.1002    raeburn  5200:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   5201:                                                     $env{'user.name'});
1.1064    raeburn  5202:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  5203:                                 (undef,my $group_privs) = split(/\//,$trole);
                   5204:                                 $group_privs = &unescape($group_privs);
                   5205:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  5206:                                 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  5207:                                 &get_groups_roles($tdomain,$trest,
                   5208:                                                   \%course_roles,\@rolecodes,
                   5209:                                                   \%groups_roles);
1.1002    raeburn  5210:                             } else {
1.1064    raeburn  5211:                                 push(@rolecodes,$$role);
1.1002    raeburn  5212:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   5213:                             }
1.1064    raeburn  5214:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   5215:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  5216:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   5217:                         }
                   5218:                     }
1.1034    raeburn  5219:                     $$tstatus = 'is';
1.1002    raeburn  5220:                 }
1.994     raeburn  5221:             }
                   5222:             if ($$tend) {
1.1104    raeburn  5223:                 if ($$tend<$update) {
1.994     raeburn  5224:                     $$tstatus='expired';
                   5225:                 } elsif ($$tend<$now) {
                   5226:                     $$tstatus='will_not';
                   5227:                 }
                   5228:             }
                   5229:         }
                   5230:     }
                   5231: }
                   5232: 
1.1104    raeburn  5233: sub get_groups_roles {
                   5234:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   5235:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   5236:                   (ref($rolecodes) eq 'ARRAY') && 
                   5237:                   (ref($groups_roles) eq 'HASH')); 
                   5238:     if (keys(%{$cdom_courseroles}) > 0) {
                   5239:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   5240:         if ($cdom ne '' && $cnum ne '') {
                   5241:             foreach my $key (keys(%{$cdom_courseroles})) {
                   5242:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   5243:                     my $crsrole = $1;
                   5244:                     my $crssec = $2;
                   5245:                     if ($crsrole =~ /^cr/) {
                   5246:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   5247:                             push(@{$rolecodes},'cr');
                   5248:                         }
                   5249:                     } else {
                   5250:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   5251:                             push(@{$rolecodes},$crsrole);
                   5252:                         }
                   5253:                     }
                   5254:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   5255:                     if ($crssec ne '') {
                   5256:                         $rolekey .= "/$crssec";
                   5257:                     }
                   5258:                     $rolekey .= './';
                   5259:                     $groups_roles->{$rolekey} = $rolecodes;
                   5260:                 }
                   5261:             }
                   5262:         }
                   5263:     }
                   5264:     return;
                   5265: }
                   5266: 
                   5267: sub delete_env_groupprivs {
                   5268:     my ($where,$courseroles,$possroles) = @_;
                   5269:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   5270:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   5271:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   5272:         %{$courseroles->{$udom}} =
                   5273:             &get_my_roles('','','userroles',['active'],
                   5274:                           $possroles,[$udom],1);
                   5275:     }
                   5276:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   5277:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   5278:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   5279:             my $area = '/'.$cdom.'/'.$cnum;
                   5280:             my $privkey = "user.priv.$crsrole.$area";
                   5281:             if ($crssec ne '') {
                   5282:                 $privkey .= '/'.$crssec;
                   5283:             }
                   5284:             $privkey .= ".$area/$group";
                   5285:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   5286:         }
                   5287:     }
                   5288:     return;
                   5289: }
                   5290: 
1.994     raeburn  5291: sub check_adhoc_privs {
1.1104    raeburn  5292:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  5293:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.9  raeburn  5294:     my $setprivs;
1.994     raeburn  5295:     if ($env{$cckey}) {
                   5296:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  5297:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  5298:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  5299:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9  raeburn  5300:             $setprivs = 1;
1.994     raeburn  5301:         }
                   5302:     } else {
1.1088    raeburn  5303:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9  raeburn  5304:         $setprivs = 1;
1.994     raeburn  5305:     }
1.1172.2.9  raeburn  5306:     return $setprivs;
1.994     raeburn  5307: }
                   5308: 
                   5309: sub set_adhoc_privileges {
                   5310: # role can be cc or ca
1.1088    raeburn  5311:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  5312:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   5313:     my $spec = $role.'.'.$area;
                   5314:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
                   5315:                                   $env{'user.name'});
                   5316:     my %ccrole = ();
                   5317:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   5318:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   5319:     &appenv(\%userroles,[$role,'cm']);
                   5320:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  5321:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   5322:         &appenv( {'request.role'        => $spec,
                   5323:                   'request.role.domain' => $dcdom,
                   5324:                   'request.course.sec'  => ''
                   5325:                  }
                   5326:                );
                   5327:         my $tadv=0;
                   5328:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   5329:         &appenv({'request.role.adv'    => $tadv});
                   5330:     }
1.994     raeburn  5331: }
                   5332: 
1.12      www      5333: # --------------------------------------------------------------- get interface
                   5334: 
                   5335: sub get {
1.131     albertel 5336:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5337:    my $items='';
1.800     albertel 5338:    foreach my $item (@$storearr) {
                   5339:        $items.=&escape($item).'&';
1.191     harris41 5340:    }
1.12      www      5341:    $items=~s/\&$//;
1.620     albertel 5342:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5343:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 5344:    my $uhome=&homeserver($uname,$udomain);
                   5345: 
1.133     albertel 5346:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5347:    my @pairs=split(/\&/,$rep);
1.273     albertel 5348:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   5349:      return @pairs;
                   5350:    }
1.15      www      5351:    my %returnhash=();
1.42      www      5352:    my $i=0;
1.800     albertel 5353:    foreach my $item (@$storearr) {
                   5354:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5355:       $i++;
1.191     harris41 5356:    }
1.15      www      5357:    return %returnhash;
1.27      www      5358: }
                   5359: 
                   5360: # --------------------------------------------------------------- del interface
                   5361: 
                   5362: sub del {
1.133     albertel 5363:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      5364:    my $items='';
1.800     albertel 5365:    foreach my $item (@$storearr) {
                   5366:        $items.=&escape($item).'&';
1.191     harris41 5367:    }
1.984     neumanie 5368: 
1.27      www      5369:    $items=~s/\&$//;
1.620     albertel 5370:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5371:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5372:    my $uhome=&homeserver($uname,$udomain);
                   5373:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5374: }
                   5375: 
                   5376: # -------------------------------------------------------------- dump interface
                   5377: 
                   5378: sub dump {
1.1166    raeburn  5379:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.755     albertel 5380:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5381:     if (!$uname) { $uname=$env{'user.name'}; }
                   5382:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 5383: 
1.755     albertel 5384:     if ($regexp) {
                   5385: 	$regexp=&escape($regexp);
                   5386:     } else {
                   5387: 	$regexp='.';
                   5388:     }
1.1166    raeburn  5389:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 5390:     my @pairs=split(/\&/,$rep);
                   5391:     my %returnhash=();
1.1098    foxr     5392:     if (!($rep =~ /^error/ )) {
                   5393: 	foreach my $item (@pairs) {
                   5394: 	    my ($key,$value)=split(/=/,$item,2);
                   5395: 	    $key = &unescape($key);
                   5396: 	    next if ($key =~ /^error: 2 /);
                   5397: 	    $returnhash{$key}=&thaw_unescape($value);
                   5398: 	}
1.755     albertel 5399:     }
                   5400:     return %returnhash;
1.407     www      5401: }
                   5402: 
1.1098    foxr     5403: 
1.717     albertel 5404: # --------------------------------------------------------- dumpstore interface
                   5405: 
                   5406: sub dumpstore {
                   5407:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 5408:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5409:    if (!$uname) { $uname=$env{'user.name'}; }
                   5410:    my $uhome=&homeserver($uname,$udomain);
                   5411:    if ($regexp) {
                   5412:        $regexp=&escape($regexp);
                   5413:    } else {
                   5414:        $regexp='.';
                   5415:    }
                   5416:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   5417:    my @pairs=split(/\&/,$rep);
                   5418:    my %returnhash=();
                   5419:    foreach my $item (@pairs) {
                   5420:        my ($key,$value)=split(/=/,$item,2);
                   5421:        next if ($key =~ /^error: 2 /);
                   5422:        $returnhash{$key}=&thaw_unescape($value);
                   5423:    }
                   5424:    return %returnhash;
1.717     albertel 5425: }
                   5426: 
1.407     www      5427: # -------------------------------------------------------------- keys interface
                   5428: 
                   5429: sub getkeys {
                   5430:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 5431:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5432:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      5433:    my $uhome=&homeserver($uname,$udomain);
                   5434:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   5435:    my @keyarray=();
1.800     albertel 5436:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  5437:       next if ($key =~ /^error: 2 /);
1.800     albertel 5438:       push(@keyarray,&unescape($key));
1.407     www      5439:    }
                   5440:    return @keyarray;
1.318     matthew  5441: }
                   5442: 
1.319     matthew  5443: # --------------------------------------------------------------- currentdump
                   5444: sub currentdump {
1.328     matthew  5445:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 5446:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   5447:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   5448:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  5449:    my $uhome = &homeserver($sname,$sdom);
                   5450:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  5451:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  5452:    #
1.318     matthew  5453:    my %returnhash=();
1.319     matthew  5454:    #
                   5455:    if ($rep eq "unknown_cmd") { 
                   5456:        # an old lond will not know currentdump
                   5457:        # Do a dump and make it look like a currentdump
1.822     albertel 5458:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  5459:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   5460:        my %hash = @tmp;
                   5461:        @tmp=();
1.424     matthew  5462:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  5463:    } else {
                   5464:        my @pairs=split(/\&/,$rep);
1.800     albertel 5465:        foreach my $pair (@pairs) {
                   5466:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  5467:            my ($symb,$param) = split(/:/,$key);
                   5468:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 5469:                                                         &thaw_unescape($value);
1.319     matthew  5470:        }
1.191     harris41 5471:    }
1.12      www      5472:    return %returnhash;
1.424     matthew  5473: }
                   5474: 
                   5475: sub convert_dump_to_currentdump{
                   5476:     my %hash = %{shift()};
                   5477:     my %returnhash;
                   5478:     # Code ripped from lond, essentially.  The only difference
                   5479:     # here is the unescaping done by lonnet::dump().  Conceivably
                   5480:     # we might run in to problems with parameter names =~ /^v\./
                   5481:     while (my ($key,$value) = each(%hash)) {
                   5482:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 5483: 	$symb  = &unescape($symb);
                   5484: 	$param = &unescape($param);
1.424     matthew  5485:         next if ($v eq 'version' || $symb eq 'keys');
                   5486:         next if (exists($returnhash{$symb}) &&
                   5487:                  exists($returnhash{$symb}->{$param}) &&
                   5488:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   5489:         $returnhash{$symb}->{$param}=$value;
                   5490:         $returnhash{$symb}->{'v.'.$param}=$v;
                   5491:     }
                   5492:     #
                   5493:     # Remove all of the keys in the hashes which keep track of
                   5494:     # the version of the parameter.
                   5495:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   5496:         # use a foreach because we are going to delete from the hash.
                   5497:         foreach my $key (keys(%$param_hash)) {
                   5498:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   5499:         }
                   5500:     }
                   5501:     return \%returnhash;
1.12      www      5502: }
                   5503: 
1.627     albertel 5504: # ------------------------------------------------------ critical inc interface
                   5505: 
                   5506: sub cinc {
                   5507:     return &inc(@_,'critical');
                   5508: }
                   5509: 
1.449     matthew  5510: # --------------------------------------------------------------- inc interface
                   5511: 
                   5512: sub inc {
1.627     albertel 5513:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 5514:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5515:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  5516:     my $uhome=&homeserver($uname,$udomain);
                   5517:     my $items='';
                   5518:     if (! ref($store)) {
                   5519:         # got a single value, so use that instead
                   5520:         $items = &escape($store).'=&';
                   5521:     } elsif (ref($store) eq 'SCALAR') {
                   5522:         $items = &escape($$store).'=&';        
                   5523:     } elsif (ref($store) eq 'ARRAY') {
                   5524:         $items = join('=&',map {&escape($_);} @{$store});
                   5525:     } elsif (ref($store) eq 'HASH') {
                   5526:         while (my($key,$value) = each(%{$store})) {
                   5527:             $items.= &escape($key).'='.&escape($value).'&';
                   5528:         }
                   5529:     }
                   5530:     $items=~s/\&$//;
1.627     albertel 5531:     if ($critical) {
                   5532: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5533:     } else {
                   5534: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5535:     }
1.449     matthew  5536: }
                   5537: 
1.12      www      5538: # --------------------------------------------------------------- put interface
                   5539: 
                   5540: sub put {
1.134     albertel 5541:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5542:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5543:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5544:    my $uhome=&homeserver($uname,$udomain);
1.12      www      5545:    my $items='';
1.800     albertel 5546:    foreach my $item (keys(%$storehash)) {
                   5547:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5548:    }
1.12      www      5549:    $items=~s/\&$//;
1.134     albertel 5550:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      5551: }
                   5552: 
1.631     albertel 5553: # ------------------------------------------------------------ newput interface
                   5554: 
                   5555: sub newput {
                   5556:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   5557:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5558:    if (!$uname) { $uname=$env{'user.name'}; }
                   5559:    my $uhome=&homeserver($uname,$udomain);
                   5560:    my $items='';
                   5561:    foreach my $key (keys(%$storehash)) {
                   5562:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   5563:    }
                   5564:    $items=~s/\&$//;
                   5565:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   5566: }
                   5567: 
                   5568: # ---------------------------------------------------------  putstore interface
                   5569: 
1.524     raeburn  5570: sub putstore {
1.715     albertel 5571:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 5572:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5573:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  5574:    my $uhome=&homeserver($uname,$udomain);
                   5575:    my $items='';
1.715     albertel 5576:    foreach my $key (keys(%$storehash)) {
                   5577:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  5578:    }
1.715     albertel 5579:    $items=~s/\&$//;
1.716     albertel 5580:    my $esc_symb=&escape($symb);
                   5581:    my $esc_v=&escape($version);
1.715     albertel 5582:    my $reply =
1.716     albertel 5583:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 5584: 	      $uhome);
                   5585:    if ($reply eq 'unknown_cmd') {
1.716     albertel 5586:        # gfall back to way things use to be done
1.715     albertel 5587:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   5588: 			    $uname);
1.524     raeburn  5589:    }
1.715     albertel 5590:    return $reply;
                   5591: }
                   5592: 
                   5593: sub old_putstore {
1.716     albertel 5594:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   5595:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5596:     if (!$uname) { $uname=$env{'user.name'}; }
                   5597:     my $uhome=&homeserver($uname,$udomain);
                   5598:     my %newstorehash;
1.800     albertel 5599:     foreach my $item (keys(%$storehash)) {
                   5600: 	my $key = $version.':'.&escape($symb).':'.$item;
                   5601: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 5602:     }
                   5603:     my $items='';
                   5604:     my %allitems = ();
1.800     albertel 5605:     foreach my $item (keys(%newstorehash)) {
                   5606: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 5607: 	    my $key = $1.':keys:'.$2;
                   5608: 	    $allitems{$key} .= $3.':';
                   5609: 	}
1.800     albertel 5610: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 5611:     }
1.800     albertel 5612:     foreach my $item (keys(%allitems)) {
                   5613: 	$allitems{$item} =~ s/\:$//;
                   5614: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 5615:     }
                   5616:     $items=~s/\&$//;
                   5617:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  5618: }
                   5619: 
1.47      www      5620: # ------------------------------------------------------ critical put interface
                   5621: 
                   5622: sub cput {
1.134     albertel 5623:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5624:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5625:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5626:    my $uhome=&homeserver($uname,$udomain);
1.47      www      5627:    my $items='';
1.800     albertel 5628:    foreach my $item (keys(%$storehash)) {
                   5629:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5630:    }
1.47      www      5631:    $items=~s/\&$//;
1.134     albertel 5632:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5633: }
                   5634: 
                   5635: # -------------------------------------------------------------- eget interface
                   5636: 
                   5637: sub eget {
1.133     albertel 5638:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5639:    my $items='';
1.800     albertel 5640:    foreach my $item (@$storearr) {
                   5641:        $items.=&escape($item).'&';
1.191     harris41 5642:    }
1.12      www      5643:    $items=~s/\&$//;
1.620     albertel 5644:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5645:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5646:    my $uhome=&homeserver($uname,$udomain);
                   5647:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5648:    my @pairs=split(/\&/,$rep);
                   5649:    my %returnhash=();
1.42      www      5650:    my $i=0;
1.800     albertel 5651:    foreach my $item (@$storearr) {
                   5652:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5653:       $i++;
1.191     harris41 5654:    }
1.12      www      5655:    return %returnhash;
                   5656: }
                   5657: 
1.667     albertel 5658: # ------------------------------------------------------------ tmpput interface
                   5659: sub tmpput {
1.802     raeburn  5660:     my ($storehash,$server,$context)=@_;
1.667     albertel 5661:     my $items='';
1.800     albertel 5662:     foreach my $item (keys(%$storehash)) {
                   5663: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 5664:     }
                   5665:     $items=~s/\&$//;
1.802     raeburn  5666:     if (defined($context)) {
                   5667:         $items .= ':'.&escape($context);
                   5668:     }
1.667     albertel 5669:     return &reply("tmpput:$items",$server);
                   5670: }
                   5671: 
                   5672: # ------------------------------------------------------------ tmpget interface
                   5673: sub tmpget {
1.688     albertel 5674:     my ($token,$server)=@_;
                   5675:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5676:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 5677:     my %returnhash;
                   5678:     foreach my $item (split(/\&/,$rep)) {
                   5679: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  5680:         next if ($key =~ /^error: 2 /);
1.667     albertel 5681: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   5682:     }
                   5683:     return %returnhash;
                   5684: }
                   5685: 
1.1113    raeburn  5686: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 5687: sub tmpdel {
                   5688:     my ($token,$server)=@_;
                   5689:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5690:     return &reply("tmpdel:$token",$server);
                   5691: }
                   5692: 
1.1172.2.13  raeburn  5693: # ------------------------------------------------------------ get_timebased_id
                   5694: 
                   5695: sub get_timebased_id {
                   5696:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   5697:         $maxtries) = @_;
                   5698:     my ($newid,$error,$dellock);
                   5699:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   5700:         return ('','ok','invalid call to get suffix');
                   5701:     }
                   5702: 
                   5703: # set defaults for any optional args for which values were not supplied
                   5704:     if ($who eq '') {
                   5705:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   5706:     }
                   5707:     if (!$locktries) {
                   5708:         $locktries = 3;
                   5709:     }
                   5710:     if (!$maxtries) {
                   5711:         $maxtries = 10;
                   5712:     }
                   5713: 
                   5714:     if (($cdom eq '') || ($cnum eq '')) {
                   5715:         if ($env{'request.course.id'}) {
                   5716:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5717:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5718:         }
                   5719:         if (($cdom eq '') || ($cnum eq '')) {
                   5720:             return ('','ok','call to get suffix not in course context');
                   5721:         }
                   5722:     }
                   5723: 
                   5724: # construct locking item
                   5725:     my $lockhash = {
                   5726:                       $prefix."\0".'locked_'.$keyid => $who,
                   5727:                    };
                   5728:     my $tries = 0;
                   5729: 
                   5730: # attempt to get lock on nohist_$namespace file
                   5731:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   5732:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   5733:         $tries ++;
                   5734:         sleep 1;
                   5735:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   5736:     }
                   5737: 
                   5738: # attempt to get unique identifier, based on current timestamp
                   5739:     if ($gotlock eq 'ok') {
                   5740:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   5741:         my $id = time;
                   5742:         $newid = $id;
                   5743:         my $idtries = 0;
                   5744:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   5745:             if ($idtype eq 'concat') {
                   5746:                 $newid = $id.$idtries;
                   5747:             } else {
                   5748:                 $newid ++;
                   5749:             }
                   5750:             $idtries ++;
                   5751:         }
                   5752:         if (!exists($inuse{$prefix."\0".$newid})) {
                   5753:             my %new_item =  (
                   5754:                               $prefix."\0".$newid => $who,
                   5755:                             );
                   5756:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   5757:                                                  $cdom,$cnum);
                   5758:             if ($putresult ne 'ok') {
                   5759:                 undef($newid);
                   5760:                 $error = 'error saving new item: '.$putresult;
                   5761:             }
                   5762:         } else {
                   5763:              $error = ('error: no unique suffix available for the new item ');
                   5764:         }
                   5765: #  remove lock
                   5766:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   5767:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   5768:     } else {
                   5769:         $error = "error: could not obtain lockfile\n";
                   5770:         $dellock = 'ok';
                   5771:     }
                   5772:     return ($newid,$dellock,$error);
                   5773: }
                   5774: 
1.765     albertel 5775: # -------------------------------------------------- portfolio access checking
                   5776: 
                   5777: sub portfolio_access {
1.766     albertel 5778:     my ($requrl) = @_;
1.765     albertel 5779:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   5780:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  5781:     if ($result) {
                   5782:         my %setters;
                   5783:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5784:             my ($startblock,$endblock) =
                   5785:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   5786:             if ($startblock && $endblock) {
                   5787:                 return 'B';
                   5788:             }
                   5789:         } else {
                   5790:             my ($startblock,$endblock) =
                   5791:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   5792:             if ($startblock && $endblock) {
                   5793:                 return 'B';
                   5794:             }
                   5795:         }
                   5796:     }
1.765     albertel 5797:     if ($result eq 'ok') {
1.766     albertel 5798:        return 'F';
1.765     albertel 5799:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 5800:        return 'A';
1.765     albertel 5801:     }
1.766     albertel 5802:     return '';
1.765     albertel 5803: }
                   5804: 
                   5805: sub get_portfolio_access {
1.767     albertel 5806:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   5807: 
                   5808:     if (!ref($access_hash)) {
                   5809: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   5810: 	my %access_controls = &get_access_controls($current_perms,$group,
                   5811: 						   $file_name);
                   5812: 	$access_hash = $access_controls{$file_name};
                   5813:     }
                   5814: 
1.765     albertel 5815:     my ($public,$guest,@domains,@users,@courses,@groups);
                   5816:     my $now = time;
                   5817:     if (ref($access_hash) eq 'HASH') {
                   5818:         foreach my $key (keys(%{$access_hash})) {
                   5819:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5820:             if ($start > $now) {
                   5821:                 next;
                   5822:             }
                   5823:             if ($end && $end<$now) {
                   5824:                 next;
                   5825:             }
                   5826:             if ($scope eq 'public') {
                   5827:                 $public = $key;
                   5828:                 last;
                   5829:             } elsif ($scope eq 'guest') {
                   5830:                 $guest = $key;
                   5831:             } elsif ($scope eq 'domains') {
                   5832:                 push(@domains,$key);
                   5833:             } elsif ($scope eq 'users') {
                   5834:                 push(@users,$key);
                   5835:             } elsif ($scope eq 'course') {
                   5836:                 push(@courses,$key);
                   5837:             } elsif ($scope eq 'group') {
                   5838:                 push(@groups,$key);
                   5839:             }
                   5840:         }
                   5841:         if ($public) {
                   5842:             return 'ok';
                   5843:         }
                   5844:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5845:             if ($guest) {
                   5846:                 return $guest;
                   5847:             }
                   5848:         } else {
                   5849:             if (@domains > 0) {
                   5850:                 foreach my $domkey (@domains) {
                   5851:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   5852:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   5853:                             return 'ok';
                   5854:                         }
                   5855:                     }
                   5856:                 }
                   5857:             }
                   5858:             if (@users > 0) {
                   5859:                 foreach my $userkey (@users) {
1.865     raeburn  5860:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   5861:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   5862:                             if (ref($item) eq 'HASH') {
                   5863:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   5864:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   5865:                                     return 'ok';
                   5866:                                 }
                   5867:                             }
                   5868:                         }
                   5869:                     } 
1.765     albertel 5870:                 }
                   5871:             }
                   5872:             my %roleshash;
                   5873:             my @courses_and_groups = @courses;
                   5874:             push(@courses_and_groups,@groups); 
                   5875:             if (@courses_and_groups > 0) {
                   5876:                 my (%allgroups,%allroles); 
                   5877:                 my ($start,$end,$role,$sec,$group);
                   5878:                 foreach my $envkey (%env) {
1.1060    raeburn  5879:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5880:                         my $cid = $2.'_'.$3; 
                   5881:                         if ($1 eq 'gr') {
                   5882:                             $group = $4;
                   5883:                             $allgroups{$cid}{$group} = $env{$envkey};
                   5884:                         } else {
                   5885:                             if ($4 eq '') {
                   5886:                                 $sec = 'none';
                   5887:                             } else {
                   5888:                                 $sec = $4;
                   5889:                             }
                   5890:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5891:                         }
1.811     albertel 5892:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5893:                         my $cid = $2.'_'.$3;
                   5894:                         if ($4 eq '') {
                   5895:                             $sec = 'none';
                   5896:                         } else {
                   5897:                             $sec = $4;
                   5898:                         }
                   5899:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5900:                     }
                   5901:                 }
                   5902:                 if (keys(%allroles) == 0) {
                   5903:                     return;
                   5904:                 }
                   5905:                 foreach my $key (@courses_and_groups) {
                   5906:                     my %content = %{$$access_hash{$key}};
                   5907:                     my $cnum = $content{'number'};
                   5908:                     my $cdom = $content{'domain'};
                   5909:                     my $cid = $cdom.'_'.$cnum;
                   5910:                     if (!exists($allroles{$cid})) {
                   5911:                         next;
                   5912:                     }    
                   5913:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   5914:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   5915:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   5916:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   5917:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   5918:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   5919:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   5920:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   5921:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   5922:                                         if (grep/^all$/,@sections) {
                   5923:                                             return 'ok';
                   5924:                                         } else {
                   5925:                                             if (grep/^$sec$/,@sections) {
                   5926:                                                 return 'ok';
                   5927:                                             }
                   5928:                                         }
                   5929:                                     }
                   5930:                                 }
                   5931:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   5932:                                     if (grep/^none$/,@groups) {
                   5933:                                         return 'ok';
                   5934:                                     }
                   5935:                                 } else {
                   5936:                                     if (grep/^all$/,@groups) {
                   5937:                                         return 'ok';
                   5938:                                     } 
                   5939:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   5940:                                         if (grep/^$group$/,@groups) {
                   5941:                                             return 'ok';
                   5942:                                         }
                   5943:                                     }
                   5944:                                 } 
                   5945:                             }
                   5946:                         }
                   5947:                     }
                   5948:                 }
                   5949:             }
                   5950:             if ($guest) {
                   5951:                 return $guest;
                   5952:             }
                   5953:         }
                   5954:     }
                   5955:     return;
                   5956: }
                   5957: 
                   5958: sub course_group_datechecker {
                   5959:     my ($dates,$now,$status) = @_;
                   5960:     my ($start,$end) = split(/\./,$dates);
                   5961:     if (!$start && !$end) {
                   5962:         return 'ok';
                   5963:     }
                   5964:     if (grep/^active$/,@{$status}) {
                   5965:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   5966:             return 'ok';
                   5967:         }
                   5968:     }
                   5969:     if (grep/^previous$/,@{$status}) {
                   5970:         if ($end > $now ) {
                   5971:             return 'ok';
                   5972:         }
                   5973:     }
                   5974:     if (grep/^future$/,@{$status}) {
                   5975:         if ($start > $now) {
                   5976:             return 'ok';
                   5977:         }
                   5978:     }
                   5979:     return; 
                   5980: }
                   5981: 
                   5982: sub parse_portfolio_url {
                   5983:     my ($url) = @_;
                   5984: 
                   5985:     my ($type,$udom,$unum,$group,$file_name);
                   5986:     
1.823     albertel 5987:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 5988: 	$type = 1;
                   5989:         $udom = $1;
                   5990:         $unum = $2;
                   5991:         $file_name = $3;
1.823     albertel 5992:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 5993: 	$type = 2;
                   5994:         $udom = $1;
                   5995:         $unum = $2;
                   5996:         $group = $3;
                   5997:         $file_name = $3.'/'.$4;
                   5998:     }
                   5999:     if (wantarray) {
                   6000: 	return ($type,$udom,$unum,$file_name,$group);
                   6001:     }
                   6002:     return $type;
                   6003: }
                   6004: 
                   6005: sub is_portfolio_url {
                   6006:     my ($url) = @_;
                   6007:     return scalar(&parse_portfolio_url($url));
                   6008: }
                   6009: 
1.798     raeburn  6010: sub is_portfolio_file {
                   6011:     my ($file) = @_;
1.820     raeburn  6012:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  6013:         return 1;
                   6014:     }
                   6015:     return;
                   6016: }
                   6017: 
1.976     raeburn  6018: sub usertools_access {
1.1084    raeburn  6019:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  6020:     my ($access,%tools);
                   6021:     if ($context eq '') {
                   6022:         $context = 'tools';
                   6023:     }
                   6024:     if ($context eq 'requestcourses') {
                   6025:         %tools = (
                   6026:                       official   => 1,
                   6027:                       unofficial => 1,
1.1006    raeburn  6028:                       community  => 1,
1.985     raeburn  6029:                  );
1.1172.2.9  raeburn  6030:     } elsif ($context eq 'requestauthor') {
                   6031:         %tools = (
                   6032:                       requestauthor => 1,
                   6033:                  );
1.985     raeburn  6034:     } else {
                   6035:         %tools = (
                   6036:                       aboutme   => 1,
                   6037:                       blog      => 1,
1.1172.2.6  raeburn  6038:                       webdav    => 1,
1.985     raeburn  6039:                       portfolio => 1,
                   6040:                  );
                   6041:     }
1.976     raeburn  6042:     return if (!defined($tools{$tool}));
                   6043: 
                   6044:     if ((!defined($udom)) || (!defined($uname))) {
                   6045:         $udom = $env{'user.domain'};
                   6046:         $uname = $env{'user.name'};
                   6047:     }
                   6048: 
1.978     raeburn  6049:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6050:         if ($action ne 'reload') {
1.985     raeburn  6051:             if ($context eq 'requestcourses') {
                   6052:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  6053:             } elsif ($context eq 'requestauthor') {
                   6054:                 return $env{'environment.canrequest.author'};
1.985     raeburn  6055:             } else {
                   6056:                 return $env{'environment.availabletools.'.$tool};
                   6057:             }
                   6058:         }
1.976     raeburn  6059:     }
                   6060: 
1.1172.2.9  raeburn  6061:     my ($toolstatus,$inststatus,$envkey);
                   6062:     if ($context eq 'requestauthor') {
                   6063:         $envkey = $context;
                   6064:     } else {
                   6065:         $envkey = $context.'.'.$tool;
                   6066:     }
1.976     raeburn  6067: 
1.985     raeburn  6068:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   6069:          ($action ne 'reload')) {
1.1172.2.9  raeburn  6070:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  6071:         $inststatus = $env{'environment.inststatus'};
                   6072:     } else {
1.1084    raeburn  6073:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  6074:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  6075:             $inststatus = $userenvref->{'inststatus'};
                   6076:         } else {
1.1172.2.9  raeburn  6077:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   6078:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  6079:             $inststatus = $userenv{'inststatus'};
                   6080:         }
1.976     raeburn  6081:     }
                   6082: 
                   6083:     if ($toolstatus ne '') {
                   6084:         if ($toolstatus) {
                   6085:             $access = 1;
                   6086:         } else {
                   6087:             $access = 0;
                   6088:         }
                   6089:         return $access;
                   6090:     }
                   6091: 
1.1084    raeburn  6092:     my ($is_adv,%domdef);
                   6093:     if (ref($is_advref) eq 'HASH') {
                   6094:         $is_adv = $is_advref->{'is_adv'};
                   6095:     } else {
                   6096:         $is_adv = &is_advanced_user($udom,$uname);
                   6097:     }
                   6098:     if (ref($domdefref) eq 'HASH') {
                   6099:         %domdef = %{$domdefref};
                   6100:     } else {
                   6101:         %domdef = &get_domain_defaults($udom);
                   6102:     }
1.976     raeburn  6103:     if (ref($domdef{$tool}) eq 'HASH') {
                   6104:         if ($is_adv) {
                   6105:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   6106:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   6107:                     $access = 1;
                   6108:                 } else {
                   6109:                     $access = 0;
                   6110:                 }
                   6111:                 return $access;
                   6112:             }
                   6113:         }
                   6114:         if ($inststatus ne '') {
                   6115:             my ($hasaccess,$hasnoaccess);
                   6116:             foreach my $affiliation (split(/:/,$inststatus)) {
                   6117:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   6118:                     if ($domdef{$tool}{$affiliation}) {
                   6119:                         $hasaccess = 1;
                   6120:                     } else {
                   6121:                         $hasnoaccess = 1;
                   6122:                     }
                   6123:                 }
                   6124:             }
                   6125:             if ($hasaccess || $hasnoaccess) {
                   6126:                 if ($hasaccess) {
                   6127:                     $access = 1;
                   6128:                 } elsif ($hasnoaccess) {
                   6129:                     $access = 0; 
                   6130:                 }
                   6131:                 return $access;
                   6132:             }
                   6133:         } else {
                   6134:             if ($domdef{$tool}{'default'} ne '') {
                   6135:                 if ($domdef{$tool}{'default'}) {
                   6136:                     $access = 1;
                   6137:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   6138:                     $access = 0;
                   6139:                 }
                   6140:                 return $access;
                   6141:             }
                   6142:         }
                   6143:     } else {
1.1172.2.6  raeburn  6144:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  6145:             $access = 1;
                   6146:         } else {
                   6147:             $access = 0;
                   6148:         }
1.976     raeburn  6149:         return $access;
                   6150:     }
                   6151: }
                   6152: 
1.1050    raeburn  6153: sub is_course_owner {
                   6154:     my ($cdom,$cnum,$udom,$uname) = @_;
                   6155:     if (($udom eq '') || ($uname eq '')) {
                   6156:         $udom = $env{'user.domain'};
                   6157:         $uname = $env{'user.name'};
                   6158:     }
                   6159:     unless (($udom eq '') || ($uname eq '')) {
                   6160:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   6161:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   6162:                 return 1;
                   6163:             } else {
                   6164:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   6165:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   6166:                     return 1;
                   6167:                 }
                   6168:             }
                   6169:         }
                   6170:     }
                   6171:     return;
                   6172: }
                   6173: 
1.976     raeburn  6174: sub is_advanced_user {
                   6175:     my ($udom,$uname) = @_;
1.1085    raeburn  6176:     if ($udom ne '' && $uname ne '') {
                   6177:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  6178:             if (wantarray) {
                   6179:                 return ($env{'user.adv'},$env{'user.author'});
                   6180:             } else {
                   6181:                 return $env{'user.adv'};
                   6182:             }
1.1085    raeburn  6183:         }
                   6184:     }
1.976     raeburn  6185:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   6186:     my %allroles;
1.1128    raeburn  6187:     my ($is_adv,$is_author);
1.976     raeburn  6188:     foreach my $role (keys(%roleshash)) {
                   6189:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   6190:         my $area = '/'.$tdomain.'/'.$trest;
                   6191:         if ($sec ne '') {
                   6192:             $area .= '/'.$sec;
                   6193:         }
                   6194:         if (($area ne '') && ($trole ne '')) {
                   6195:             my $spec=$trole.'.'.$area;
                   6196:             if ($trole =~ /^cr\//) {
                   6197:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6198:             } elsif ($trole ne 'gr') {
                   6199:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6200:             }
1.1128    raeburn  6201:             if ($trole eq 'au') {
                   6202:                 $is_author = 1;
                   6203:             }
1.976     raeburn  6204:         }
                   6205:     }
                   6206:     foreach my $role (keys(%allroles)) {
                   6207:         last if ($is_adv);
                   6208:         foreach my $item (split(/:/,$allroles{$role})) {
                   6209:             if ($item ne '') {
                   6210:                 my ($privilege,$restrictions)=split(/&/,$item);
                   6211:                 if ($privilege eq 'adv') {
                   6212:                     $is_adv = 1;
                   6213:                     last;
                   6214:                 }
                   6215:             }
                   6216:         }
                   6217:     }
1.1128    raeburn  6218:     if (wantarray) {
                   6219:         return ($is_adv,$is_author);
                   6220:     }
1.976     raeburn  6221:     return $is_adv;
                   6222: }
1.798     raeburn  6223: 
1.1035    raeburn  6224: sub check_can_request {
1.1036    raeburn  6225:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  6226:     my $canreq = 0;
                   6227:     my ($types,$typename) = &Apache::loncommon::course_types();
                   6228:     my @options = ('approval','validate','autolimit');
                   6229:     my $optregex = join('|',@options);
                   6230:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   6231:         foreach my $type (@{$types}) {
                   6232:             if (&usertools_access($env{'user.name'},
                   6233:                                   $env{'user.domain'},
                   6234:                                   $type,undef,'requestcourses')) {
                   6235:                 $canreq ++;
1.1036    raeburn  6236:                 if (ref($request_domains) eq 'HASH') {
                   6237:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   6238:                 }
1.1035    raeburn  6239:                 if ($dom eq $env{'user.domain'}) {
                   6240:                     $can_request->{$type} = 1;
                   6241:                 }
                   6242:             }
                   6243:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   6244:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   6245:                 if (@curr > 0) {
1.1036    raeburn  6246:                     foreach my $item (@curr) {
                   6247:                         if (ref($request_domains) eq 'HASH') {
                   6248:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   6249:                             if ($otherdom ne '') {
                   6250:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   6251:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   6252:                                         push(@{$request_domains->{$type}},$otherdom);
                   6253:                                     }
                   6254:                                 } else {
                   6255:                                     push(@{$request_domains->{$type}},$otherdom);
                   6256:                                 }
                   6257:                             }
                   6258:                         }
                   6259:                     }
                   6260:                     unless($dom eq $env{'user.domain'}) {
                   6261:                         $canreq ++;
1.1035    raeburn  6262:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   6263:                             $can_request->{$type} = 1;
                   6264:                         }
                   6265:                     }
                   6266:                 }
                   6267:             }
                   6268:         }
                   6269:     }
                   6270:     return $canreq;
                   6271: }
                   6272: 
1.341     www      6273: # ---------------------------------------------- Custom access rule evaluation
                   6274: 
                   6275: sub customaccess {
                   6276:     my ($priv,$uri)=@_;
1.807     albertel 6277:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      6278:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 6279:     $udom = &LONCAPA::clean_domain($udom);
                   6280:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      6281:     my $access=0;
1.800     albertel 6282:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 6283: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   6284: 	if ($type eq 'user') {
                   6285: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 6286: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 6287: 		if ($tdom) {
                   6288: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   6289: 		}
1.896     albertel 6290: 		if ($tuname) {
                   6291: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 6292: 		}
                   6293: 		$access=($effect eq 'allow');
                   6294: 		last;
                   6295: 	    }
                   6296: 	} else {
                   6297: 	    if ($role) {
                   6298: 		if ($role ne $urole) { next; }
                   6299: 	    }
                   6300: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   6301: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   6302: 		if ($tdom) {
                   6303: 		    if ($tdom ne $udom) { next; }
                   6304: 		}
                   6305: 		if ($tcrs) {
                   6306: 		    if ($tcrs ne $ucrs) { next; }
                   6307: 		}
                   6308: 		if ($tsec) {
                   6309: 		    if ($tsec ne $usec) { next; }
                   6310: 		}
                   6311: 		$access=($effect eq 'allow');
                   6312: 		last;
                   6313: 	    }
                   6314: 	    if ($realm eq '' && $role eq '') {
                   6315: 		$access=($effect eq 'allow');
                   6316: 	    }
1.402     bowersj2 6317: 	}
1.341     www      6318:     }
                   6319:     return $access;
                   6320: }
                   6321: 
1.103     harris41 6322: # ------------------------------------------------- Check for a user privilege
1.12      www      6323: 
                   6324: sub allowed {
1.810     raeburn  6325:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 6326:     my $ver_orguri=$uri;
1.439     www      6327:     $uri=&deversion($uri);
1.152     www      6328:     my $orguri=$uri;
1.52      www      6329:     $uri=&declutter($uri);
1.809     raeburn  6330: 
1.810     raeburn  6331:     if ($priv eq 'evb') {
                   6332: # Evade communication block restrictions for specified role in a course
                   6333:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   6334:             return $1;
                   6335:         } else {
                   6336:             return;
                   6337:         }
                   6338:     }
                   6339: 
1.620     albertel 6340:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      6341: # Free bre access to adm and meta resources
1.775     albertel 6342:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 6343: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   6344: 	&& ($priv eq 'bre')) {
1.14      www      6345: 	return 'F';
1.159     www      6346:     }
                   6347: 
1.545     banghart 6348: # Free bre access to user's own portfolio contents
1.714     raeburn  6349:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  6350:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  6351: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  6352:         my %setters;
                   6353:         my ($startblock,$endblock) = 
                   6354:             &Apache::loncommon::blockcheck(\%setters,'port');
                   6355:         if ($startblock && $endblock) {
                   6356:             return 'B';
                   6357:         } else {
                   6358:             return 'F';
                   6359:         }
1.545     banghart 6360:     }
                   6361: 
1.762     raeburn  6362: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  6363:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   6364:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   6365:         if (exists($env{'request.course.id'})) {
                   6366:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6367:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6368:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   6369:                 my $courseprivid=$env{'request.course.id'};
                   6370:                 $courseprivid=~s/\_/\//;
                   6371:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   6372:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   6373:                     return $1; 
1.762     raeburn  6374:                 } else {
                   6375:                     if ($env{'request.course.sec'}) {
                   6376:                         $courseprivid.='/'.$env{'request.course.sec'};
                   6377:                     }
                   6378:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   6379:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   6380:                         return $2;
                   6381:                     }
1.714     raeburn  6382:                 }
                   6383:             }
                   6384:         }
                   6385:     }
                   6386: 
1.159     www      6387: # Free bre to public access
                   6388: 
                   6389:     if ($priv eq 'bre') {
1.238     www      6390:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 6391: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      6392:            return 'F'; 
                   6393:         }
1.238     www      6394:         if ($copyright eq 'priv') {
                   6395:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6396: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      6397: 		return '';
                   6398:             }
                   6399:         }
                   6400:         if ($copyright eq 'domain') {
                   6401:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6402: 	    unless (($env{'user.domain'} eq $1) ||
                   6403:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      6404: 		return '';
                   6405:             }
1.262     matthew  6406:         }
1.620     albertel 6407:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  6408:             # Library role, so allow browsing of resources in this domain.
                   6409:             return 'F';
1.238     www      6410:         }
1.341     www      6411:         if ($copyright eq 'custom') {
                   6412: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   6413:         }
1.14      www      6414:     }
1.264     matthew  6415:     # Domain coordinator is trying to create a course
1.620     albertel 6416:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  6417:         # uri is the requested domain in this case.
                   6418:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  6419:         # a role of dc for the domain in question.
1.620     albertel 6420:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  6421:     }
1.29      www      6422: 
1.52      www      6423:     my $thisallowed='';
                   6424:     my $statecond=0;
                   6425:     my $courseprivid='';
                   6426: 
1.1039    raeburn  6427:     my $ownaccess;
1.1043    raeburn  6428:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  6429:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   6430:         if ($uri eq '') {
                   6431:             $ownaccess = 1;
                   6432:         } else {
                   6433:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   6434:                 my $udom = $env{'user.domain'};
                   6435:                 my $uname = $env{'user.name'};
                   6436:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   6437:                     $ownaccess = 1;
1.1040    raeburn  6438:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  6439:                     unless ($uri =~ m{\.\./}) {
                   6440:                         $ownaccess = 1;
                   6441:                     }
                   6442:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   6443:                     my $now = time;
                   6444:                     if ($uri =~ m{^([^/]+)/?$}) {
                   6445:                         my $adom = $1;
                   6446:                         foreach my $key (keys(%env)) {
1.1042    raeburn  6447:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  6448:                                 my ($start,$end) = split('.',$env{$key});
                   6449:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6450:                                     $ownaccess = 1;
                   6451:                                     last;
                   6452:                                 }
                   6453:                             }
                   6454:                         }
                   6455:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   6456:                         my $adom = $1;
                   6457:                         my $aname = $2;
1.1042    raeburn  6458:                         foreach my $role ('ca','aa') { 
                   6459:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   6460:                                 my ($start,$end) =
                   6461:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   6462:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6463:                                     $ownaccess = 1;
                   6464:                                     last;
                   6465:                                 }
1.1039    raeburn  6466:                             }
                   6467:                         }
                   6468:                     }
                   6469:                 }
                   6470:             }
                   6471:         }
                   6472:     }
                   6473: 
1.52      www      6474: # Course
                   6475: 
1.620     albertel 6476:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6477:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6478:             $thisallowed.=$1;
                   6479:         }
1.52      www      6480:     }
1.29      www      6481: 
1.52      www      6482: # Domain
                   6483: 
1.620     albertel 6484:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 6485:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6486:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6487:             $thisallowed.=$1;
                   6488:         }
1.12      www      6489:     }
1.52      www      6490: 
1.1141    raeburn  6491: # User who is not author or co-author might still be able to edit
                   6492: # resource of an author in the domain (e.g., if Domain Coordinator).
                   6493:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   6494:         (&allowed('mdc',$env{'request.course.id'}))) {
                   6495:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   6496:             $thisallowed.=$1;
                   6497:         }
                   6498:     }
                   6499: 
1.52      www      6500: # Course: uri itself is a course
1.66      www      6501:     my $courseuri=$uri;
                   6502:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      6503:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      6504: 
1.620     albertel 6505:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 6506:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6507:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6508:             $thisallowed.=$1;
                   6509:         }
1.12      www      6510:     }
1.29      www      6511: 
1.665     albertel 6512: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 6513: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 6514:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 6515: 	$thisallowed='';
1.671     raeburn  6516:         my ($match)=&is_on_map($uri);
                   6517:         if ($match) {
                   6518:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   6519:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6520:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6521:                 if (@blockers > 0) {
                   6522:                     $thisallowed = 'B';
                   6523:                 } else {
                   6524:                     $thisallowed.=$1;
                   6525:                 }
1.671     raeburn  6526:             }
                   6527:         } else {
1.705     albertel 6528:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  6529:             if ($refuri) {
                   6530:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  6531:                     $thisallowed='F';
1.671     raeburn  6532:                 } else {
                   6533:                     $refuri=&declutter($refuri);
                   6534:                     my ($match) = &is_on_map($refuri);
                   6535:                     if ($match) {
1.1162    raeburn  6536:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6537:                         if (@blockers > 0) {
                   6538:                             $thisallowed = 'B';
                   6539:                         } else {
                   6540:                             $thisallowed='F';
                   6541:                         }
1.671     raeburn  6542:                     }
1.669     raeburn  6543:                 }
1.671     raeburn  6544:             }
                   6545:         }
1.314     www      6546:     }
1.492     albertel 6547: 
1.766     albertel 6548:     if ($priv eq 'bre'
                   6549: 	&& $thisallowed ne 'F' 
                   6550: 	&& $thisallowed ne '2'
                   6551: 	&& &is_portfolio_url($uri)) {
                   6552: 	$thisallowed = &portfolio_access($uri);
                   6553:     }
                   6554:     
1.52      www      6555: # Full access at system, domain or course-wide level? Exit.
1.29      www      6556:     if ($thisallowed=~/F/) {
                   6557: 	return 'F';
                   6558:     }
                   6559: 
1.52      www      6560: # If this is generating or modifying users, exit with special codes
1.29      www      6561: 
1.643     www      6562:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   6563: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 6564: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      6565: # no author name given, so this just checks on the general right to make a co-author in this domain
                   6566: 	    unless ($auname) { return $thisallowed; }
                   6567: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 6568: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   6569: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   6570: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   6571: 	}
1.52      www      6572: 	return $thisallowed;
                   6573:     }
                   6574: #
1.103     harris41 6575: # Gathered so far: system, domain and course wide privileges
1.52      www      6576: #
                   6577: # Course: See if uri or referer is an individual resource that is part of 
                   6578: # the course
                   6579: 
1.620     albertel 6580:     if ($env{'request.course.id'}) {
1.232     www      6581: 
1.620     albertel 6582:        $courseprivid=$env{'request.course.id'};
                   6583:        if ($env{'request.course.sec'}) {
                   6584:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      6585:        }
                   6586:        $courseprivid=~s/\_/\//;
                   6587:        my $checkreferer=1;
1.232     www      6588:        my ($match,$cond)=&is_on_map($uri);
                   6589:        if ($match) {
                   6590:            $statecond=$cond;
1.620     albertel 6591:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6592:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6593:                my $value = $1;
                   6594:                if ($priv eq 'bre') {
                   6595:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6596:                    if (@blockers > 0) {
                   6597:                        $thisallowed = 'B';
                   6598:                    } else {
                   6599:                        $thisallowed.=$value;
                   6600:                    }
                   6601:                } else {
                   6602:                    $thisallowed.=$value;
                   6603:                }
1.52      www      6604:                $checkreferer=0;
                   6605:            }
1.29      www      6606:        }
1.83      www      6607:        
1.148     www      6608:        if ($checkreferer) {
1.620     albertel 6609: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      6610:             unless ($refuri) {
1.800     albertel 6611:                 foreach my $key (keys(%env)) {
                   6612: 		    if ($key=~/^httpref\..*\*/) {
                   6613: 			my $pattern=$key;
1.156     www      6614:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      6615:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   6616:                         $pattern=~s/\//\\\//g;
1.152     www      6617:                         if ($orguri=~/$pattern/) {
1.800     albertel 6618: 			    $refuri=$env{$key};
1.148     www      6619:                         }
                   6620:                     }
1.191     harris41 6621:                 }
1.148     www      6622:             }
1.232     www      6623: 
1.148     www      6624:          if ($refuri) { 
1.152     www      6625: 	  $refuri=&declutter($refuri);
1.232     www      6626:           my ($match,$cond)=&is_on_map($refuri);
                   6627:             if ($match) {
                   6628:               my $refstatecond=$cond;
1.620     albertel 6629:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6630:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6631:                   my $value = $1;
                   6632:                   if ($priv eq 'bre') {
                   6633:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6634:                       if (@blockers > 0) {
                   6635:                           $thisallowed = 'B';
                   6636:                       } else {
                   6637:                           $thisallowed.=$value;
                   6638:                       }
                   6639:                   } else {
                   6640:                       $thisallowed.=$value;
                   6641:                   }
1.53      www      6642:                   $uri=$refuri;
                   6643:                   $statecond=$refstatecond;
1.52      www      6644:               }
                   6645:           }
1.148     www      6646:         }
1.29      www      6647:        }
1.52      www      6648:    }
1.29      www      6649: 
1.52      www      6650: #
1.103     harris41 6651: # Gathered now: all privileges that could apply, and condition number
1.52      www      6652: # 
                   6653: #
                   6654: # Full or no access?
                   6655: #
1.29      www      6656: 
1.52      www      6657:     if ($thisallowed=~/F/) {
                   6658: 	return 'F';
                   6659:     }
1.29      www      6660: 
1.52      www      6661:     unless ($thisallowed) {
                   6662:         return '';
                   6663:     }
1.29      www      6664: 
1.52      www      6665: # Restrictions exist, deal with them
                   6666: #
                   6667: #   C:according to course preferences
                   6668: #   R:according to resource settings
                   6669: #   L:unless locked
                   6670: #   X:according to user session state
                   6671: #
                   6672: 
                   6673: # Possibly locked functionality, check all courses
1.54      www      6674: # Locks might take effect only after 10 minutes cache expiration for other
                   6675: # courses, and 2 minutes for current course
1.52      www      6676: 
                   6677:     my $envkey;
                   6678:     if ($thisallowed=~/L/) {
1.1000    raeburn  6679:         foreach $envkey (keys(%env)) {
1.54      www      6680:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   6681:                my $courseid=$2;
                   6682:                my $roleid=$1.'.'.$2;
1.92      www      6683:                $courseid=~s/^\///;
1.54      www      6684:                my $expiretime=600;
1.620     albertel 6685:                if ($env{'request.role'} eq $roleid) {
1.54      www      6686: 		  $expiretime=120;
                   6687:                }
                   6688: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   6689:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 6690:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 6691: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      6692:                }
1.620     albertel 6693:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6694:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   6695: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   6696:                        &log($env{'user.domain'},$env{'user.name'},
                   6697:                             $env{'user.home'},
1.57      www      6698:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      6699:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6700:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6701: 		       return '';
                   6702:                    }
                   6703:                }
1.620     albertel 6704:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6705:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   6706: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   6707:                        &log($env{'user.domain'},$env{'user.name'},
                   6708:                             $env{'user.home'},
1.57      www      6709:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      6710:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6711:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6712: 		       return '';
                   6713:                    }
                   6714:                }
                   6715: 	   }
1.29      www      6716:        }
1.52      www      6717:     }
                   6718:    
                   6719: #
                   6720: # Rest of the restrictions depend on selected course
                   6721: #
                   6722: 
1.620     albertel 6723:     unless ($env{'request.course.id'}) {
1.766     albertel 6724: 	if ($thisallowed eq 'A') {
                   6725: 	    return 'A';
1.814     raeburn  6726:         } elsif ($thisallowed eq 'B') {
                   6727:             return 'B';
1.766     albertel 6728: 	} else {
                   6729: 	    return '1';
                   6730: 	}
1.52      www      6731:     }
1.29      www      6732: 
1.52      www      6733: #
                   6734: # Now user is definitely in a course
                   6735: #
1.53      www      6736: 
                   6737: 
                   6738: # Course preferences
                   6739: 
                   6740:    if ($thisallowed=~/C/) {
1.620     albertel 6741:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   6742:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   6743:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 6744: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  6745: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6746: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6747: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   6748: 			$env{'request.course.id'});
                   6749: 	   }
1.237     www      6750:            return '';
                   6751:        }
                   6752: 
1.620     albertel 6753:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 6754: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  6755: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6756: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   6757: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   6758: 			$env{'request.course.id'});
                   6759: 	   }
1.54      www      6760:            return '';
                   6761:        }
1.53      www      6762:    }
                   6763: 
                   6764: # Resource preferences
                   6765: 
                   6766:    if ($thisallowed=~/R/) {
1.620     albertel 6767:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 6768:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  6769: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6770: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6771: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   6772: 	   }
                   6773: 	   return '';
1.54      www      6774:        }
1.53      www      6775:    }
1.30      www      6776: 
1.246     www      6777: # Restricted by state or randomout?
1.30      www      6778: 
1.52      www      6779:    if ($thisallowed=~/X/) {
1.620     albertel 6780:       if ($env{'acc.randomout'}) {
1.579     albertel 6781: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 6782:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      6783:             return ''; 
                   6784:          }
1.247     www      6785:       }
                   6786:       if (&condval($statecond)) {
1.52      www      6787: 	 return '2';
                   6788:       } else {
                   6789:          return '';
                   6790:       }
                   6791:    }
1.30      www      6792: 
1.766     albertel 6793:     if ($thisallowed eq 'A') {
                   6794: 	return 'A';
1.814     raeburn  6795:     } elsif ($thisallowed eq 'B') {
                   6796:         return 'B';
1.766     albertel 6797:     }
1.52      www      6798:    return 'F';
1.232     www      6799: }
1.1162    raeburn  6800: 
1.1172.2.13  raeburn  6801: # ------------------------------------------- Check construction space access
                   6802: 
                   6803: sub constructaccess {
                   6804:     my ($url,$setpriv)=@_;
                   6805: 
                   6806: # We do not allow editing of previous versions of files
                   6807:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   6808: 
                   6809: # Get username and domain from URL
                   6810:     my ($ownername,$ownerdomain,$ownerhome);
                   6811: 
                   6812:     ($ownerdomain,$ownername) =
                   6813:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
                   6814: 
                   6815: # The URL does not really point to any authorspace, forget it
                   6816:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   6817: 
                   6818: # Now we need to see if the user has access to the authorspace of
                   6819: # $ownername at $ownerdomain
                   6820: 
                   6821:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   6822: # Real author for this?
                   6823:        $ownerhome = $env{'user.home'};
                   6824:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   6825:           return ($ownername,$ownerdomain,$ownerhome);
                   6826:        }
                   6827:     } else {
                   6828: # Co-author for this?
                   6829:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   6830:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   6831:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   6832:             return ($ownername,$ownerdomain,$ownerhome);
                   6833:         }
                   6834:     }
                   6835: 
                   6836: # We don't have any access right now. If we are not possibly going to do anything about this,
                   6837: # we might as well leave
                   6838:    unless ($setpriv) { return ''; }
                   6839: 
                   6840: # Backdoor access?
                   6841:     my $allowed=&allowed('eco',$ownerdomain);
                   6842: # Nope
                   6843:     unless ($allowed) { return ''; }
                   6844: # Looks like we may have access, but could be locked by the owner of the construction space
                   6845:     if ($allowed eq 'U') {
                   6846:         my %blocked=&get('environment',['domcoord.author'],
                   6847:                          $ownerdomain,$ownername);
                   6848: # Is blocked by owner
                   6849:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   6850:     }
                   6851:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   6852: # Grant temporary access
                   6853:         my $then=$env{'user.login.time'};
                   6854:         my $update==$env{'user.update.time'};
                   6855:         if (!$update) { $update = $then; }
                   6856:         my $refresh=$env{'user.refresh.time'};
                   6857:         if (!$refresh) { $refresh = $update; }
                   6858:         my $now = time;
                   6859:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   6860:                            $now,'ca','constructaccess');
                   6861:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   6862:         return($ownername,$ownerdomain,$ownerhome);
                   6863:     }
                   6864: # No business here
                   6865:     return '';
                   6866: }
                   6867: 
1.1162    raeburn  6868: sub get_comm_blocks {
                   6869:     my ($cdom,$cnum) = @_;
                   6870:     if ($cdom eq '' || $cnum eq '') {
                   6871:         return unless ($env{'request.course.id'});
                   6872:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6873:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6874:     }
                   6875:     my %commblocks;
                   6876:     my $hashid=$cdom.'_'.$cnum;
                   6877:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   6878:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   6879:         %commblocks = %{$blocksref};
                   6880:     } else {
                   6881:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   6882:         my $cachetime = 600;
                   6883:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   6884:     }
                   6885:     return %commblocks;
                   6886: }
                   6887: 
                   6888: sub has_comm_blocking {
                   6889:     my ($priv,$symb,$uri,$blocks) = @_;
                   6890:     return unless ($env{'request.course.id'});
                   6891:     return unless ($priv eq 'bre');
                   6892:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   6893:     my %commblocks;
                   6894:     if (ref($blocks) eq 'HASH') {
                   6895:         %commblocks = %{$blocks};
                   6896:     } else {
                   6897:         %commblocks = &get_comm_blocks();
                   6898:     }
                   6899:     return unless (keys(%commblocks) > 0);
                   6900:     if (!$symb) { $symb=&symbread($uri,1); }
                   6901:     my ($map,$resid,undef)=&decode_symb($symb);
                   6902:     my %tocheck = (
                   6903:                     maps      => $map,
                   6904:                     resources => $symb,
                   6905:                   );
                   6906:     my @blockers;
                   6907:     my $now = time;
1.1163    raeburn  6908:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1162    raeburn  6909:     foreach my $block (keys(%commblocks)) {
                   6910:         if ($block =~ /^(\d+)____(\d+)$/) {
                   6911:             my ($start,$end) = ($1,$2);
                   6912:             if ($start <= $now && $end >= $now) {
                   6913:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   6914:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   6915:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   6916:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
                   6917:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   6918:                                     push(@blockers,$block);
                   6919:                                 }
                   6920:                             }
                   6921:                         }
                   6922:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   6923:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
                   6924:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
                   6925:                                     push(@blockers,$block);
                   6926:                                 }
                   6927:                             }
                   6928:                         }
                   6929:                     }
                   6930:                 }
                   6931:             }
                   6932:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   6933:             my $item = $1;
1.1163    raeburn  6934:             my @to_test;
1.1162    raeburn  6935:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   6936:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   6937:                     my $check_interval;
                   6938:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
                   6939:                         my @interval;
                   6940:                         my $type = 'map';
                   6941:                         if ($item eq 'course') {
                   6942:                             $type = 'course';
                   6943:                             @interval=&EXT("resource.0.interval");
                   6944:                         } else {
                   6945:                             if ($item =~ /___\d+___/) {
                   6946:                                 $type = 'resource';
                   6947:                                 @interval=&EXT("resource.0.interval",$item);
1.1163    raeburn  6948:                                 if (ref($navmap)) {                        
                   6949:                                     my $res = $navmap->getBySymb($item); 
                   6950:                                     push(@to_test,$res);
                   6951:                                 }
1.1162    raeburn  6952:                             } else {
                   6953:                                 my $mapsymb = &symbread($item,1);
                   6954:                                 if ($mapsymb) {
                   6955:                                     if (ref($navmap)) {
                   6956:                                         my $mapres = $navmap->getBySymb($mapsymb);
1.1163    raeburn  6957:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
                   6958:                                         foreach my $res (@to_test) {
1.1162    raeburn  6959:                                             my $symb = $res->symb();
                   6960:                                             next if ($symb eq $mapsymb);
                   6961:                                             if ($symb ne '') {
                   6962:                                                 @interval=&EXT("resource.0.interval",$symb);
                   6963:                                                 last;
                   6964:                                             }
                   6965:                                         }
                   6966:                                     }
                   6967:                                 }
                   6968:                             }
                   6969:                         }
                   6970:                         if ($interval[0] =~ /\d+/) {
                   6971:                             my $first_access;
                   6972:                             if ($type eq 'resource') {
                   6973:                                 $first_access=&get_first_access($interval[1],$item);
                   6974:                             } elsif ($type eq 'map') {
                   6975:                                 $first_access=&get_first_access($interval[1],undef,$item);
                   6976:                             } else {
                   6977:                                 $first_access=&get_first_access($interval[1]);
                   6978:                             }
                   6979:                             if ($first_access) {
                   6980:                                 my $timesup = $first_access+$interval[0];
                   6981:                                 if ($timesup > $now) {
1.1163    raeburn  6982:                                     foreach my $res (@to_test) {
                   6983:                                         if ($res->is_problem()) {
                   6984:                                             if ($res->completable()) {
                   6985:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   6986:                                                     push(@blockers,$block);
                   6987:                                                 }
                   6988:                                                 last;
                   6989:                                             }
                   6990:                                         }
1.1162    raeburn  6991:                                     }
                   6992:                                 }
                   6993:                             }
                   6994:                         }
                   6995:                     }
                   6996:                 }
                   6997:             }
                   6998:         }
                   6999:     }
                   7000:     return @blockers;
                   7001: }
                   7002: 
                   7003: sub check_docs_block {
                   7004:     my ($docsblock,$tocheck) =@_;
                   7005:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
                   7006:         return;
                   7007:     }
                   7008:     if (ref($docsblock->{'maps'}) eq 'HASH') {
                   7009:         if ($tocheck->{'maps'}) {
                   7010:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
                   7011:                 return 1;
                   7012:             }
                   7013:         }
                   7014:     }
                   7015:     if (ref($docsblock->{'resources'}) eq 'HASH') {
                   7016:         if ($tocheck->{'resources'}) {
                   7017:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
                   7018:                 return 1;
                   7019:             }
                   7020:         }
                   7021:     }
                   7022:     return;
                   7023: }
                   7024: 
1.1133    foxr     7025: #
                   7026: #   Removes the versino from a URI and
                   7027: #   splits it in to its filename and path to the filename.
                   7028: #   Seems like File::Basename could have done this more clearly.
                   7029: #   Parameters:
                   7030: #      $uri   - input URI
                   7031: #   Returns:
                   7032: #     Two element list consisting of 
                   7033: #     $pathname  - the URI up to and excluding the trailing /
                   7034: #     $filename  - The part of the URI following the last /
                   7035: #  NOTE:
                   7036: #    Another realization of this is simply:
                   7037: #    use File::Basename;
                   7038: #    ...
                   7039: #    $uri = shift;
                   7040: #    $filename = basename($uri);
                   7041: #    $path     = dirname($uri);
                   7042: #    return ($filename, $path);
                   7043: #
                   7044: #     The implementation below is probably faster however.
                   7045: #
1.710     albertel 7046: sub split_uri_for_cond {
                   7047:     my $uri=&deversion(&declutter(shift));
                   7048:     my @uriparts=split(/\//,$uri);
                   7049:     my $filename=pop(@uriparts);
                   7050:     my $pathname=join('/',@uriparts);
                   7051:     return ($pathname,$filename);
                   7052: }
1.232     www      7053: # --------------------------------------------------- Is a resource on the map?
                   7054: 
                   7055: sub is_on_map {
1.710     albertel 7056:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 7057:     #Trying to find the conditional for the file
1.620     albertel 7058:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 7059: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      7060:     if ($match) {
1.289     bowersj2 7061: 	return (1,$1);
                   7062:     } else {
1.434     www      7063: 	return (0,0);
1.289     bowersj2 7064:     }
1.12      www      7065: }
                   7066: 
1.427     www      7067: # --------------------------------------------------------- Get symb from alias
                   7068: 
                   7069: sub get_symb_from_alias {
                   7070:     my $symb=shift;
                   7071:     my ($map,$resid,$url)=&decode_symb($symb);
                   7072: # Already is a symb
                   7073:     if ($url) { return $symb; }
                   7074: # Must be an alias
                   7075:     my $aliassymb='';
                   7076:     my %bighash;
1.620     albertel 7077:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      7078:                             &GDBM_READER(),0640)) {
                   7079:         my $rid=$bighash{'mapalias_'.$symb};
                   7080: 	if ($rid) {
                   7081: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 7082: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   7083: 				    $resid,$bighash{'src_'.$rid});
1.427     www      7084: 	}
                   7085:         untie %bighash;
                   7086:     }
                   7087:     return $aliassymb;
                   7088: }
                   7089: 
1.12      www      7090: # ----------------------------------------------------------------- Define Role
                   7091: 
                   7092: sub definerole {
                   7093:   if (allowed('mcr','/')) {
                   7094:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 7095:     foreach my $role (split(':',$sysrole)) {
                   7096: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7097:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   7098:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   7099: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7100:                return "refused:s:$crole&$cqual"; 
                   7101:             }
                   7102:         }
1.191     harris41 7103:     }
1.800     albertel 7104:     foreach my $role (split(':',$domrole)) {
                   7105: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7106:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   7107:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   7108: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      7109:                return "refused:d:$crole&$cqual"; 
                   7110:             }
                   7111:         }
1.191     harris41 7112:     }
1.800     albertel 7113:     foreach my $role (split(':',$courole)) {
                   7114: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7115:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   7116:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   7117: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7118:                return "refused:c:$crole&$cqual"; 
                   7119:             }
                   7120:         }
1.191     harris41 7121:     }
1.620     albertel 7122:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   7123:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7124: 	        "rolesdef_$rolename=".
                   7125:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 7126:     return reply($command,$env{'user.home'});
1.12      www      7127:   } else {
                   7128:     return 'refused';
                   7129:   }
1.105     harris41 7130: }
                   7131: 
                   7132: # ---------------- Make a metadata query against the network of library servers
                   7133: 
                   7134: sub metadata_query {
1.244     matthew  7135:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 7136:     my %rhash;
1.845     albertel 7137:     my %libserv = &all_library();
1.244     matthew  7138:     my @server_list = (defined($server_array) ? @$server_array
                   7139:                                               : keys(%libserv) );
                   7140:     for my $server (@server_list) {
1.118     harris41 7141: 	unless ($custom or $customshow) {
                   7142: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   7143: 	    $rhash{$server}=$reply;
                   7144: 	}
                   7145: 	else {
                   7146: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   7147: 			     &escape($custom).':'.&escape($customshow),
                   7148: 			     $server);
                   7149: 	    $rhash{$server}=$reply;
                   7150: 	}
1.112     harris41 7151:     }
1.118     harris41 7152:     return \%rhash;
1.240     www      7153: }
                   7154: 
                   7155: # ----------------------------------------- Send log queries and wait for reply
                   7156: 
                   7157: sub log_query {
                   7158:     my ($uname,$udom,$query,%filters)=@_;
                   7159:     my $uhome=&homeserver($uname,$udom);
                   7160:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 7161:     my $uhost=&hostname($uhome);
1.800     albertel 7162:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      7163:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   7164:                        $uhome);
1.479     albertel 7165:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      7166:     return get_query_reply($queryid);
                   7167: }
                   7168: 
1.818     raeburn  7169: # -------------------------- Update MySQL table for portfolio file
                   7170: 
                   7171: sub update_portfolio_table {
1.821     raeburn  7172:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  7173:     if ($group ne '') {
                   7174:         $file_name =~s /^\Q$group\E//;
                   7175:     }
1.818     raeburn  7176:     my $homeserver = &homeserver($uname,$udom);
                   7177:     my $queryid=
1.821     raeburn  7178:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   7179:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  7180:     my $reply = &get_query_reply($queryid);
                   7181:     return $reply;
                   7182: }
                   7183: 
1.899     raeburn  7184: # -------------------------- Update MySQL allusers table
                   7185: 
                   7186: sub update_allusers_table {
                   7187:     my ($uname,$udom,$names) = @_;
                   7188:     my $homeserver = &homeserver($uname,$udom);
                   7189:     my $queryid=
                   7190:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   7191:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   7192:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   7193:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   7194:                'generation='.&escape($names->{'generation'}).'%%'.
                   7195:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   7196:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  7197:     return;
1.899     raeburn  7198: }
                   7199: 
1.508     raeburn  7200: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  7201: 
                   7202: sub fetch_enrollment_query {
1.511     raeburn  7203:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  7204:     my $homeserver;
1.547     raeburn  7205:     my $maxtries = 1;
1.508     raeburn  7206:     if ($context eq 'automated') {
                   7207:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  7208:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  7209:     } else {
                   7210:         $homeserver = &homeserver($cnum,$dom);
                   7211:     }
1.838     albertel 7212:     my $host=&hostname($homeserver);
1.506     raeburn  7213:     my $cmd = '';
1.1000    raeburn  7214:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 7215:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  7216:     }
                   7217:     $cmd =~ s/%%$//;
                   7218:     $cmd = &escape($cmd);
                   7219:     my $query = 'fetchenrollment';
1.620     albertel 7220:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  7221:     unless ($queryid=~/^\Q$host\E\_/) { 
                   7222:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   7223:         return 'error: '.$queryid;
                   7224:     }
1.506     raeburn  7225:     my $reply = &get_query_reply($queryid);
1.547     raeburn  7226:     my $tries = 1;
                   7227:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7228:         $reply = &get_query_reply($queryid);
                   7229:         $tries ++;
                   7230:     }
1.526     raeburn  7231:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 7232:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  7233:     } else {
1.901     albertel 7234:         my @responses = split(/:/,$reply);
1.515     raeburn  7235:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 7236:             foreach my $line (@responses) {
                   7237:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  7238:                 $$replyref{$key} = $value;
                   7239:             }
                   7240:         } else {
1.1117    foxr     7241:             my $pathname = LONCAPA::tempdir();
1.800     albertel 7242:             foreach my $line (@responses) {
                   7243:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  7244:                 $$replyref{$key} = $value;
                   7245:                 if ($value > 0) {
1.800     albertel 7246:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   7247:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  7248:                         my $destname = $pathname.'/'.$filename;
                   7249:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  7250:                         if ($xml_classlist =~ /^error/) {
                   7251:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   7252:                         } else {
1.506     raeburn  7253:                             if ( open(FILE,">$destname") ) {
                   7254:                                 print FILE &unescape($xml_classlist);
                   7255:                                 close(FILE);
1.526     raeburn  7256:                             } else {
                   7257:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  7258:                             }
                   7259:                         }
                   7260:                     }
                   7261:                 }
                   7262:             }
                   7263:         }
                   7264:         return 'ok';
                   7265:     }
                   7266:     return 'error';
                   7267: }
                   7268: 
1.242     www      7269: sub get_query_reply {
                   7270:     my $queryid=shift;
1.1117    foxr     7271:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      7272:     my $reply='';
                   7273:     for (1..100) {
                   7274: 	sleep 2;
                   7275:         if (-e $replyfile.'.end') {
1.448     albertel 7276: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 7277: 		$reply = join('',<$fh>);
                   7278: 		close($fh);
1.240     www      7279: 	   } else { return 'error: reply_file_error'; }
1.242     www      7280:            return &unescape($reply);
                   7281: 	}
1.240     www      7282:     }
1.242     www      7283:     return 'timeout:'.$queryid;
1.240     www      7284: }
                   7285: 
                   7286: sub courselog_query {
1.241     www      7287: #
                   7288: # possible filters:
                   7289: # url: url or symb
                   7290: # username
                   7291: # domain
                   7292: # action: view, submit, grade
                   7293: # start: timestamp
                   7294: # end: timestamp
                   7295: #
1.240     www      7296:     my (%filters)=@_;
1.620     albertel 7297:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      7298:     if ($filters{'url'}) {
                   7299: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   7300:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   7301:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   7302:     }
1.620     albertel 7303:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7304:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      7305:     return &log_query($cname,$cdom,'courselog',%filters);
                   7306: }
                   7307: 
                   7308: sub userlog_query {
1.858     raeburn  7309: #
                   7310: # possible filters:
                   7311: # action: log check role
                   7312: # start: timestamp
                   7313: # end: timestamp
                   7314: #
1.240     www      7315:     my ($uname,$udom,%filters)=@_;
                   7316:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      7317: }
                   7318: 
1.506     raeburn  7319: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   7320: 
                   7321: sub auto_run {
1.508     raeburn  7322:     my ($cnum,$cdom) = @_;
1.876     raeburn  7323:     my $response = 0;
                   7324:     my $settings;
                   7325:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   7326:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   7327:         $settings = $domconfig{'autoenroll'};
                   7328:         if ($settings->{'run'} eq '1') {
                   7329:             $response = 1;
                   7330:         }
                   7331:     } else {
1.934     raeburn  7332:         my $homeserver;
                   7333:         if (&is_course($cdom,$cnum)) {
                   7334:             $homeserver = &homeserver($cnum,$cdom);
                   7335:         } else {
                   7336:             $homeserver = &domain($cdom,'primary');
                   7337:         }
                   7338:         if ($homeserver ne 'no_host') {
                   7339:             $response = &reply('autorun:'.$cdom,$homeserver);
                   7340:         }
1.876     raeburn  7341:     }
1.506     raeburn  7342:     return $response;
                   7343: }
1.776     albertel 7344: 
1.506     raeburn  7345: sub auto_get_sections {
1.508     raeburn  7346:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  7347:     my $homeserver;
                   7348:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   7349:         $homeserver = &homeserver($cnum,$cdom);
                   7350:     }
                   7351:     if (!defined($homeserver)) { 
                   7352:         if ($cdom =~ /^$match_domain$/) {
                   7353:             $homeserver = &domain($cdom,'primary');
                   7354:         }
                   7355:     }
                   7356:     my @secs;
                   7357:     if (defined($homeserver)) {
                   7358:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   7359:         unless ($response eq 'refused') {
                   7360:             @secs = split(/:/,$response);
                   7361:         }
1.506     raeburn  7362:     }
                   7363:     return @secs;
                   7364: }
1.776     albertel 7365: 
1.506     raeburn  7366: sub auto_new_course {
1.1099    raeburn  7367:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  7368:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  7369:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  7370:     return $response;
                   7371: }
1.776     albertel 7372: 
1.506     raeburn  7373: sub auto_validate_courseID {
1.508     raeburn  7374:     my ($cnum,$cdom,$inst_course_id) = @_;
                   7375:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  7376:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  7377:     return $response;
                   7378: }
1.776     albertel 7379: 
1.1007    raeburn  7380: sub auto_validate_instcode {
1.1020    raeburn  7381:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  7382:     my ($homeserver,$response);
                   7383:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7384:         $homeserver = &homeserver($cnum,$cdom);
                   7385:     }
                   7386:     if (!defined($homeserver)) {
                   7387:         if ($cdom =~ /^$match_domain$/) {
                   7388:             $homeserver = &domain($cdom,'primary');
                   7389:         }
                   7390:     }
1.1065    raeburn  7391:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   7392:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1027    raeburn  7393:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
                   7394:     return ($outcome,$description);
1.1007    raeburn  7395: }
                   7396: 
1.506     raeburn  7397: sub auto_create_password {
1.873     raeburn  7398:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   7399:     my ($homeserver,$response);
1.506     raeburn  7400:     my $create_passwd = 0;
                   7401:     my $authchk = '';
1.873     raeburn  7402:     if ($udom =~ /^$match_domain$/) {
                   7403:         $homeserver = &domain($udom,'primary');
                   7404:     }
                   7405:     if ($homeserver eq '') {
                   7406:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7407:             $homeserver = &homeserver($cnum,$cdom);
                   7408:         }
                   7409:     }
                   7410:     if ($homeserver eq '') {
                   7411:         $authchk = 'nodomain';
1.506     raeburn  7412:     } else {
1.873     raeburn  7413:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   7414:         if ($response eq 'refused') {
                   7415:             $authchk = 'refused';
                   7416:         } else {
1.901     albertel 7417:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  7418:         }
1.506     raeburn  7419:     }
                   7420:     return ($authparam,$create_passwd,$authchk);
                   7421: }
                   7422: 
1.706     raeburn  7423: sub auto_photo_permission {
                   7424:     my ($cnum,$cdom,$students) = @_;
                   7425:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 7426:     my ($outcome,$perm_reqd,$conditions) = 
                   7427: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 7428:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7429: 	return (undef,undef);
                   7430:     }
1.706     raeburn  7431:     return ($outcome,$perm_reqd,$conditions);
                   7432: }
                   7433: 
                   7434: sub auto_checkphotos {
                   7435:     my ($uname,$udom,$pid) = @_;
                   7436:     my $homeserver = &homeserver($uname,$udom);
                   7437:     my ($result,$resulttype);
                   7438:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 7439: 				   &escape($uname).':'.&escape($pid),
                   7440: 				   $homeserver));
1.709     albertel 7441:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7442: 	return (undef,undef);
                   7443:     }
1.706     raeburn  7444:     if ($outcome) {
                   7445:         ($result,$resulttype) = split(/:/,$outcome);
                   7446:     } 
                   7447:     return ($result,$resulttype);
                   7448: }
                   7449: 
                   7450: sub auto_photochoice {
                   7451:     my ($cnum,$cdom) = @_;
                   7452:     my $homeserver = &homeserver($cnum,$cdom);
                   7453:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 7454: 						       &escape($cdom),
                   7455: 						       $homeserver)));
1.709     albertel 7456:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7457: 	return (undef,undef);
                   7458:     }
1.706     raeburn  7459:     return ($update,$comment);
                   7460: }
                   7461: 
                   7462: sub auto_photoupdate {
                   7463:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   7464:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 7465:     my $host=&hostname($homeserver);
1.706     raeburn  7466:     my $cmd = '';
                   7467:     my $maxtries = 1;
1.800     albertel 7468:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   7469:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  7470:     }
                   7471:     $cmd =~ s/%%$//;
                   7472:     $cmd = &escape($cmd);
                   7473:     my $query = 'institutionalphotos';
                   7474:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   7475:     unless ($queryid=~/^\Q$host\E\_/) {
                   7476:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   7477:         return 'error: '.$queryid;
                   7478:     }
                   7479:     my $reply = &get_query_reply($queryid);
                   7480:     my $tries = 1;
                   7481:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7482:         $reply = &get_query_reply($queryid);
                   7483:         $tries ++;
                   7484:     }
                   7485:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   7486:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   7487:     } else {
                   7488:         my @responses = split(/:/,$reply);
                   7489:         my $outcome = shift(@responses); 
                   7490:         foreach my $item (@responses) {
                   7491:             my ($key,$value) = split(/=/,$item);
                   7492:             $$photo{$key} = $value;
                   7493:         }
                   7494:         return $outcome;
                   7495:     }
                   7496:     return 'error';
                   7497: }
                   7498: 
1.521     raeburn  7499: sub auto_instcode_format {
1.793     albertel 7500:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   7501: 	$cat_order) = @_;
1.521     raeburn  7502:     my $courses = '';
1.772     raeburn  7503:     my @homeservers;
1.521     raeburn  7504:     if ($caller eq 'global') {
1.841     albertel 7505: 	my %servers = &get_servers($codedom,'library');
                   7506: 	foreach my $tryserver (keys(%servers)) {
                   7507: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7508: 		push(@homeservers,$tryserver);
                   7509: 	    }
1.584     raeburn  7510:         }
1.1022    raeburn  7511:     } elsif ($caller eq 'requests') {
                   7512:         if ($codedom =~ /^$match_domain$/) {
                   7513:             my $chome = &domain($codedom,'primary');
                   7514:             unless ($chome eq 'no_host') {
                   7515:                 push(@homeservers,$chome);
                   7516:             }
                   7517:         }
1.521     raeburn  7518:     } else {
1.772     raeburn  7519:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  7520:     }
1.793     albertel 7521:     foreach my $code (keys(%{$instcodes})) {
                   7522:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  7523:     }
                   7524:     chop($courses);
1.772     raeburn  7525:     my $ok_response = 0;
                   7526:     my $response;
                   7527:     while (@homeservers > 0 && $ok_response == 0) {
                   7528:         my $server = shift(@homeservers); 
                   7529:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   7530:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   7531:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 7532: 		split(/:/,$response);
1.772     raeburn  7533:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   7534:             push(@{$codetitles},&str2array($codetitles_str));
                   7535:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   7536:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   7537:             $ok_response = 1;
                   7538:         }
                   7539:     }
                   7540:     if ($ok_response) {
1.521     raeburn  7541:         return 'ok';
1.772     raeburn  7542:     } else {
                   7543:         return $response;
1.521     raeburn  7544:     }
                   7545: }
                   7546: 
1.792     raeburn  7547: sub auto_instcode_defaults {
                   7548:     my ($domain,$returnhash,$code_order) = @_;
                   7549:     my @homeservers;
1.841     albertel 7550: 
                   7551:     my %servers = &get_servers($domain,'library');
                   7552:     foreach my $tryserver (keys(%servers)) {
                   7553: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7554: 	    push(@homeservers,$tryserver);
                   7555: 	}
1.792     raeburn  7556:     }
1.841     albertel 7557: 
1.792     raeburn  7558:     my $response;
1.841     albertel 7559:     foreach my $server (@homeservers) {
1.792     raeburn  7560:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 7561:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   7562: 	
                   7563: 	foreach my $pair (split(/\&/,$response)) {
                   7564: 	    my ($name,$value)=split(/\=/,$pair);
                   7565: 	    if ($name eq 'code_order') {
                   7566: 		@{$code_order} = split(/\&/,&unescape($value));
                   7567: 	    } else {
                   7568: 		$returnhash->{&unescape($name)}=&unescape($value);
                   7569: 	    }
                   7570: 	}
                   7571: 	return 'ok';
1.792     raeburn  7572:     }
1.841     albertel 7573: 
                   7574:     return $response;
1.1003    raeburn  7575: }
                   7576: 
                   7577: sub auto_possible_instcodes {
1.1007    raeburn  7578:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   7579:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   7580:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   7581:         return;
                   7582:     }
1.1003    raeburn  7583:     my (@homeservers,$uhome);
                   7584:     if (defined(&domain($domain,'primary'))) {
                   7585:         $uhome=&domain($domain,'primary');
                   7586:         push(@homeservers,&domain($domain,'primary'));
                   7587:     } else {
                   7588:         my %servers = &get_servers($domain,'library');
                   7589:         foreach my $tryserver (keys(%servers)) {
                   7590:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7591:                 push(@homeservers,$tryserver);
                   7592:             }
                   7593:         }
                   7594:     }
                   7595:     my $response;
                   7596:     foreach my $server (@homeservers) {
                   7597:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   7598:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  7599:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   7600:             split(':',$response);
                   7601:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   7602:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  7603:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  7604:             my ($name,$value)=split('=',$item);
                   7605:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7606:         }
                   7607:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  7608:             my ($name,$value)=split('=',$item);
                   7609:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7610:         }
                   7611:         return 'ok';
                   7612:     }
                   7613:     return $response;
                   7614: }
1.792     raeburn  7615: 
1.1010    raeburn  7616: sub auto_courserequest_checks {
                   7617:     my ($dom) = @_;
1.1020    raeburn  7618:     my ($homeserver,%validations);
                   7619:     if ($dom =~ /^$match_domain$/) {
                   7620:         $homeserver = &domain($dom,'primary');
                   7621:     }
                   7622:     unless ($homeserver eq 'no_host') {
                   7623:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   7624:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   7625:             my @items = split(/&/,$response);
                   7626:             foreach my $item (@items) {
                   7627:                 my ($key,$value) = split('=',$item);
                   7628:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   7629:             }
                   7630:         }
                   7631:     }
1.1010    raeburn  7632:     return %validations; 
                   7633: }
                   7634: 
1.1020    raeburn  7635: sub auto_courserequest_validation {
                   7636:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   7637:     my ($homeserver,$response);
                   7638:     if ($dom =~ /^$match_domain$/) {
                   7639:         $homeserver = &domain($dom,'primary');
                   7640:     }
                   7641:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  7642:           
1.1020    raeburn  7643:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  7644:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  7645:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   7646:                                     $homeserver));
                   7647:     }
                   7648:     return $response;
                   7649: }
                   7650: 
1.777     albertel 7651: sub auto_validate_class_sec {
1.918     raeburn  7652:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  7653:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  7654:     my $ownerlist;
                   7655:     if (ref($owners) eq 'ARRAY') {
                   7656:         $ownerlist = join(',',@{$owners});
                   7657:     } else {
                   7658:         $ownerlist = $owners;
                   7659:     }
1.773     raeburn  7660:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  7661:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  7662:     return $response;
                   7663: }
                   7664: 
1.679     raeburn  7665: # ------------------------------------------------------- Course Group routines
                   7666: 
                   7667: sub get_coursegroups {
1.809     raeburn  7668:     my ($cdom,$cnum,$group,$namespace) = @_;
                   7669:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  7670: }
                   7671: 
1.679     raeburn  7672: sub modify_coursegroup {
                   7673:     my ($cdom,$cnum,$groupsettings) = @_;
                   7674:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   7675: }
                   7676: 
1.809     raeburn  7677: sub toggle_coursegroup_status {
                   7678:     my ($cdom,$cnum,$group,$action) = @_;
                   7679:     my ($from_namespace,$to_namespace);
                   7680:     if ($action eq 'delete') {
                   7681:         $from_namespace = 'coursegroups';
                   7682:         $to_namespace = 'deleted_groups';
                   7683:     } else {
                   7684:         $from_namespace = 'deleted_groups';
                   7685:         $to_namespace = 'coursegroups';
                   7686:     }
                   7687:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  7688:     if (my $tmp = &error(%curr_group)) {
                   7689:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   7690:         return ('read error',$tmp);
                   7691:     } else {
                   7692:         my %savedsettings = %curr_group; 
1.809     raeburn  7693:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  7694:         my $deloutcome;
                   7695:         if ($result eq 'ok') {
1.809     raeburn  7696:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  7697:         } else {
                   7698:             return ('write error',$result);
                   7699:         }
                   7700:         if ($deloutcome eq 'ok') {
                   7701:             return 'ok';
                   7702:         } else {
                   7703:             return ('delete error',$deloutcome);
                   7704:         }
                   7705:     }
                   7706: }
                   7707: 
1.679     raeburn  7708: sub modify_group_roles {
1.957     raeburn  7709:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  7710:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   7711:     my $role = 'gr/'.&escape($userprivs);
                   7712:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  7713:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  7714:     if ($result eq 'ok') {
                   7715:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   7716:     }
1.679     raeburn  7717:     return $result;
                   7718: }
                   7719: 
                   7720: sub modify_coursegroup_membership {
                   7721:     my ($cdom,$cnum,$membership) = @_;
                   7722:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   7723:     return $result;
                   7724: }
                   7725: 
1.682     raeburn  7726: sub get_active_groups {
                   7727:     my ($udom,$uname,$cdom,$cnum) = @_;
                   7728:     my $now = time;
                   7729:     my %groups = ();
                   7730:     foreach my $key (keys(%env)) {
1.811     albertel 7731:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  7732:             my ($start,$end) = split(/\./,$env{$key});
                   7733:             if (($end!=0) && ($end<$now)) { next; }
                   7734:             if (($start!=0) && ($start>$now)) { next; }
                   7735:             if ($1 eq $cdom && $2 eq $cnum) {
                   7736:                 $groups{$3} = $env{$key} ;
                   7737:             }
                   7738:         }
                   7739:     }
                   7740:     return %groups;
                   7741: }
                   7742: 
1.683     raeburn  7743: sub get_group_membership {
                   7744:     my ($cdom,$cnum,$group) = @_;
                   7745:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   7746: }
                   7747: 
                   7748: sub get_users_groups {
                   7749:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  7750:     my @usersgroups;
1.683     raeburn  7751:     my $cachetime=1800;
                   7752: 
                   7753:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  7754:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   7755:     if (defined($cached)) {
1.734     albertel 7756:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  7757:     } else {  
                   7758:         $grouplist = '';
1.816     raeburn  7759:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  7760:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  7761:         my $access_end = $env{'course.'.$courseid.
                   7762:                               '.default_enrollment_end_date'};
                   7763:         my $now = time;
                   7764:         foreach my $key (keys(%roleshash)) {
                   7765:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   7766:                 my $group = $1;
                   7767:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   7768:                     my $start = $2;
                   7769:                     my $end = $1;
                   7770:                     if ($start == -1) { next; } # deleted from group
                   7771:                     if (($start!=0) && ($start>$now)) { next; }
                   7772:                     if (($end!=0) && ($end<$now)) {
                   7773:                         if ($access_end && $access_end < $now) {
                   7774:                             if ($access_end - $end < 86400) {
                   7775:                                 push(@usersgroups,$group);
1.733     raeburn  7776:                             }
                   7777:                         }
1.817     raeburn  7778:                         next;
1.733     raeburn  7779:                     }
1.817     raeburn  7780:                     push(@usersgroups,$group);
1.683     raeburn  7781:                 }
                   7782:             }
                   7783:         }
1.817     raeburn  7784:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   7785:         $grouplist = join(':',@usersgroups);
                   7786:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  7787:     }
1.733     raeburn  7788:     return @usersgroups;
1.683     raeburn  7789: }
                   7790: 
                   7791: sub devalidate_getgroups_cache {
                   7792:     my ($udom,$uname,$cdom,$cnum)=@_;
                   7793:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 7794: 
1.683     raeburn  7795:     my $hashid="$udom:$uname:$courseid";
                   7796:     &devalidate_cache_new('getgroups',$hashid);
                   7797: }
                   7798: 
1.12      www      7799: # ------------------------------------------------------------------ Plain Text
                   7800: 
                   7801: sub plaintext {
1.988     raeburn  7802:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  7803:     if ($short =~ m{^cr/}) {
1.758     albertel 7804: 	return (split('/',$short))[-1];
                   7805:     }
1.742     raeburn  7806:     if (!defined($cid)) {
                   7807:         $cid = $env{'request.course.id'};
                   7808:     }
                   7809:     my %rolenames = (
1.1008    raeburn  7810:                       Course    => 'std',
                   7811:                       Community => 'alt1',
1.742     raeburn  7812:                     );
1.1037    raeburn  7813:     if ($cid ne '') {
                   7814:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   7815:             unless ($forcedefault) {
                   7816:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   7817:                 &Apache::lonlocal::mt_escape(\$roletext);
                   7818:                 return &Apache::lonlocal::mt($roletext);
                   7819:             }
                   7820:         }
                   7821:     }
                   7822:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   7823:         (defined($rolenames{$type})) && 
                   7824:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  7825:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  7826:     } elsif ($cid ne '') {
                   7827:         my $crstype = $env{'course.'.$cid.'.type'};
                   7828:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   7829:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   7830:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   7831:         }
1.742     raeburn  7832:     }
1.1037    raeburn  7833:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      7834: }
                   7835: 
                   7836: # ----------------------------------------------------------------- Assign Role
                   7837: 
                   7838: sub assignrole {
1.957     raeburn  7839:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   7840:         $context)=@_;
1.21      www      7841:     my $mrole;
                   7842:     if ($role =~ /^cr\//) {
1.393     www      7843:         my $cwosec=$url;
1.811     albertel 7844:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      7845: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  7846:            my $refused = 1;
                   7847:            if ($context eq 'requestcourses') {
                   7848:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   7849:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   7850:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   7851:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   7852:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7853:                            if ($crsenv{'internal.courseowner'} eq
                   7854:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   7855:                                $refused = '';
                   7856:                            }
                   7857:                        }
                   7858:                    }
                   7859:                }
                   7860:            }
                   7861:            if ($refused) {
                   7862:                &logthis('Refused custom assignrole: '.
                   7863:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   7864:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   7865:                return 'refused';
                   7866:            }
1.104     www      7867:         }
1.21      www      7868:         $mrole='cr';
1.678     raeburn  7869:     } elsif ($role =~ /^gr\//) {
                   7870:         my $cwogrp=$url;
1.811     albertel 7871:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  7872:         unless (&allowed('mdg',$cwogrp)) {
                   7873:             &logthis('Refused group assignrole: '.
                   7874:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   7875:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   7876:             return 'refused';
                   7877:         }
                   7878:         $mrole='gr';
1.21      www      7879:     } else {
1.82      www      7880:         my $cwosec=$url;
1.811     albertel 7881:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  7882:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   7883:             my $refused;
                   7884:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   7885:                 if (!(&allowed('c'.$role,$url))) {
                   7886:                     $refused = 1;
                   7887:                 }
                   7888:             } else {
                   7889:                 $refused = 1;
                   7890:             }
1.947     raeburn  7891:             if ($refused) {
1.1045    raeburn  7892:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   7893:                 if (!$selfenroll && $context eq 'course') {
                   7894:                     my %crsenv;
                   7895:                     if ($role eq 'cc' || $role eq 'co') {
                   7896:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7897:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   7898:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   7899:                                 if ($crsenv{'internal.courseowner'} eq 
                   7900:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   7901:                                     $refused = '';
                   7902:                                 }
                   7903:                             }
                   7904:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   7905:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   7906:                                 if ($crsenv{'internal.courseowner'} eq 
                   7907:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   7908:                                     $refused = '';
                   7909:                                 }
                   7910:                             }
                   7911:                         }
                   7912:                     }
                   7913:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  7914:                     $refused = '';
1.1017    raeburn  7915:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  7916:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  7917:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  7918:                         my $wrongcc;
                   7919:                         if ($cnum =~ /^$match_community$/) {
                   7920:                             $wrongcc = 1 if ($role eq 'cc');
                   7921:                         } else {
                   7922:                             $wrongcc = 1 if ($role eq 'co');
                   7923:                         }
                   7924:                         unless ($wrongcc) {
                   7925:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7926:                             if ($crsenv{'internal.courseowner'} eq 
                   7927:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   7928:                                 $refused = '';
                   7929:                             }
1.1017    raeburn  7930:                         }
                   7931:                     }
1.1172.2.9  raeburn  7932:                 } elsif ($context eq 'requestauthor') {
                   7933:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7934:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   7935:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   7936:                             $refused = '';
                   7937:                         } else {
                   7938:                             my %domdefaults = &get_domain_defaults($udom);
                   7939:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   7940:                                 my $checkbystatus;
                   7941:                                 if ($env{'user.adv'}) {
                   7942:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   7943:                                     if ($disposition eq 'automatic') {
                   7944:                                         $refused = '';
                   7945:                                     } elsif ($disposition eq '') {
                   7946:                                         $checkbystatus = 1;
                   7947:                                     }
                   7948:                                 } else {
                   7949:                                     $checkbystatus = 1;
                   7950:                                 }
                   7951:                                 if ($checkbystatus) {
                   7952:                                     if ($env{'environment.inststatus'}) {
                   7953:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   7954:                                         foreach my $type (@inststatuses) {
                   7955:                                             if (($type ne '') &&
                   7956:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   7957:                                                 $refused = '';
                   7958:                                             }
                   7959:                                         }
                   7960:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   7961:                                         $refused = '';
                   7962:                                     }
                   7963:                                 }
                   7964:                             }
                   7965:                         }
                   7966:                     }
1.1017    raeburn  7967:                 }
                   7968:                 if ($refused) {
1.947     raeburn  7969:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   7970:                              ' '.$role.' '.$end.' '.$start.' by '.
                   7971: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   7972:                     return 'refused';
                   7973:                 }
1.932     raeburn  7974:             }
1.1131    raeburn  7975:         } elsif ($role eq 'au') {
                   7976:             if ($url ne '/'.$udom.'/') {
                   7977:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   7978:                          ' to assign author role for '.$uname.':'.$udom.
                   7979:                          ' in domain: '.$url.' refused (wrong domain).');
                   7980:                 return 'refused';
                   7981:             }
1.104     www      7982:         }
1.21      www      7983:         $mrole=$role;
                   7984:     }
1.620     albertel 7985:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7986:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      7987:     if ($end) { $command.='_'.$end; }
1.21      www      7988:     if ($start) {
                   7989: 	if ($end) { 
1.81      www      7990:            $command.='_'.$start; 
1.21      www      7991:         } else {
1.81      www      7992:            $command.='_0_'.$start;
1.21      www      7993:         }
                   7994:     }
1.739     raeburn  7995:     my $origstart = $start;
                   7996:     my $origend = $end;
1.957     raeburn  7997:     my $delflag;
1.357     www      7998: # actually delete
                   7999:     if ($deleteflag) {
1.373     www      8000: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      8001: # modify command to delete the role
1.620     albertel 8002:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      8003:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 8004: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      8005: # set start and finish to negative values for userrolelog
                   8006:            $start=-1;
                   8007:            $end=-1;
1.957     raeburn  8008:            $delflag = 1;
1.357     www      8009:         }
                   8010:     }
                   8011: # send command
1.349     www      8012:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      8013: # log new user role if status is ok
1.349     www      8014:     if ($answer eq 'ok') {
1.663     raeburn  8015: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  8016:         if (($role eq 'cc') || ($role eq 'in') ||
                   8017:             ($role eq 'ep') || ($role eq 'ad') ||
                   8018:             ($role eq 'ta') || ($role eq 'st') ||
                   8019:             ($role=~/^cr/) || ($role eq 'gr') ||
                   8020:             ($role eq 'co')) {
1.1172.2.13  raeburn  8021: # for course roles, perform group memberships changes triggered by role change.
                   8022:             unless ($role =~ /^gr/) {
                   8023:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   8024:                                                  $origstart,$selfenroll,$context);
                   8025:             }
1.1172.2.9  raeburn  8026:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8027:                            $selfenroll,$context);
                   8028:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
                   8029:                  ($role eq 'au') || ($role eq 'dc')) {
                   8030:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8031:                            $context);
                   8032:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   8033:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8034:                              $context);
                   8035:         }
1.1053    raeburn  8036:         if ($role eq 'cc') {
                   8037:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   8038:         }
1.349     www      8039:     }
                   8040:     return $answer;
1.169     harris41 8041: }
                   8042: 
1.1053    raeburn  8043: sub autoupdate_coowners {
                   8044:     my ($url,$end,$start,$uname,$udom) = @_;
                   8045:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   8046:     if (($cdom ne '') && ($cnum ne '')) {
                   8047:         my $now = time;
                   8048:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   8049:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   8050:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   8051:             my $instcode = $coursehash{'internal.coursecode'};
                   8052:             if ($instcode ne '') {
1.1056    raeburn  8053:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   8054:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  8055:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  8056:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   8057:                         if ($result eq 'valid') {
                   8058:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  8059:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8060:                                     push(@newcoowners,$coowner);
                   8061:                                 }
                   8062:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   8063:                                     push(@newcoowners,$uname.':'.$udom);
                   8064:                                 }
                   8065:                                 @newcoowners = sort(@newcoowners);
                   8066:                             } else {
                   8067:                                 push(@newcoowners,$uname.':'.$udom);
                   8068:                             }
                   8069:                         } else {
                   8070:                             if ($coursehash{'internal.co-owners'}) {
                   8071:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8072:                                     unless ($coowner eq $uname.':'.$udom) {
                   8073:                                         push(@newcoowners,$coowner);
                   8074:                                     }
                   8075:                                 }
                   8076:                                 unless (@newcoowners > 0) {
                   8077:                                     $delcoowners = 1;
                   8078:                                     $coowners = '';
                   8079:                                 }
                   8080:                             }
                   8081:                         }
                   8082:                         if (@newcoowners || $delcoowners) {
                   8083:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   8084:                                             $delcoowners,@newcoowners);
                   8085:                         }
                   8086:                     }
                   8087:                 }
                   8088:             }
                   8089:         }
                   8090:     }
                   8091: }
                   8092: 
                   8093: sub store_coowners {
                   8094:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   8095:     my $cid = $cdom.'_'.$cnum;
                   8096:     my ($coowners,$delresult,$putresult);
                   8097:     if (@newcoowners) {
                   8098:         $coowners = join(',',@newcoowners);
                   8099:         my %coownershash = (
                   8100:                             'internal.co-owners' => $coowners,
                   8101:                            );
                   8102:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   8103:         if ($putresult eq 'ok') {
                   8104:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   8105:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   8106:             }
                   8107:         }
                   8108:     }
                   8109:     if ($delcoowners) {
                   8110:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   8111:         if ($delresult eq 'ok') {
                   8112:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   8113:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   8114:             }
                   8115:         }
                   8116:     }
                   8117:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   8118:         my %crsinfo =
                   8119:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   8120:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   8121:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   8122:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   8123:         }
                   8124:     }
                   8125: }
                   8126: 
1.169     harris41 8127: # -------------------------------------------------- Modify user authentication
1.197     www      8128: # Overrides without validation
                   8129: 
1.169     harris41 8130: sub modifyuserauth {
                   8131:     my ($udom,$uname,$umode,$upass)=@_;
                   8132:     my $uhome=&homeserver($uname,$udom);
1.197     www      8133:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   8134:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 8135:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8136:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 8137:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   8138: 		     &escape($upass),$uhome);
1.620     albertel 8139:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      8140:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   8141:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   8142:     &log($udom,,$uname,$uhome,
1.620     albertel 8143:         'Authentication changed by '.$env{'user.domain'}.', '.
                   8144:                                      $env{'user.name'}.', '.$umode.
1.197     www      8145:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 8146:     unless ($reply eq 'ok') {
1.197     www      8147:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 8148: 	return 'error: '.$reply;
                   8149:     }   
1.170     harris41 8150:     return 'ok';
1.80      www      8151: }
                   8152: 
1.81      www      8153: # --------------------------------------------------------------- Modify a user
1.80      www      8154: 
1.81      www      8155: sub modifyuser {
1.206     matthew  8156:     my ($udom,    $uname, $uid,
                   8157:         $umode,   $upass, $first,
                   8158:         $middle,  $last,  $gene,
1.1058    raeburn  8159:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 8160:     $udom= &LONCAPA::clean_domain($udom);
                   8161:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  8162:     my $showcandelete = 'none';
                   8163:     if (ref($candelete) eq 'ARRAY') {
                   8164:         if (@{$candelete} > 0) {
                   8165:             $showcandelete = join(', ',@{$candelete});
                   8166:         }
                   8167:     }
1.81      www      8168:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      8169:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  8170: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  8171:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   8172:                                      ' desiredhome not specified'). 
1.620     albertel 8173:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8174:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 8175:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  8176:     my $newuser;
                   8177:     if ($uhome eq 'no_host') {
                   8178:         $newuser = 1;
                   8179:     }
1.80      www      8180: # ----------------------------------------------------------------- Create User
1.406     albertel 8181:     if (($uhome eq 'no_host') && 
                   8182: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      8183:         my $unhome='';
1.844     albertel 8184:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  8185:             $unhome = $desiredhome;
1.620     albertel 8186: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   8187: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  8188:         } else { # load balancing routine for determining $unhome
1.81      www      8189:             my $loadm=10000000;
1.841     albertel 8190: 	    my %servers = &get_servers($udom,'library');
                   8191: 	    foreach my $tryserver (keys(%servers)) {
                   8192: 		my $answer=reply('load',$tryserver);
                   8193: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   8194: 		    $loadm=$answer;
                   8195: 		    $unhome=$tryserver;
                   8196: 		}
1.80      www      8197: 	    }
                   8198:         }
                   8199:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  8200: 	    return 'error: unable to find a home server for '.$uname.
                   8201:                    ' in domain '.$udom;
1.80      www      8202:         }
                   8203:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   8204:                          &escape($upass),$unhome);
                   8205: 	unless ($reply eq 'ok') {
                   8206:             return 'error: '.$reply;
                   8207:         }   
1.230     stredwic 8208:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      8209:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  8210: 	    return 'error: unable verify users home machine.';
1.80      www      8211:         }
1.209     matthew  8212:     }   # End of creation of new user
1.80      www      8213: # ---------------------------------------------------------------------- Add ID
                   8214:     if ($uid) {
                   8215:        $uid=~tr/A-Z/a-z/;
                   8216:        my %uidhash=&idrget($udom,$uname);
1.196     www      8217:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   8218:          && (!$forceid)) {
1.80      www      8219: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  8220: 	      return 'error: user id "'.$uid.'" does not match '.
                   8221:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      8222:           }
                   8223:        } else {
                   8224: 	  &idput($udom,($uname => $uid));
                   8225:        }
                   8226:     }
                   8227: # -------------------------------------------------------------- Add names, etc
1.313     matthew  8228:     my @tmp=&get('environment',
1.899     raeburn  8229: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  8230:                     'permanentemail','inststatus'],
1.134     albertel 8231: 		   $udom,$uname);
1.1075    raeburn  8232:     my (%names,%oldnames);
1.313     matthew  8233:     if ($tmp[0] =~ m/^error:.*/) { 
                   8234:         %names=(); 
                   8235:     } else {
                   8236:         %names = @tmp;
1.1075    raeburn  8237:         %oldnames = %names;
1.313     matthew  8238:     }
1.388     www      8239: #
1.1058    raeburn  8240: # If name, email and/or uid are blank (e.g., because an uploaded file
                   8241: # of users did not contain them), do not overwrite existing values
                   8242: # unless field is in $candelete array ref.  
                   8243: #
                   8244: 
                   8245:     my @fields = ('firstname','middlename','lastname','generation',
                   8246:                   'permanentemail','id');
                   8247:     my %newvalues;
                   8248:     if (ref($candelete) eq 'ARRAY') {
                   8249:         foreach my $field (@fields) {
                   8250:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   8251:                 if ($field eq 'firstname') {
                   8252:                     $names{$field} = $first;
                   8253:                 } elsif ($field eq 'middlename') {
                   8254:                     $names{$field} = $middle;
                   8255:                 } elsif ($field eq 'lastname') {
                   8256:                     $names{$field} = $last;
                   8257:                 } elsif ($field eq 'generation') { 
                   8258:                     $names{$field} = $gene;
                   8259:                 } elsif ($field eq 'permanentemail') {
                   8260:                     $names{$field} = $email;
                   8261:                 } elsif ($field eq 'id') {
                   8262:                     $names{$field}  = $uid;
                   8263:                 }
                   8264:             }
                   8265:         }
                   8266:     }
1.388     www      8267:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  8268:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      8269:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  8270:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      8271:     if ($email) {
                   8272:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  8273:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      8274:     }
1.899     raeburn  8275:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  8276:     if (defined($inststatus)) {
                   8277:         $names{'inststatus'} = '';
                   8278:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   8279:         if (ref($usertypes) eq 'HASH') {
                   8280:             my @okstatuses; 
                   8281:             foreach my $item (split(/:/,$inststatus)) {
                   8282:                 if (defined($usertypes->{$item})) {
                   8283:                     push(@okstatuses,$item);  
                   8284:                 }
                   8285:             }
                   8286:             if (@okstatuses) {
                   8287:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   8288:             }
                   8289:         }
                   8290:     }
1.1075    raeburn  8291:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  8292:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  8293:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  8294:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   8295:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   8296:     } else {
                   8297:         $logmsg .= ' during self creation';
                   8298:     }
1.1075    raeburn  8299:     my $changed;
                   8300:     if ($newuser) {
                   8301:         $changed = 1;
                   8302:     } else {
                   8303:         foreach my $field (@fields) {
                   8304:             if ($names{$field} ne $oldnames{$field}) {
                   8305:                 $changed = 1;
                   8306:                 last;
                   8307:             }
                   8308:         }
                   8309:     }
                   8310:     unless ($changed) {
                   8311:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   8312:         &logthis($logmsg);
                   8313:         return 'ok';
                   8314:     }
                   8315:     my $reply = &put('environment', \%names, $udom,$uname);
                   8316:     if ($reply ne 'ok') { 
                   8317:         return 'error: '.$reply;
                   8318:     }
1.1087    raeburn  8319:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   8320:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   8321:     }
1.1075    raeburn  8322:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   8323:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   8324:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  8325:     &logthis($logmsg);
1.134     albertel 8326:     return 'ok';
1.80      www      8327: }
                   8328: 
1.81      www      8329: # -------------------------------------------------------------- Modify student
1.80      www      8330: 
1.81      www      8331: sub modifystudent {
                   8332:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  8333:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990     raeburn  8334:         $selfenroll,$context,$inststatus)=@_;
1.455     albertel 8335:     if (!$cid) {
1.620     albertel 8336: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8337: 	    return 'not_in_class';
                   8338: 	}
1.80      www      8339:     }
                   8340: # --------------------------------------------------------------- Make the user
1.81      www      8341:     my $reply=&modifyuser
1.209     matthew  8342: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  8343:          $desiredhome,$email,$inststatus);
1.80      www      8344:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  8345:     # This will cause &modify_student_enrollment to get the uid from the
                   8346:     # students environment
                   8347:     $uid = undef if (!$forceid);
1.455     albertel 8348:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  8349: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  8350:     return $reply;
                   8351: }
                   8352: 
                   8353: sub modify_student_enrollment {
1.957     raeburn  8354:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 8355:     my ($cdom,$cnum,$chome);
                   8356:     if (!$cid) {
1.620     albertel 8357: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8358: 	    return 'not_in_class';
                   8359: 	}
1.620     albertel 8360: 	$cdom=$env{'course.'.$cid.'.domain'};
                   8361: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 8362:     } else {
                   8363: 	($cdom,$cnum)=split(/_/,$cid);
                   8364:     }
1.620     albertel 8365:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 8366:     if (!$chome) {
1.457     raeburn  8367: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  8368:     }
1.455     albertel 8369:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  8370:     # Make sure the user exists
1.81      www      8371:     my $uhome=&homeserver($uname,$udom);
                   8372:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8373: 	return 'error: no such user';
                   8374:     }
1.297     matthew  8375:     # Get student data if we were not given enough information
                   8376:     if (!defined($first)  || $first  eq '' || 
                   8377:         !defined($last)   || $last   eq '' || 
                   8378:         !defined($uid)    || $uid    eq '' || 
                   8379:         !defined($middle) || $middle eq '' || 
                   8380:         !defined($gene)   || $gene   eq '') {
1.294     matthew  8381:         # They did not supply us with enough data to enroll the student, so
                   8382:         # we need to pick up more information.
1.297     matthew  8383:         my %tmp = &get('environment',
1.294     matthew  8384:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  8385:                        ,$udom,$uname);
                   8386: 
1.800     albertel 8387:         #foreach my $key (keys(%tmp)) {
                   8388:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 8389:         #}
1.294     matthew  8390:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   8391:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   8392:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  8393:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  8394:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   8395:     }
1.556     albertel 8396:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  8397:     my $user = "$uname:$udom";
                   8398:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 8399:     my $reply=cput('classlist',
1.1148    raeburn  8400: 		   {$user => 
1.515     raeburn  8401: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 8402: 		   $cdom,$cnum);
1.1148    raeburn  8403:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   8404:         &devalidate_getsection_cache($udom,$uname,$cid);
                   8405:     } else { 
1.81      www      8406: 	return 'error: '.$reply;
                   8407:     }
1.297     matthew  8408:     # Add student role to user
1.83      www      8409:     my $uurl='/'.$cid;
1.81      www      8410:     $uurl=~s/\_/\//g;
                   8411:     if ($usec) {
                   8412: 	$uurl.='/'.$usec;
                   8413:     }
1.1148    raeburn  8414:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   8415:                              $selfenroll,$context);
                   8416:     if ($result ne 'ok') {
                   8417:         if ($old_entry{$user} ne '') {
                   8418:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   8419:         } else {
                   8420:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   8421:         }
                   8422:     }
                   8423:     return $result; 
1.21      www      8424: }
                   8425: 
1.556     albertel 8426: sub format_name {
                   8427:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   8428:     my $name;
                   8429:     if ($first ne 'lastname') {
                   8430: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   8431:     } else {
                   8432: 	if ($lastname=~/\S/) {
                   8433: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   8434: 	    $name=~s/\s+,/,/;
                   8435: 	} else {
                   8436: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   8437: 	}
                   8438:     }
                   8439:     $name=~s/^\s+//;
                   8440:     $name=~s/\s+$//;
                   8441:     $name=~s/\s+/ /g;
                   8442:     return $name;
                   8443: }
                   8444: 
1.84      www      8445: # ------------------------------------------------- Write to course preferences
                   8446: 
                   8447: sub writecoursepref {
                   8448:     my ($courseid,%prefs)=@_;
                   8449:     $courseid=~s/^\///;
                   8450:     $courseid=~s/\_/\//g;
                   8451:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   8452:     my $chome=homeserver($cnum,$cdomain);
                   8453:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   8454: 	return 'error: no such course';
                   8455:     }
                   8456:     my $cstring='';
1.800     albertel 8457:     foreach my $pref (keys(%prefs)) {
                   8458: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 8459:     }
1.84      www      8460:     $cstring=~s/\&$//;
                   8461:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   8462: }
                   8463: 
                   8464: # ---------------------------------------------------------- Make/modify course
                   8465: 
                   8466: sub createcourse {
1.741     raeburn  8467:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  8468:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      8469:     $url=&declutter($url);
                   8470:     my $cid='';
1.1028    raeburn  8471:     if ($context eq 'requestcourses') {
                   8472:         my $can_create = 0;
                   8473:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   8474:         if ($udom eq $ownerdom) {
                   8475:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   8476:                                   $context)) {
                   8477:                 $can_create = 1;
                   8478:             }
                   8479:         } else {
                   8480:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   8481:                                            $category);
                   8482:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   8483:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   8484:                 if (@curr > 0) {
                   8485:                     my @options = qw(approval validate autolimit);
                   8486:                     my $optregex = join('|',@options);
                   8487:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   8488:                         $can_create = 1;
                   8489:                     }
                   8490:                 }
                   8491:             }
                   8492:         }
                   8493:         if ($can_create) {
                   8494:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   8495:                 unless (&allowed('ccc',$udom)) {
                   8496:                     return 'refused'; 
                   8497:                 }
1.1017    raeburn  8498:             }
                   8499:         } else {
                   8500:             return 'refused';
                   8501:         }
1.1028    raeburn  8502:     } elsif (!&allowed('ccc',$udom)) {
                   8503:         return 'refused';
1.84      www      8504:     }
1.1011    raeburn  8505: # --------------------------------------------------------------- Get Unique ID
                   8506:     my $uname;
                   8507:     if ($cnum =~ /^$match_courseid$/) {
                   8508:         my $chome=&homeserver($cnum,$udom,'true');
                   8509:         if (($chome eq '') || ($chome eq 'no_host')) {
                   8510:             $uname = $cnum;
                   8511:         } else {
1.1038    raeburn  8512:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8513:         }
                   8514:     } else {
1.1038    raeburn  8515:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8516:     }
                   8517:     return $uname if ($uname =~ /^error/);
                   8518: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  8519:     if (!defined($course_server)) {
                   8520:         if (defined(&domain($udom,'primary'))) {
                   8521:             $course_server = &domain($udom,'primary');
                   8522:         } else {
                   8523:             $course_server = $env{'user.home'}; 
                   8524:         }
                   8525:     }
                   8526:     my %host_servers =
                   8527:         &Apache::lonnet::get_servers($udom,'library');
                   8528:     unless ($host_servers{$course_server}) {
                   8529:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  8530:     }
1.84      www      8531: # ------------------------------------------------------------- Make the course
                   8532:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  8533:                       $course_server);
1.84      www      8534:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  8535:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      8536:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8537: 	return 'error: no such course';
                   8538:     }
1.271     www      8539: # ----------------------------------------------------------------- Course made
1.516     raeburn  8540: # log existence
1.1029    raeburn  8541:     my $now = time;
1.918     raeburn  8542:     my $newcourse = {
                   8543:                     $udom.'_'.$uname => {
1.921     raeburn  8544:                                      description => $description,
                   8545:                                      inst_code   => $inst_code,
                   8546:                                      owner       => $course_owner,
                   8547:                                      type        => $crstype,
1.1029    raeburn  8548:                                      creator     => $env{'user.name'}.':'.
                   8549:                                                     $env{'user.domain'},
                   8550:                                      created     => $now,
                   8551:                                      context     => $context,
1.918     raeburn  8552:                                                 },
                   8553:                     };
1.921     raeburn  8554:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      8555: # set toplevel url
1.271     www      8556:     my $topurl=$url;
                   8557:     unless ($nonstandard) {
                   8558: # ------------------------------------------ For standard courses, make top url
                   8559:         my $mapurl=&clutter($url);
1.278     www      8560:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 8561:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      8562: <map>
                   8563: <resource id="1" type="start"></resource>
                   8564: <resource id="2" src="$mapurl"></resource>
                   8565: <resource id="3" type="finish"></resource>
                   8566: <link index="1" from="1" to="2"></link>
                   8567: <link index="2" from="2" to="3"></link>
                   8568: </map>
                   8569: ENDINITMAP
                   8570:         $topurl=&declutter(
1.638     albertel 8571:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      8572:                           );
                   8573:     }
                   8574: # ----------------------------------------------------------- Write preferences
1.84      www      8575:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  8576:                      ('description'              => $description,
                   8577:                       'url'                      => $topurl,
                   8578:                       'internal.creator'         => $env{'user.name'}.':'.
                   8579:                                                     $env{'user.domain'},
                   8580:                       'internal.created'         => $now,
                   8581:                       'internal.creationcontext' => $context)
                   8582:                     );
1.84      www      8583:     return '/'.$udom.'/'.$uname;
                   8584: }
                   8585: 
1.1011    raeburn  8586: # ------------------------------------------------------------------- Create ID
                   8587: sub generate_coursenum {
1.1038    raeburn  8588:     my ($udom,$crstype) = @_;
1.1011    raeburn  8589:     my $domdesc = &domain($udom);
                   8590:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  8591:     my $first;
                   8592:     if ($crstype eq 'Community') {
                   8593:         $first = '0';
                   8594:     } else {
                   8595:         $first = int(1+rand(9)); 
                   8596:     } 
                   8597:     my $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: # ----------------------------------------------- Make sure that does not exist
                   8602:     my $uhome=&homeserver($uname,$udom,'true');
                   8603:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  8604:         if ($crstype eq 'Community') {
                   8605:             $first = '0';
                   8606:         } else {
                   8607:             $first = int(1+rand(9));
                   8608:         }
                   8609:         $uname=$first.
1.1011    raeburn  8610:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8611:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8612:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8613:         $uhome=&homeserver($uname,$udom,'true');
                   8614:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   8615:             return 'error: unable to generate unique course-ID';
                   8616:         }
                   8617:     }
                   8618:     return $uname;
                   8619: }
                   8620: 
1.813     albertel 8621: sub is_course {
1.1167    droeschl 8622:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   8623:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   8624: 
                   8625:     return unless $cdom and $cnum;
                   8626: 
                   8627:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   8628:         '.');
                   8629: 
                   8630:     return unless exists($courses{$cdom.'_'.$cnum});
                   8631:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 8632: }
                   8633: 
1.1015    raeburn  8634: sub store_userdata {
                   8635:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  8636:     my $result;
1.1016    raeburn  8637:     if ($datakey ne '') {
1.1013    raeburn  8638:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  8639:             if ($udom eq '' || $uname eq '') {
                   8640:                 $udom = $env{'user.domain'};
                   8641:                 $uname = $env{'user.name'};
                   8642:             }
                   8643:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  8644:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   8645:                 $result = 'error: no_host';
                   8646:             } else {
                   8647:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   8648:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   8649: 
                   8650:                 my $namevalue='';
                   8651:                 foreach my $key (keys(%{$storehash})) {
                   8652:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   8653:                 }
                   8654:                 $namevalue=~s/\&$//;
1.1105    raeburn  8655:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   8656:                                   $namevalue,$uhome);
1.1013    raeburn  8657:             }
                   8658:         } else {
                   8659:             $result = 'error: data to store was not a hash reference'; 
                   8660:         }
                   8661:     } else {
                   8662:         $result= 'error: invalid requestkey'; 
                   8663:     }
                   8664:     return $result;
                   8665: }
                   8666: 
1.21      www      8667: # ---------------------------------------------------------- Assign Custom Role
                   8668: 
                   8669: sub assigncustomrole {
1.957     raeburn  8670:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8671:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  8672:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      8673: }
                   8674: 
                   8675: # ----------------------------------------------------------------- Revoke Role
                   8676: 
                   8677: sub revokerole {
1.957     raeburn  8678:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8679:     my $now=time;
1.965     raeburn  8680:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      8681: }
                   8682: 
                   8683: # ---------------------------------------------------------- Revoke Custom Role
                   8684: 
                   8685: sub revokecustomrole {
1.957     raeburn  8686:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8687:     my $now=time;
1.357     www      8688:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  8689:            $deleteflag,$selfenroll,$context);
1.17      www      8690: }
                   8691: 
1.533     banghart 8692: # ------------------------------------------------------------ Disk usage
1.535     albertel 8693: sub diskusage {
1.955     raeburn  8694:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   8695:     $directorypath =~ s/\/$//;
                   8696:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   8697:                        .&escape($getpropath).':'.&escape($uname).':'
                   8698:                        .&escape($udom),homeserver($uname,$udom));
                   8699:     if ($listing eq 'unknown_cmd') {
                   8700:         if ($getpropath) {
                   8701:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   8702:         }
                   8703:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   8704:     }
1.514     albertel 8705:     return $listing;
1.512     banghart 8706: }
                   8707: 
1.566     banghart 8708: sub is_locked {
1.1096    raeburn  8709:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 8710:     my @check;
                   8711:     my $is_locked;
1.1093    raeburn  8712:     push (@check,$file_name);
1.613     albertel 8713:     my %locked = &get('file_permissions',\@check,
1.620     albertel 8714: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 8715:     my ($tmp)=keys(%locked);
                   8716:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  8717:     
1.566     banghart 8718:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  8719:         $is_locked = 'false';
                   8720:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  8721:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  8722:                $is_locked = 'true';
1.1096    raeburn  8723:                if (ref($which) eq 'ARRAY') {
                   8724:                    push(@{$which},$entry);
                   8725:                } else {
                   8726:                    last;
                   8727:                }
1.745     raeburn  8728:            }
                   8729:        }
1.566     banghart 8730:     } else {
                   8731:         $is_locked = 'false';
                   8732:     }
1.1093    raeburn  8733:     return $is_locked;
1.566     banghart 8734: }
                   8735: 
1.759     albertel 8736: sub declutter_portfile {
                   8737:     my ($file) = @_;
1.833     albertel 8738:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 8739:     return $file;
                   8740: }
                   8741: 
1.559     banghart 8742: # ------------------------------------------------------------- Mark as Read Only
                   8743: 
                   8744: sub mark_as_readonly {
                   8745:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 8746:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 8747:     my ($tmp)=keys(%current_permissions);
                   8748:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 8749:     foreach my $file (@{$files}) {
1.759     albertel 8750: 	$file = &declutter_portfile($file);
1.561     banghart 8751:         push(@{$current_permissions{$file}},$what);
1.559     banghart 8752:     }
1.613     albertel 8753:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 8754:     return;
                   8755: }
                   8756: 
1.572     banghart 8757: # ------------------------------------------------------------Save Selected Files
                   8758: 
                   8759: sub save_selected_files {
                   8760:     my ($user, $path, @files) = @_;
                   8761:     my $filename = $user."savedfiles";
1.573     banghart 8762:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 8763:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 8764:     foreach my $file (@files) {
1.620     albertel 8765:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 8766:     }
                   8767:     foreach my $file (@other_files) {
1.574     banghart 8768:         print (OUT $file."\n");
1.572     banghart 8769:     }
1.574     banghart 8770:     close (OUT);
1.572     banghart 8771:     return 'ok';
                   8772: }
                   8773: 
1.574     banghart 8774: sub clear_selected_files {
                   8775:     my ($user) = @_;
                   8776:     my $filename = $user."savedfiles";
1.1117    foxr     8777:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 8778:     print (OUT undef);
                   8779:     close (OUT);
                   8780:     return ("ok");    
                   8781: }
                   8782: 
1.572     banghart 8783: sub files_in_path {
                   8784:     my ($user, $path) = @_;
                   8785:     my $filename = $user."savedfiles";
                   8786:     my %return_files;
1.1117    foxr     8787:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 8788:     while (my $line_in = <IN>) {
1.574     banghart 8789:         chomp ($line_in);
                   8790:         my @paths_and_file = split (m!/!, $line_in);
                   8791:         my $file_part = pop (@paths_and_file);
                   8792:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 8793:         $path_part.='/';
                   8794:         my $path_and_file = $path_part.$file_part;
                   8795:         if ($path_part eq $path) {
                   8796:             $return_files{$file_part}= 'selected';
                   8797:         }
                   8798:     }
1.574     banghart 8799:     close (IN);
                   8800:     return (\%return_files);
1.572     banghart 8801: }
                   8802: 
                   8803: # called in portfolio select mode, to show files selected NOT in current directory
                   8804: sub files_not_in_path {
                   8805:     my ($user, $path) = @_;
                   8806:     my $filename = $user."savedfiles";
                   8807:     my @return_files;
                   8808:     my $path_part;
1.1117    foxr     8809:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 8810:     while (my $line = <IN>) {
1.572     banghart 8811:         #ok, I know it's clunky, but I want it to work
1.800     albertel 8812:         my @paths_and_file = split(m|/|, $line);
                   8813:         my $file_part = pop(@paths_and_file);
                   8814:         chomp($file_part);
                   8815:         my $path_part = join('/', @paths_and_file);
1.572     banghart 8816:         $path_part .= '/';
                   8817:         my $path_and_file = $path_part.$file_part;
                   8818:         if ($path_part ne $path) {
1.800     albertel 8819:             push(@return_files, ($path_and_file));
1.572     banghart 8820:         }
                   8821:     }
1.800     albertel 8822:     close(OUT);
1.574     banghart 8823:     return (@return_files);
1.572     banghart 8824: }
                   8825: 
1.745     raeburn  8826: #----------------------------------------------Get portfolio file permissions
1.629     banghart 8827: 
1.745     raeburn  8828: sub get_portfile_permissions {
                   8829:     my ($domain,$user) = @_;
1.613     albertel 8830:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 8831:     my ($tmp)=keys(%current_permissions);
                   8832:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  8833:     return \%current_permissions;
                   8834: }
                   8835: 
                   8836: #---------------------------------------------Get portfolio file access controls
                   8837: 
1.749     raeburn  8838: sub get_access_controls {
1.745     raeburn  8839:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 8840:     my %access;
                   8841:     my $real_file = $file;
                   8842:     $file =~ s/\.meta$//;
1.745     raeburn  8843:     if (defined($file)) {
1.749     raeburn  8844:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   8845:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 8846:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  8847:             }
                   8848:         }
1.745     raeburn  8849:     } else {
1.749     raeburn  8850:         foreach my $key (keys(%{$current_permissions})) {
                   8851:             if ($key =~ /\0accesscontrol$/) {
                   8852:                 if (defined($group)) {
                   8853:                     if ($key !~ m-^\Q$group\E/-) {
                   8854:                         next;
                   8855:                     }
                   8856:                 }
                   8857:                 my ($fullpath) = split(/\0/,$key);
                   8858:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   8859:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   8860:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   8861:                     }
                   8862:                 }
                   8863:             }
                   8864:         }
                   8865:     }
                   8866:     return %access;
                   8867: }
                   8868: 
                   8869: sub modify_access_controls {
                   8870:     my ($file_name,$changes,$domain,$user)=@_;
                   8871:     my ($outcome,$deloutcome);
                   8872:     my %store_permissions;
                   8873:     my %new_values;
                   8874:     my %new_control;
                   8875:     my %translation;
                   8876:     my @deletions = ();
                   8877:     my $now = time;
                   8878:     if (exists($$changes{'activate'})) {
                   8879:         if (ref($$changes{'activate'}) eq 'HASH') {
                   8880:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   8881:             my $numnew = scalar(@newitems);
                   8882:             for (my $i=0; $i<$numnew; $i++) {
                   8883:                 my $newkey = $newitems[$i];
                   8884:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  8885:                 if ($newkey =~ /^\d+:/) { 
                   8886:                     $newkey =~ s/^(\d+)/$newid/;
                   8887:                     $translation{$1} = $newid;
                   8888:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   8889:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   8890:                     $translation{$1} = $newid;
                   8891:                 }
1.749     raeburn  8892:                 $new_values{$file_name."\0".$newkey} = 
                   8893:                                           $$changes{'activate'}{$newitems[$i]};
                   8894:                 $new_control{$newkey} = $now;
                   8895:             }
                   8896:         }
                   8897:     }
                   8898:     my %todelete;
                   8899:     my %changed_items;
                   8900:     foreach my $action ('delete','update') {
                   8901:         if (exists($$changes{$action})) {
                   8902:             if (ref($$changes{$action}) eq 'HASH') {
                   8903:                 foreach my $key (keys(%{$$changes{$action}})) {
                   8904:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   8905:                     if ($action eq 'delete') { 
                   8906:                         $todelete{$itemnum} = 1;
                   8907:                     } else {
                   8908:                         $changed_items{$itemnum} = $key;
                   8909:                     }
                   8910:                 }
1.745     raeburn  8911:             }
                   8912:         }
1.749     raeburn  8913:     }
                   8914:     # get lock on access controls for file.
                   8915:     my $lockhash = {
                   8916:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   8917:                                                        ':'.$env{'user.domain'},
                   8918:                    }; 
                   8919:     my $tries = 0;
                   8920:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   8921:    
                   8922:     while (($gotlock ne 'ok') && $tries <3) {
                   8923:         $tries ++;
                   8924:         sleep 1;
                   8925:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   8926:     }
                   8927:     if ($gotlock eq 'ok') {
                   8928:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   8929:         my ($tmp)=keys(%curr_permissions);
                   8930:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   8931:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   8932:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   8933:             if (ref($curr_controls) eq 'HASH') {
                   8934:                 foreach my $control_item (keys(%{$curr_controls})) {
                   8935:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   8936:                     if (defined($todelete{$itemnum})) {
                   8937:                         push(@deletions,$file_name."\0".$control_item);
                   8938:                     } else {
                   8939:                         if (defined($changed_items{$itemnum})) {
                   8940:                             $new_control{$changed_items{$itemnum}} = $now;
                   8941:                             push(@deletions,$file_name."\0".$control_item);
                   8942:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   8943:                         } else {
                   8944:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   8945:                         }
                   8946:                     }
1.745     raeburn  8947:                 }
                   8948:             }
                   8949:         }
1.970     raeburn  8950:         my ($group);
                   8951:         if (&is_course($domain,$user)) {
                   8952:             ($group,my $file) = split(/\//,$file_name,2);
                   8953:         }
1.749     raeburn  8954:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   8955:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   8956:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   8957:         #  remove lock
                   8958:         my @del_lock = ($file_name."\0".'locked_access_records');
                   8959:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  8960:         my $sqlresult =
1.970     raeburn  8961:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  8962:                                     $group);
1.749     raeburn  8963:     } else {
                   8964:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  8965:     }
1.749     raeburn  8966:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  8967: }
                   8968: 
1.827     raeburn  8969: sub make_public_indefinitely {
                   8970:     my ($requrl) = @_;
                   8971:     my $now = time;
                   8972:     my $action = 'activate';
                   8973:     my $aclnum = 0;
                   8974:     if (&is_portfolio_url($requrl)) {
                   8975:         my (undef,$udom,$unum,$file_name,$group) =
                   8976:             &parse_portfolio_url($requrl);
                   8977:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   8978:         my %access_controls = &get_access_controls($current_perms,
                   8979:                                                    $group,$file_name);
                   8980:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   8981:             my ($num,$scope,$end,$start) = 
                   8982:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   8983:             if ($scope eq 'public') {
                   8984:                 if ($start <= $now && $end == 0) {
                   8985:                     $action = 'none';
                   8986:                 } else {
                   8987:                     $action = 'update';
                   8988:                     $aclnum = $num;
                   8989:                 }
                   8990:                 last;
                   8991:             }
                   8992:         }
                   8993:         if ($action eq 'none') {
                   8994:              return 'ok';
                   8995:         } else {
                   8996:             my %changes;
                   8997:             my $newend = 0;
                   8998:             my $newstart = $now;
                   8999:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   9000:             $changes{$action}{$newkey} = {
                   9001:                 type => 'public',
                   9002:                 time => {
                   9003:                     start => $newstart,
                   9004:                     end   => $newend,
                   9005:                 },
                   9006:             };
                   9007:             my ($outcome,$deloutcome,$new_values,$translation) =
                   9008:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   9009:             return $outcome;
                   9010:         }
                   9011:     } else {
                   9012:         return 'invalid';
                   9013:     }
                   9014: }
                   9015: 
1.745     raeburn  9016: #------------------------------------------------------Get Marked as Read Only
                   9017: 
                   9018: sub get_marked_as_readonly {
                   9019:     my ($domain,$user,$what,$group) = @_;
                   9020:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 9021:     my @readonly_files;
1.629     banghart 9022:     my $cmp1=$what;
                   9023:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  9024:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9025:         if (defined($group)) {
                   9026:             if ($file_name !~ m-^\Q$group\E/-) {
                   9027:                 next;
                   9028:             }
                   9029:         }
1.561     banghart 9030:         if (ref($value) eq "ARRAY"){
                   9031:             foreach my $stored_what (@{$value}) {
1.629     banghart 9032:                 my $cmp2=$stored_what;
1.759     albertel 9033:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  9034:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  9035:                 }
1.629     banghart 9036:                 if ($cmp1 eq $cmp2) {
1.561     banghart 9037:                     push(@readonly_files, $file_name);
1.745     raeburn  9038:                     last;
1.563     banghart 9039:                 } elsif (!defined($what)) {
                   9040:                     push(@readonly_files, $file_name);
1.745     raeburn  9041:                     last;
1.561     banghart 9042:                 }
                   9043:             }
1.745     raeburn  9044:         }
1.561     banghart 9045:     }
                   9046:     return @readonly_files;
                   9047: }
1.577     banghart 9048: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 9049: 
1.577     banghart 9050: sub get_marked_as_readonly_hash {
1.745     raeburn  9051:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 9052:     my %readonly_files;
1.745     raeburn  9053:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9054:         if (defined($group)) {
                   9055:             if ($file_name !~ m-^\Q$group\E/-) {
                   9056:                 next;
                   9057:             }
                   9058:         }
1.577     banghart 9059:         if (ref($value) eq "ARRAY"){
                   9060:             foreach my $stored_what (@{$value}) {
1.745     raeburn  9061:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 9062:                     foreach my $lock_descriptor(@{$stored_what}) {
                   9063:                         if ($lock_descriptor eq 'graded') {
                   9064:                             $readonly_files{$file_name} = 'graded';
                   9065:                         } elsif ($lock_descriptor eq 'handback') {
                   9066:                             $readonly_files{$file_name} = 'handback';
                   9067:                         } else {
                   9068:                             if (!exists($readonly_files{$file_name})) {
                   9069:                                 $readonly_files{$file_name} = 'locked';
                   9070:                             }
                   9071:                         }
1.745     raeburn  9072:                     }
1.750     banghart 9073:                 } 
1.577     banghart 9074:             }
                   9075:         } 
                   9076:     }
                   9077:     return %readonly_files;
                   9078: }
1.559     banghart 9079: # ------------------------------------------------------------ Unmark as Read Only
                   9080: 
                   9081: sub unmark_as_readonly {
1.629     banghart 9082:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   9083:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  9084:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 9085:     $file_name = &declutter_portfile($file_name);
1.634     albertel 9086:     my $symb_crs = $what;
                   9087:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  9088:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 9089:     my ($tmp)=keys(%current_permissions);
                   9090:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9091:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 9092:     foreach my $file (@readonly_files) {
1.759     albertel 9093: 	my $clean_file = &declutter_portfile($file);
                   9094: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 9095: 	my $current_locks = $current_permissions{$file};
1.563     banghart 9096:         my @new_locks;
                   9097:         my @del_keys;
                   9098:         if (ref($current_locks) eq "ARRAY"){
                   9099:             foreach my $locker (@{$current_locks}) {
1.632     albertel 9100:                 my $compare=$locker;
1.749     raeburn  9101:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  9102:                     $compare=join('',@{$locker});
1.746     raeburn  9103:                     if ($compare ne $symb_crs) {
                   9104:                         push(@new_locks, $locker);
                   9105:                     }
1.563     banghart 9106:                 }
                   9107:             }
1.650     albertel 9108:             if (scalar(@new_locks) > 0) {
1.563     banghart 9109:                 $current_permissions{$file} = \@new_locks;
                   9110:             } else {
                   9111:                 push(@del_keys, $file);
1.613     albertel 9112:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 9113:                 delete($current_permissions{$file});
1.563     banghart 9114:             }
                   9115:         }
1.561     banghart 9116:     }
1.613     albertel 9117:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9118:     return;
                   9119: }
1.512     banghart 9120: 
1.17      www      9121: # ------------------------------------------------------------ Directory lister
                   9122: 
                   9123: sub dirlist {
1.955     raeburn  9124:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      9125:     $uri=~s/^\///;
                   9126:     $uri=~s/\/$//;
1.253     stredwic 9127:     my ($udom, $uname);
1.955     raeburn  9128:     if ($getuserdir) {
1.253     stredwic 9129:         $udom = $userdomain;
                   9130:         $uname = $username;
1.955     raeburn  9131:     } else {
                   9132:         (undef,$udom,$uname)=split(/\//,$uri);
                   9133:         if(defined($userdomain)) {
                   9134:             $udom = $userdomain;
                   9135:         }
                   9136:         if(defined($username)) {
                   9137:             $uname = $username;
                   9138:         }
1.253     stredwic 9139:     }
1.955     raeburn  9140:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 9141: 
1.955     raeburn  9142:     $dirRoot = $perlvar{'lonDocRoot'};
                   9143:     if (defined($getpropath)) {
                   9144:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 9145:         $dirRoot =~ s/\/$//;
1.955     raeburn  9146:     } elsif (defined($getuserdir)) {
                   9147:         my $subdir=$uname.'__';
                   9148:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   9149:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   9150:                    ."/$udom/$subdir/$uname";
                   9151:     } elsif (defined($alternateRoot)) {
                   9152:         $dirRoot = $alternateRoot;
1.751     banghart 9153:     }
1.253     stredwic 9154: 
                   9155:     if($udom) {
                   9156:         if($uname) {
1.1135    raeburn  9157:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  9158:             if ($uhome eq 'no_host') {
                   9159:                 return ([],'no_host');
                   9160:             }
1.955     raeburn  9161:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  9162:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  9163:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  9164:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9165:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  9166:             } else {
                   9167:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9168:             }
1.605     matthew  9169:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9170:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  9171:                 @listing_results = split(/:/,$listing);
                   9172:             } else {
                   9173:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9174:             }
1.1135    raeburn  9175:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  9176:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9177:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9178:                 return ([],$listing);
                   9179:             } else {
                   9180:                 return (\@listing_results);
1.1135    raeburn  9181:             }
1.955     raeburn  9182:         } elsif(!$alternateRoot) {
1.1136    raeburn  9183:             my (%allusers,%listerror);
1.841     albertel 9184: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  9185:  	    foreach my $tryserver (keys(%servers)) {
                   9186:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   9187:                                   &escape($udom),$tryserver);
                   9188:                 if ($listing eq 'unknown_cmd') {
                   9189: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9190: 				      $udom, $tryserver);
                   9191:                 } else {
                   9192:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9193:                 }
1.841     albertel 9194: 		if ($listing eq 'unknown_cmd') {
                   9195: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9196: 				      $udom, $tryserver);
                   9197: 		    @listing_results = split(/:/,$listing);
                   9198: 		} else {
                   9199: 		    @listing_results =
                   9200: 			map { &unescape($_); } split(/:/,$listing);
                   9201: 		}
1.1136    raeburn  9202:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   9203:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9204:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9205:                     $listerror{$tryserver} = $listing;
                   9206:                 } else {
1.841     albertel 9207: 		    foreach my $line (@listing_results) {
                   9208: 			my ($entry) = split(/&/,$line,2);
                   9209: 			$allusers{$entry} = 1;
                   9210: 		    }
                   9211: 		}
1.253     stredwic 9212:             }
1.1136    raeburn  9213:             my @alluserslist=();
1.800     albertel 9214:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  9215:                 push(@alluserslist,$user.'&user');
1.253     stredwic 9216:             }
1.1136    raeburn  9217:             return (\@alluserslist);
1.253     stredwic 9218:         } else {
1.1136    raeburn  9219:             return ([],'missing username');
1.253     stredwic 9220:         }
1.955     raeburn  9221:     } elsif(!defined($getpropath)) {
1.1136    raeburn  9222:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   9223:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   9224:         return (\@all_domains);
1.955     raeburn  9225:     } else {
1.1136    raeburn  9226:         return ([],'missing domain');
1.275     stredwic 9227:     }
                   9228: }
                   9229: 
                   9230: # --------------------------------------------- GetFileTimestamp
                   9231: # This function utilizes dirlist and returns the date stamp for
                   9232: # when it was last modified.  It will also return an error of -1
                   9233: # if an error occurs
                   9234: 
                   9235: sub GetFileTimestamp {
1.955     raeburn  9236:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 9237:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   9238:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  9239:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   9240:                                     undef,$getuserdir);
                   9241:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9242:         return -1;
                   9243:     }
                   9244:     if (ref($fileref) eq 'ARRAY') {
                   9245:         my @stats = split('&',$fileref->[0]);
1.375     matthew  9246:         # @stats contains first the filename, then the stat output
                   9247:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 9248:     } else {
                   9249:         return -1;
1.253     stredwic 9250:     }
1.26      www      9251: }
                   9252: 
1.712     albertel 9253: sub stat_file {
                   9254:     my ($uri) = @_;
1.787     albertel 9255:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 9256: 
1.955     raeburn  9257:     my ($udom,$uname,$file);
1.712     albertel 9258:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   9259: 	($udom,$uname,$file) =
1.811     albertel 9260: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 9261: 	$file = 'userfiles/'.$file;
                   9262:     }
                   9263:     if ($uri =~ m-^/res/-) {
                   9264: 	($udom,$uname) = 
1.807     albertel 9265: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 9266: 	$file = $uri;
                   9267:     }
                   9268: 
                   9269:     if (!$udom || !$uname || !$file) {
                   9270: 	# unable to handle the uri
                   9271: 	return ();
                   9272:     }
1.956     raeburn  9273:     my $getpropath;
                   9274:     if ($file =~ /^userfiles\//) {
                   9275:         $getpropath = 1;
                   9276:     }
1.1136    raeburn  9277:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   9278:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9279:         return ();
                   9280:     } else {
                   9281:         if (ref($listref) eq 'ARRAY') {
                   9282:             my @stats = split('&',$listref->[0]);
                   9283: 	    shift(@stats); #filename is first
                   9284: 	    return @stats;
                   9285:         }
1.712     albertel 9286:     }
                   9287:     return ();
                   9288: }
                   9289: 
1.26      www      9290: # -------------------------------------------------------- Value of a Condition
                   9291: 
1.713     albertel 9292: # gets the value of a specific preevaluated condition
                   9293: #    stored in the string  $env{user.state.<cid>}
                   9294: # or looks up a condition reference in the bighash and if if hasn't
                   9295: # already been evaluated recurses into docondval to get the value of
                   9296: # the condition, then memoizing it to 
                   9297: #   $env{user.state.<cid>.<condition>}
1.40      www      9298: sub directcondval {
                   9299:     my $number=shift;
1.620     albertel 9300:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 9301: 	&Apache::lonuserstate::evalstate();
                   9302:     }
1.713     albertel 9303:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   9304: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   9305:     } elsif ($number =~ /^_/) {
                   9306: 	my $sub_condition;
                   9307: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   9308: 		&GDBM_READER(),0640)) {
                   9309: 	    $sub_condition=$bighash{'conditions'.$number};
                   9310: 	    untie(%bighash);
                   9311: 	}
                   9312: 	my $value = &docondval($sub_condition);
1.949     raeburn  9313: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 9314: 	return $value;
                   9315:     }
1.620     albertel 9316:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   9317:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      9318:     } else {
                   9319:        return 2;
                   9320:     }
                   9321: }
                   9322: 
1.713     albertel 9323: # get the collection of conditions for this resource
1.26      www      9324: sub condval {
                   9325:     my $condidx=shift;
1.54      www      9326:     my $allpathcond='';
1.713     albertel 9327:     foreach my $cond (split(/\|/,$condidx)) {
                   9328: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   9329: 	    $allpathcond.=
                   9330: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   9331: 	}
1.191     harris41 9332:     }
1.54      www      9333:     $allpathcond=~s/\|$//;
1.713     albertel 9334:     return &docondval($allpathcond);
                   9335: }
                   9336: 
                   9337: #evaluates an expression of conditions
                   9338: sub docondval {
                   9339:     my ($allpathcond) = @_;
                   9340:     my $result=0;
                   9341:     if ($env{'request.course.id'}
                   9342: 	&& defined($allpathcond)) {
                   9343: 	my $operand='|';
                   9344: 	my @stack;
                   9345: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   9346: 	    if ($chunk eq '(') {
                   9347: 		push @stack,($operand,$result);
                   9348: 	    } elsif ($chunk eq ')') {
                   9349: 		my $before=pop @stack;
                   9350: 		if (pop @stack eq '&') {
                   9351: 		    $result=$result>$before?$before:$result;
                   9352: 		} else {
                   9353: 		    $result=$result>$before?$result:$before;
                   9354: 		}
                   9355: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   9356: 		$operand=$chunk;
                   9357: 	    } else {
                   9358: 		my $new=directcondval($chunk);
                   9359: 		if ($operand eq '&') {
                   9360: 		    $result=$result>$new?$new:$result;
                   9361: 		} else {
                   9362: 		    $result=$result>$new?$result:$new;
                   9363: 		}
                   9364: 	    }
                   9365: 	}
1.26      www      9366:     }
                   9367:     return $result;
1.421     albertel 9368: }
                   9369: 
                   9370: # ---------------------------------------------------- Devalidate courseresdata
                   9371: 
                   9372: sub devalidatecourseresdata {
                   9373:     my ($coursenum,$coursedomain)=@_;
                   9374:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9375:     &devalidate_cache_new('courseres',$hashid);
1.28      www      9376: }
                   9377: 
1.763     www      9378: 
1.200     www      9379: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     9380: #
                   9381: #  Parameters:
                   9382: #      $coursenum    - Number of the course.
                   9383: #      $coursedomain - Domain at which the course was created.
                   9384: #  Returns:
                   9385: #     A hash of the course parameters along (I think) with timestamps
                   9386: #     and version info.
1.877     foxr     9387: 
1.624     albertel 9388: sub get_courseresdata {
                   9389:     my ($coursenum,$coursedomain)=@_;
1.200     www      9390:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   9391:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9392:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 9393:     my %dumpreply;
1.417     albertel 9394:     unless (defined($cached)) {
1.624     albertel 9395: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 9396: 	$result=\%dumpreply;
1.251     albertel 9397: 	my ($tmp) = keys(%dumpreply);
                   9398: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 9399: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 9400: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   9401: 	    return $tmp;
1.416     albertel 9402: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 9403: 	    $result=undef;
1.599     albertel 9404: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 9405: 	}
                   9406:     }
1.624     albertel 9407:     return $result;
                   9408: }
                   9409: 
1.633     albertel 9410: sub devalidateuserresdata {
                   9411:     my ($uname,$udom)=@_;
                   9412:     my $hashid="$udom:$uname";
                   9413:     &devalidate_cache_new('userres',$hashid);
                   9414: }
                   9415: 
1.624     albertel 9416: sub get_userresdata {
                   9417:     my ($uname,$udom)=@_;
                   9418:     #most student don\'t have any data set, check if there is some data
                   9419:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   9420: 
                   9421:     my $hashid="$udom:$uname";
                   9422:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   9423:     if (!defined($cached)) {
                   9424: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   9425: 	$result=\%resourcedata;
                   9426: 	&do_cache_new('userres',$hashid,$result,600);
                   9427:     }
                   9428:     my ($tmp)=keys(%$result);
                   9429:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   9430: 	return $result;
                   9431:     }
                   9432:     #error 2 occurs when the .db doesn't exist
                   9433:     if ($tmp!~/error: 2 /) {
1.672     albertel 9434: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 9435: 		 " Trying to get resource data for ".
                   9436: 		 $uname." at ".$udom.": ".
                   9437: 		 $tmp."</font>");
                   9438:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 9439: 	#&EXT_cache_set($udom,$uname);
                   9440: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 9441: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 9442:     }
                   9443:     return $tmp;
                   9444: }
1.879     foxr     9445: #----------------------------------------------- resdata - return resource data
                   9446: #  Purpose:
                   9447: #    Return resource data for either users or for a course.
                   9448: #  Parameters:
                   9449: #     $name      - Course/user name.
                   9450: #     $domain    - Name of the domain the user/course is registered on.
                   9451: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   9452: #     @which     - Array of names of resources desired.
                   9453: #  Returns:
                   9454: #     The value of the first reasource in @which that is found in the
                   9455: #     resource hash.
                   9456: #  Exceptional Conditions:
                   9457: #     If the $type passed in is not valid (not the string 'course' or 
                   9458: #     'user', an undefined  reference is returned.
                   9459: #     If none of the resources are found, an undef is returned
1.624     albertel 9460: sub resdata {
                   9461:     my ($name,$domain,$type,@which)=@_;
                   9462:     my $result;
                   9463:     if ($type eq 'course') {
                   9464: 	$result=&get_courseresdata($name,$domain);
                   9465:     } elsif ($type eq 'user') {
                   9466: 	$result=&get_userresdata($name,$domain);
                   9467:     }
                   9468:     if (!ref($result)) { return $result; }    
1.251     albertel 9469:     foreach my $item (@which) {
1.927     albertel 9470: 	if (defined($result->{$item->[0]})) {
                   9471: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 9472: 	}
1.250     albertel 9473:     }
1.291     albertel 9474:     return undef;
1.200     www      9475: }
                   9476: 
1.379     matthew  9477: #
                   9478: # EXT resource caching routines
                   9479: #
                   9480: 
                   9481: sub clear_EXT_cache_status {
1.383     albertel 9482:     &delenv('cache.EXT.');
1.379     matthew  9483: }
                   9484: 
                   9485: sub EXT_cache_status {
                   9486:     my ($target_domain,$target_user) = @_;
1.383     albertel 9487:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 9488:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  9489:         # We know already the user has no data
                   9490:         return 1;
                   9491:     } else {
                   9492:         return 0;
                   9493:     }
                   9494: }
                   9495: 
                   9496: sub EXT_cache_set {
                   9497:     my ($target_domain,$target_user) = @_;
1.383     albertel 9498:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  9499:     #&appenv({$cachename => time});
1.379     matthew  9500: }
                   9501: 
1.28      www      9502: # --------------------------------------------------------- Value of a Variable
1.58      www      9503: sub EXT {
1.715     albertel 9504: 
1.395     albertel 9505:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      9506:     unless ($varname) { return ''; }
1.218     albertel 9507:     #get real user name/domain, courseid and symb
                   9508:     my $courseid;
1.359     albertel 9509:     my $publicuser;
1.427     www      9510:     if ($symbparm) {
                   9511: 	$symbparm=&get_symb_from_alias($symbparm);
                   9512:     }
1.218     albertel 9513:     if (!($uname && $udom)) {
1.790     albertel 9514:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 9515:       if (!$symbparm) {	$symbparm=$cursymb; }
                   9516:     } else {
1.620     albertel 9517: 	$courseid=$env{'request.course.id'};
1.218     albertel 9518:     }
1.48      www      9519:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   9520:     my $rest;
1.320     albertel 9521:     if (defined($therest[0])) {
1.48      www      9522:        $rest=join('.',@therest);
                   9523:     } else {
                   9524:        $rest='';
                   9525:     }
1.320     albertel 9526: 
1.57      www      9527:     my $qualifierrest=$qualifier;
                   9528:     if ($rest) { $qualifierrest.='.'.$rest; }
                   9529:     my $spacequalifierrest=$space;
                   9530:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      9531:     if ($realm eq 'user') {
1.48      www      9532: # --------------------------------------------------------------- user.resource
                   9533: 	if ($space eq 'resource') {
1.651     albertel 9534: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   9535: 		  || defined($Apache::lonhomework::parsing_a_task))
                   9536: 		 &&
1.744     albertel 9537: 		 ($symbparm eq &symbread()) ) {	
                   9538: 		# if we are in the middle of processing the resource the
                   9539: 		# get the value we are planning on committing
                   9540:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   9541:                     return $Apache::lonhomework::results{$qualifierrest};
                   9542:                 } else {
                   9543:                     return $Apache::lonhomework::history{$qualifierrest};
                   9544:                 }
1.335     albertel 9545: 	    } else {
1.359     albertel 9546: 		my %restored;
1.620     albertel 9547: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 9548: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   9549: 		} else {
                   9550: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   9551: 		}
1.335     albertel 9552: 		return $restored{$qualifierrest};
                   9553: 	    }
1.48      www      9554: # ----------------------------------------------------------------- user.access
                   9555:         } elsif ($space eq 'access') {
1.218     albertel 9556: 	    # FIXME - not supporting calls for a specific user
1.48      www      9557:             return &allowed($qualifier,$rest);
                   9558: # ------------------------------------------ user.preferences, user.environment
                   9559:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 9560: 	    if (($uname eq $env{'user.name'}) &&
                   9561: 		($udom eq $env{'user.domain'})) {
                   9562: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 9563: 	    } else {
1.359     albertel 9564: 		my %returnhash;
                   9565: 		if (!$publicuser) {
                   9566: 		    %returnhash=&userenvironment($udom,$uname,
                   9567: 						 $qualifierrest);
                   9568: 		}
1.218     albertel 9569: 		return $returnhash{$qualifierrest};
                   9570: 	    }
1.48      www      9571: # ----------------------------------------------------------------- user.course
                   9572:         } elsif ($space eq 'course') {
1.218     albertel 9573: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9574:             return $env{join('.',('request.course',$qualifier))};
1.48      www      9575: # ------------------------------------------------------------------- user.role
                   9576:         } elsif ($space eq 'role') {
1.218     albertel 9577: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9578:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      9579:             if ($qualifier eq 'value') {
                   9580: 		return $role;
                   9581:             } elsif ($qualifier eq 'extent') {
                   9582:                 return $where;
                   9583:             }
                   9584: # ----------------------------------------------------------------- user.domain
                   9585:         } elsif ($space eq 'domain') {
1.218     albertel 9586:             return $udom;
1.48      www      9587: # ------------------------------------------------------------------- user.name
                   9588:         } elsif ($space eq 'name') {
1.218     albertel 9589:             return $uname;
1.48      www      9590: # ---------------------------------------------------- Any other user namespace
1.29      www      9591:         } else {
1.359     albertel 9592: 	    my %reply;
                   9593: 	    if (!$publicuser) {
                   9594: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   9595: 	    }
                   9596: 	    return $reply{$qualifierrest};
1.48      www      9597:         }
1.236     www      9598:     } elsif ($realm eq 'query') {
                   9599: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 9600:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   9601: 						[$spacequalifierrest]);
1.620     albertel 9602: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      9603:    } elsif ($realm eq 'request') {
1.48      www      9604: # ------------------------------------------------------------- request.browser
                   9605:         if ($space eq 'browser') {
1.1145    bisitz   9606:             return $env{'browser.'.$qualifier};
1.57      www      9607: # ------------------------------------------------------------ request.filename
                   9608:         } else {
1.620     albertel 9609:             return $env{'request.'.$spacequalifierrest};
1.29      www      9610:         }
1.28      www      9611:     } elsif ($realm eq 'course') {
1.48      www      9612: # ---------------------------------------------------------- course.description
1.620     albertel 9613:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      9614:     } elsif ($realm eq 'resource') {
1.165     www      9615: 
1.620     albertel 9616: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 9617: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   9618: 	}
1.693     albertel 9619: 
                   9620: 	if ($space eq 'title') {
                   9621: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   9622: 	    return &gettitle($symbparm);
                   9623: 	}
                   9624: 	
                   9625: 	if ($space eq 'map') {
                   9626: 	    my ($map) = &decode_symb($symbparm);
                   9627: 	    return &symbread($map);
                   9628: 	}
1.905     albertel 9629: 	if ($space eq 'filename') {
                   9630: 	    if ($symbparm) {
                   9631: 		return &clutter((&decode_symb($symbparm))[2]);
                   9632: 	    }
                   9633: 	    return &hreflocation('',$env{'request.filename'});
                   9634: 	}
1.693     albertel 9635: 
                   9636: 	my ($section, $group, @groups);
1.593     albertel 9637: 	my ($courselevelm,$courselevel);
1.539     albertel 9638: 	if ($symbparm && defined($courseid) && 
1.620     albertel 9639: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      9640: 
1.218     albertel 9641: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      9642: 
1.60      www      9643: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 9644: 	    my $symbp=$symbparm;
1.735     albertel 9645: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 9646: 
                   9647: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   9648: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   9649: 
1.620     albertel 9650: 	    if (($env{'user.name'} eq $uname) &&
                   9651: 		($env{'user.domain'} eq $udom)) {
                   9652: 		$section=$env{'request.course.sec'};
1.733     raeburn  9653:                 @groups = split(/:/,$env{'request.course.groups'});  
                   9654:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 9655: 	    } else {
1.539     albertel 9656: 		if (! defined($usection)) {
1.551     albertel 9657: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 9658: 		} else {
                   9659: 		    $section = $usection;
                   9660: 		}
1.733     raeburn  9661:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 9662: 	    }
                   9663: 
                   9664: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   9665: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   9666: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   9667: 
1.593     albertel 9668: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 9669: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 9670: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      9671: 
1.60      www      9672: # ----------------------------------------------------------- first, check user
1.624     albertel 9673: 
                   9674: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 9675: 				       ([$courselevelr,'resource'],
                   9676: 					[$courselevelm,'map'     ],
                   9677: 					[$courselevel, 'course'  ]));
1.931     albertel 9678: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      9679: 
1.594     albertel 9680: # ------------------------------------------------ second, check some of course
1.684     raeburn  9681:             my $coursereply;
1.691     raeburn  9682:             if (@groups > 0) {
                   9683:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   9684:                                        $mapparm,$spacequalifierrest);
1.927     albertel 9685:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  9686:             }
1.96      www      9687: 
1.684     raeburn  9688: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 9689: 				  $env{'course.'.$courseid.'.domain'},
                   9690: 				  'course',
                   9691: 				  ([$seclevelr,   'resource'],
                   9692: 				   [$seclevelm,   'map'     ],
                   9693: 				   [$seclevel,    'course'  ],
                   9694: 				   [$courselevelr,'resource']));
                   9695: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      9696: 
1.60      www      9697: # ------------------------------------------------------ third, check map parms
1.218     albertel 9698: 	    my %parmhash=();
                   9699: 	    my $thisparm='';
                   9700: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 9701: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 9702: 		    &GDBM_READER(),0640)) {
1.218     albertel 9703: 		$thisparm=$parmhash{$symbparm};
                   9704: 		untie(%parmhash);
                   9705: 	    }
1.927     albertel 9706: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 9707: 	}
1.594     albertel 9708: # ------------------------------------------ fourth, look in resource metadata
1.71      www      9709: 
1.218     albertel 9710: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 9711: 	my $filename;
                   9712: 	if (!$symbparm) { $symbparm=&symbread(); }
                   9713: 	if ($symbparm) {
1.409     www      9714: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 9715: 	} else {
1.620     albertel 9716: 	    $filename=$env{'request.filename'};
1.282     albertel 9717: 	}
                   9718: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 9719: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 9720: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 9721: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      9722: 
1.927     albertel 9723: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 9724: 	if ($symbparm && defined($courseid) && 
1.620     albertel 9725: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 9726: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   9727: 				     $env{'course.'.$courseid.'.domain'},
                   9728: 				     'course',
1.927     albertel 9729: 				     ([$courselevelm,'map'   ],
                   9730: 				      [$courselevel, 'course']));
                   9731: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 9732: 	}
1.145     www      9733: # ------------------------------------------------------------------ Cascade up
1.218     albertel 9734: 	unless ($space eq '0') {
1.336     albertel 9735: 	    my @parts=split(/_/,$space);
                   9736: 	    my $id=pop(@parts);
                   9737: 	    my $part=join('_',@parts);
                   9738: 	    if ($part eq '') { $part='0'; }
1.927     albertel 9739: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 9740: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  9741: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 9742: 	}
1.395     albertel 9743: 	if ($recurse) { return undef; }
                   9744: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 9745: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      9746: # ---------------------------------------------------- Any other user namespace
                   9747:     } elsif ($realm eq 'environment') {
                   9748: # ----------------------------------------------------------------- environment
1.620     albertel 9749: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   9750: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 9751: 	} else {
1.770     albertel 9752: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   9753: 		return '';
                   9754: 	    }
1.219     albertel 9755: 	    my %returnhash=&userenvironment($udom,$uname,
                   9756: 					    $spacequalifierrest);
                   9757: 	    return $returnhash{$spacequalifierrest};
                   9758: 	}
1.28      www      9759:     } elsif ($realm eq 'system') {
1.48      www      9760: # ----------------------------------------------------------------- system.time
                   9761: 	if ($space eq 'time') {
                   9762: 	    return time;
                   9763:         }
1.696     albertel 9764:     } elsif ($realm eq 'server') {
                   9765: # ----------------------------------------------------------------- system.time
                   9766: 	if ($space eq 'name') {
                   9767: 	    return $ENV{'SERVER_NAME'};
                   9768:         }
1.28      www      9769:     }
1.48      www      9770:     return '';
1.61      www      9771: }
                   9772: 
1.927     albertel 9773: sub get_reply {
                   9774:     my ($reply_value) = @_;
1.940     raeburn  9775:     if (ref($reply_value) eq 'ARRAY') {
                   9776:         if (wantarray) {
                   9777: 	    return @$reply_value;
                   9778:         }
                   9779:         return $reply_value->[0];
                   9780:     } else {
                   9781:         return $reply_value;
1.927     albertel 9782:     }
                   9783: }
                   9784: 
1.691     raeburn  9785: sub check_group_parms {
                   9786:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   9787:     my @groupitems = ();
                   9788:     my $resultitem;
1.927     albertel 9789:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  9790:     foreach my $group (@{$groups}) {
                   9791:         foreach my $level (@levels) {
1.927     albertel 9792:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   9793:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  9794:         }
                   9795:     }
                   9796:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   9797:                             $env{'course.'.$courseid.'.domain'},
                   9798:                                      'course',@groupitems);
                   9799:     return $coursereply;
                   9800: }
                   9801: 
                   9802: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  9803:     my ($courseid,@groups) = @_;
                   9804:     @groups = sort(@groups);
1.691     raeburn  9805:     return @groups;
                   9806: }
                   9807: 
1.395     albertel 9808: sub packages_tab_default {
                   9809:     my ($uri,$varname)=@_;
                   9810:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 9811: 
                   9812:     my (@extension,@specifics,$do_default);
                   9813:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 9814: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 9815: 	if ($pack_type eq 'default') {
                   9816: 	    $do_default=1;
                   9817: 	} elsif ($pack_type eq 'extension') {
                   9818: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 9819: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 9820: 	    # only look at packages defaults for packages that this id is
1.738     albertel 9821: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   9822: 	}
                   9823:     }
                   9824:     # first look for a package that matches the requested part id
                   9825:     foreach my $package (@specifics) {
                   9826: 	my (undef,$pack_type,$pack_part)=@{$package};
                   9827: 	next if ($pack_part ne $part);
                   9828: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9829: 	    return $packagetab{"$pack_type&$name&default"};
                   9830: 	}
                   9831:     }
                   9832:     # look for any possible matching non extension_ package
                   9833:     foreach my $package (@specifics) {
                   9834: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 9835: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9836: 	    return $packagetab{"$pack_type&$name&default"};
                   9837: 	}
1.585     albertel 9838: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 9839: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   9840: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 9841: 	}
                   9842:     }
1.738     albertel 9843:     # look for any posible extension_ match
                   9844:     foreach my $package (@extension) {
                   9845: 	my ($package,$pack_type)=@{$package};
                   9846: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9847: 	    return $packagetab{"$pack_type&$name&default"};
                   9848: 	}
                   9849: 	if (defined($packagetab{$package."&$name&default"})) {
                   9850: 	    return $packagetab{$package."&$name&default"};
                   9851: 	}
                   9852:     }
                   9853:     # look for a global default setting
                   9854:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   9855: 	return $packagetab{"default&$name&default"};
                   9856:     }
1.395     albertel 9857:     return undef;
                   9858: }
                   9859: 
1.334     albertel 9860: sub add_prefix_and_part {
                   9861:     my ($prefix,$part)=@_;
                   9862:     my $keyroot;
                   9863:     if (defined($prefix) && $prefix !~ /^__/) {
                   9864: 	# prefix that has a part already
                   9865: 	$keyroot=$prefix;
                   9866:     } elsif (defined($prefix)) {
                   9867: 	# prefix that is missing a part
                   9868: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   9869:     } else {
                   9870: 	# no prefix at all
                   9871: 	if (defined($part)) { $keyroot='_'.$part; }
                   9872:     }
                   9873:     return $keyroot;
                   9874: }
                   9875: 
1.71      www      9876: # ---------------------------------------------------------------- Get metadata
                   9877: 
1.599     albertel 9878: my %metaentry;
1.1070    www      9879: my %importedpartids;
1.71      www      9880: sub metadata {
1.176     www      9881:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      9882:     $uri=&declutter($uri);
1.288     albertel 9883:     # if it is a non metadata possible uri return quickly
1.529     albertel 9884:     if (($uri eq '') || 
                   9885: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 9886: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1108    raeburn  9887:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 9888: 	return undef;
                   9889:     }
1.1140    www      9890:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
1.924     albertel 9891: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 9892: 	return undef;
1.288     albertel 9893:     }
1.73      www      9894:     my $filename=$uri;
                   9895:     $uri=~s/\.meta$//;
1.172     www      9896: #
                   9897: # Is the metadata already cached?
1.177     www      9898: # Look at timestamp of caching
1.172     www      9899: # Everything is cached by the main uri, libraries are never directly cached
                   9900: #
1.428     albertel 9901:     if (!defined($liburi)) {
1.599     albertel 9902: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 9903: 	if (defined($cached)) { return $result->{':'.$what}; }
                   9904:     }
                   9905:     {
1.1069    www      9906: # Imported parts would go here
1.1070    www      9907:         my %importedids=();
                   9908:         my @origfileimportpartids=();
1.1069    www      9909:         my $importedparts=0;
1.172     www      9910: #
                   9911: # Is this a recursive call for a library?
                   9912: #
1.599     albertel 9913: #	if (! exists($metacache{$uri})) {
                   9914: #	    $metacache{$uri}={};
                   9915: #	}
1.924     albertel 9916: 	my $cachetime = 60*60;
1.171     www      9917:         if ($liburi) {
                   9918: 	    $liburi=&declutter($liburi);
                   9919:             $filename=$liburi;
1.401     bowersj2 9920:         } else {
1.599     albertel 9921: 	    &devalidate_cache_new('meta',$uri);
                   9922: 	    undef(%metaentry);
1.401     bowersj2 9923: 	}
1.140     www      9924:         my %metathesekeys=();
1.73      www      9925:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 9926: 	my $metastring;
1.1140    www      9927: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 9928: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 9929: 	    $metastring = 
1.929     albertel 9930: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 9931: 					  ('grade_target' => 'meta'));
                   9932: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  9933: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   9934:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 9935: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 9936: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 9937: 	    $metastring=&getfile($file);
1.489     albertel 9938: 	}
1.208     albertel 9939:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      9940:         my $token;
1.140     www      9941:         undef %metathesekeys;
1.71      www      9942:         while ($token=$parser->get_token) {
1.339     albertel 9943: 	    if ($token->[0] eq 'S') {
                   9944: 		if (defined($token->[2]->{'package'})) {
1.172     www      9945: #
                   9946: # This is a package - get package info
                   9947: #
1.339     albertel 9948: 		    my $package=$token->[2]->{'package'};
                   9949: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9950: 		    if (defined($token->[2]->{'id'})) { 
                   9951: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   9952: 		    }
1.599     albertel 9953: 		    if ($metaentry{':packages'}) {
                   9954: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 9955: 		    } else {
1.599     albertel 9956: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 9957: 		    }
1.736     albertel 9958: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 9959: 			my $part=$keyroot;
                   9960: 			$part=~s/^\_//;
1.736     albertel 9961: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   9962: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   9963: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 9964: 			    # ignore package.tab specified default values
                   9965:                             # here &package_tab_default() will fetch those
                   9966: 			    if ($subp eq 'default') { next; }
1.736     albertel 9967: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 9968: 			    my $unikey;
                   9969: 			    if ($pack =~ /_0$/) {
                   9970: 				$unikey='parameter_0_'.$name;
                   9971: 				$part=0;
                   9972: 			    } else {
                   9973: 				$unikey='parameter'.$keyroot.'_'.$name;
                   9974: 			    }
1.339     albertel 9975: 			    if ($subp eq 'display') {
                   9976: 				$value.=' [Part: '.$part.']';
                   9977: 			    }
1.599     albertel 9978: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 9979: 			    $metathesekeys{$unikey}=1;
1.599     albertel 9980: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   9981: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 9982: 			    }
1.599     albertel 9983: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   9984: 				$metaentry{':'.$unikey}=
                   9985: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 9986: 			    }
1.339     albertel 9987: 			}
                   9988: 		    }
                   9989: 		} else {
1.172     www      9990: #
                   9991: # This is not a package - some other kind of start tag
1.339     albertel 9992: #
                   9993: 		    my $entry=$token->[1];
1.1068    www      9994: 		    my $unikey='';
1.175     www      9995: 
1.339     albertel 9996: 		    if ($entry eq 'import') {
1.175     www      9997: #
                   9998: # Importing a library here
1.339     albertel 9999: #
1.1067    www      10000:                         my $location=$parser->get_text('/import');
                   10001:                         my $dir=$filename;
                   10002:                         $dir=~s|[^/]*$||;
                   10003:                         $location=&filelocation($dir,$location);
1.1069    www      10004:                        
1.1068    www      10005:                         my $importmode=$token->[2]->{'importmode'};
                   10006:                         if ($importmode eq 'problem') {
1.1069    www      10007: # Import as problem/response
1.1068    www      10008:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10009:                         } elsif ($importmode eq 'part') {
                   10010: # Import as part(s)
1.1069    www      10011:                            $importedparts=1;
                   10012: # We need to get the original file and the imported file to get the part order correct
                   10013: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   10014: # Load and inspect original file
1.1070    www      10015:                            if ($#origfileimportpartids<0) {
                   10016:                               undef(%importedpartids);
                   10017:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   10018:                               my $origfile=&getfile($origfilelocation);
                   10019:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10020:                            }
                   10021: 
1.1069    www      10022: # Load and inspect imported file
                   10023:                            my $impfile=&getfile($location);
                   10024:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10025:                            if ($#impfilepartids>=0) {
                   10026: # This problem had parts
1.1070    www      10027:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      10028:                            } else {
                   10029: # Importing by turning a single problem into a problem part
                   10030: # It gets the import-tags ID as part-ID
                   10031:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      10032:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      10033:                            }
1.1068    www      10034:                         } else {
                   10035: # Normal import
                   10036:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10037:                            if (defined($token->[2]->{'id'})) {
                   10038:                               $unikey.='_'.$token->[2]->{'id'};
                   10039:                            }
1.1067    www      10040:                         }
                   10041: 
1.339     albertel 10042: 			if ($depthcount<20) {
1.736     albertel 10043: 			    my $metadata = 
                   10044: 				&metadata($uri,'keys', $location,$unikey,
                   10045: 					  $depthcount+1);
                   10046: 			    foreach my $meta (split(',',$metadata)) {
                   10047: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   10048: 				$metathesekeys{$meta}=1;
1.339     albertel 10049: 			    }
1.1068    www      10050: 			
                   10051:                         }
1.1067    www      10052: 		    } else {
                   10053: #
                   10054: # Not importing, some other kind of non-package, non-library start tag
                   10055: # 
                   10056:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10057:                         if (defined($token->[2]->{'id'})) {
                   10058:                             $unikey.='_'.$token->[2]->{'id'};
                   10059:                         }
1.339     albertel 10060: 			if (defined($token->[2]->{'name'})) { 
                   10061: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   10062: 			}
                   10063: 			$metathesekeys{$unikey}=1;
1.736     albertel 10064: 			foreach my $param (@{$token->[3]}) {
                   10065: 			    $metaentry{':'.$unikey.'.'.$param} =
                   10066: 				$token->[2]->{$param};
1.339     albertel 10067: 			}
                   10068: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 10069: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 10070: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   10071: 		 # only ws inside the tag, and not in default, so use default
                   10072: 		 # as value
1.599     albertel 10073: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 10074: 			} elsif ( $internaltext =~ /\S/ ) {
                   10075: 		  # something interesting inside the tag
                   10076: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 10077: 			} else {
1.908     albertel 10078: 		  # no interesting values, don't set a default
1.339     albertel 10079: 			}
1.172     www      10080: # end of not-a-package not-a-library import
1.339     albertel 10081: 		    }
1.172     www      10082: # end of not-a-package start tag
1.339     albertel 10083: 		}
1.172     www      10084: # the next is the end of "start tag"
1.339     albertel 10085: 	    }
                   10086: 	}
1.483     albertel 10087: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 10088: 	$extension = lc($extension);
                   10089: 	if ($extension eq 'htm') { $extension='html'; }
                   10090: 
1.737     albertel 10091: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 10092: 	    #no specific packages #how's our extension
                   10093: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 10094: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 10095: 					 \%metathesekeys);
                   10096: 	}
1.883     albertel 10097: 
                   10098: 	if (!exists($metaentry{':packages'})
                   10099: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 10100: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 10101: 		#no specific packages well let's get default then
                   10102: 		if ($key!~/^default&/) { next; }
1.488     albertel 10103: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 10104: 					     \%metathesekeys);
                   10105: 	    }
                   10106: 	}
1.338     www      10107: # are there custom rights to evaluate
1.599     albertel 10108: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 10109: 
1.338     www      10110:     #
                   10111:     # Importing a rights file here
1.339     albertel 10112:     #
                   10113: 	    unless ($depthcount) {
1.599     albertel 10114: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 10115: 		my $dir=$filename;
                   10116: 		$dir=~s|[^/]*$||;
                   10117: 		$location=&filelocation($dir,$location);
1.736     albertel 10118: 		my $rights_metadata =
                   10119: 		    &metadata($uri,'keys',$location,'_rights',
                   10120: 			      $depthcount+1);
                   10121: 		foreach my $rights (split(',',$rights_metadata)) {
                   10122: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   10123: 		    $metathesekeys{$rights}=1;
1.339     albertel 10124: 		}
                   10125: 	    }
                   10126: 	}
1.737     albertel 10127: 	# uniqifiy package listing
                   10128: 	my %seen;
                   10129: 	my @uniq_packages =
                   10130: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   10131: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   10132: 
1.1070    www      10133:         if ($importedparts) {
                   10134: # We had imported parts and need to rebuild partorder
                   10135:            $metaentry{':partorder'}='';
                   10136:            $metathesekeys{'partorder'}=1;
                   10137:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   10138:                if ($origfileimportpartids[$index] eq 'part') {
                   10139: # original part, part of the problem
                   10140:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   10141:                } else {
                   10142: # we have imported parts at this position
                   10143:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   10144:                }
                   10145:            }
                   10146:            $metaentry{':partorder'}=~s/^\,//;
                   10147:         }
                   10148: 
1.737     albertel 10149: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 10150: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   10151: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 10152: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      10153: # this is the end of "was not already recently cached
1.71      www      10154:     }
1.599     albertel 10155:     return $metaentry{':'.$what};
1.261     albertel 10156: }
                   10157: 
1.488     albertel 10158: sub metadata_create_package_def {
1.483     albertel 10159:     my ($uri,$key,$package,$metathesekeys)=@_;
                   10160:     my ($pack,$name,$subp)=split(/\&/,$key);
                   10161:     if ($subp eq 'default') { next; }
                   10162:     
1.599     albertel 10163:     if (defined($metaentry{':packages'})) {
                   10164: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 10165:     } else {
1.599     albertel 10166: 	$metaentry{':packages'}=$package;
1.483     albertel 10167:     }
                   10168:     my $value=$packagetab{$key};
                   10169:     my $unikey;
                   10170:     $unikey='parameter_0_'.$name;
1.599     albertel 10171:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 10172:     $$metathesekeys{$unikey}=1;
1.599     albertel 10173:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10174: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 10175:     }
1.599     albertel 10176:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   10177: 	$metaentry{':'.$unikey}=
                   10178: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 10179:     }
                   10180: }
                   10181: 
1.261     albertel 10182: sub metadata_generate_part0 {
                   10183:     my ($metadata,$metacache,$uri) = @_;
                   10184:     my %allnames;
1.737     albertel 10185:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 10186: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 10187: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   10188: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 10189: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 10190: 	    $allnames{$name}=$part;
                   10191: 	  }
                   10192: 	}
                   10193:     }
                   10194:     foreach my $name (keys(%allnames)) {
                   10195:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 10196:       my $key=":parameter_0_$name";
1.261     albertel 10197:       $$metacache{"$key.part"}='0';
                   10198:       $$metacache{"$key.name"}=$name;
1.428     albertel 10199:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 10200: 					   $allnames{$name}.'_'.$name.
                   10201: 					   '.type'};
1.428     albertel 10202:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 10203: 			     '.display'};
1.644     www      10204:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 10205:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 10206:       $$metacache{"$key.display"}=$olddis;
                   10207:     }
1.71      www      10208: }
                   10209: 
1.764     albertel 10210: # ------------------------------------------------------ Devalidate title cache
                   10211: 
                   10212: sub devalidate_title_cache {
                   10213:     my ($url)=@_;
                   10214:     if (!$env{'request.course.id'}) { return; }
                   10215:     my $symb=&symbread($url);
                   10216:     if (!$symb) { return; }
                   10217:     my $key=$env{'request.course.id'}."\0".$symb;
                   10218:     &devalidate_cache_new('title',$key);
                   10219: }
                   10220: 
1.1014    droeschl 10221: # ------------------------------------------------- Get the title of a course
                   10222: 
                   10223: sub current_course_title {
                   10224:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   10225: }
1.301     www      10226: # ------------------------------------------------- Get the title of a resource
                   10227: 
                   10228: sub gettitle {
                   10229:     my $urlsymb=shift;
                   10230:     my $symb=&symbread($urlsymb);
1.534     albertel 10231:     if ($symb) {
1.620     albertel 10232: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 10233: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 10234: 	if (defined($cached)) { 
                   10235: 	    return $result;
                   10236: 	}
1.534     albertel 10237: 	my ($map,$resid,$url)=&decode_symb($symb);
                   10238: 	my $title='';
1.907     albertel 10239: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   10240: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   10241: 	} else {
                   10242: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10243: 		    &GDBM_READER(),0640)) {
                   10244: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   10245: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   10246: 		untie(%bighash);
                   10247: 	    }
1.534     albertel 10248: 	}
                   10249: 	$title=~s/\&colon\;/\:/gs;
                   10250: 	if ($title) {
1.1159    www      10251: # Remember both $symb and $title for dynamic metadata
                   10252:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      10253:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      10254: # Cache this title and then return it
1.599     albertel 10255: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 10256: 	}
                   10257: 	$urlsymb=$url;
                   10258:     }
                   10259:     my $title=&metadata($urlsymb,'title');
                   10260:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   10261:     return $title;
1.301     www      10262: }
1.613     albertel 10263: 
1.1172.2.13  raeburn  10264: sub getdocspath {
                   10265:     my ($symb) = @_;
                   10266:     my $path;
                   10267:     if ($symb) {
                   10268:         my ($mapurl,$id,$resurl) = &decode_symb($symb);
                   10269:         if ($resurl=~/\.(sequence|page)$/) {
                   10270:             $mapurl=$resurl;
                   10271:         } elsif ($resurl eq 'adm/navmaps') {
                   10272:             $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   10273:         }
                   10274:         my $mapresobj;
                   10275:         my $navmap = Apache::lonnavmaps::navmap->new();
                   10276:         if (ref($navmap)) {
                   10277:             $mapresobj = $navmap->getResourceByUrl($mapurl);
                   10278:         }
                   10279:         $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   10280:         my $type=$2;
                   10281:         if (ref($mapresobj)) {
                   10282:             my $pcslist = $mapresobj->map_hierarchy();
                   10283:             if ($pcslist ne '') {
                   10284:                 foreach my $pc (split(/,/,$pcslist)) {
                   10285:                     next if ($pc <= 1);
                   10286:                     my $res = $navmap->getByMapPc($pc);
                   10287:                     if (ref($res)) {
                   10288:                         my $thisurl = $res->src();
                   10289:                         $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   10290:                         my $thistitle = $res->title();
                   10291:                         $path .= '&'.
                   10292:                                  &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
                   10293:                                  &Apache::lonhtmlcommon::entity_encode($thistitle).
                   10294:                                  ':'.$res->randompick().
                   10295:                                  ':'.$res->randomout().
                   10296:                                  ':'.$res->encrypted().
                   10297:                                  ':'.$res->randomorder().
                   10298:                                  ':'.$res->is_page();
                   10299:                     }
                   10300:                 }
                   10301:             }
                   10302:             $path =~ s/^\&//;
                   10303:             my $maptitle = $mapresobj->title();
                   10304:             if ($mapurl eq 'default') {
                   10305:                 $maptitle = 'Main Course Documents';
                   10306:             }
                   10307:             $path .= ($path ne '')? '&' : ''.
                   10308:                     &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
                   10309:                     &Apache::lonhtmlcommon::entity_encode($maptitle).
                   10310:                     ':'.$mapresobj->randompick().
                   10311:                     ':'.$mapresobj->randomout().
                   10312:                     ':'.$mapresobj->encrypted().
                   10313:                     ':'.$mapresobj->randomorder().
                   10314:                     ':'.$mapresobj->is_page();
                   10315:         } else {
                   10316:             my $maptitle = &gettitle($mapurl);
                   10317:             my $ispage;
                   10318:             if ($mapurl =~ /\.page$/) {
                   10319:                 $ispage = 1;
                   10320:             }
                   10321:             if ($mapurl eq 'default') {
                   10322:                 $maptitle = 'Main Course Documents';
                   10323:             }
                   10324:             $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
                   10325:                     &Apache::lonhtmlcommon::entity_encode($maptitle).':::::'.$ispage;
                   10326:         }
                   10327:         unless ($mapurl eq 'default') {
                   10328:             $path = 'default&'.
                   10329:                     &Apache::lonhtmlcommon::entity_encode('Main Course Documents').
                   10330:                     ':::::&'.$path;
                   10331:         }
                   10332:     }
                   10333:     return $path;
                   10334: }
                   10335: 
1.614     albertel 10336: sub get_slot {
                   10337:     my ($which,$cnum,$cdom)=@_;
                   10338:     if (!$cnum || !$cdom) {
1.790     albertel 10339: 	(undef,my $courseid)=&whichuser();
1.620     albertel 10340: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   10341: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 10342:     }
1.703     albertel 10343:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   10344:     my %slotinfo;
                   10345:     if (exists($remembered{$key})) {
                   10346: 	$slotinfo{$which} = $remembered{$key};
                   10347:     } else {
                   10348: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   10349: 	&Apache::lonhomework::showhash(%slotinfo);
                   10350: 	my ($tmp)=keys(%slotinfo);
                   10351: 	if ($tmp=~/^error:/) { return (); }
                   10352: 	$remembered{$key} = $slotinfo{$which};
                   10353:     }
1.616     albertel 10354:     if (ref($slotinfo{$which}) eq 'HASH') {
                   10355: 	return %{$slotinfo{$which}};
                   10356:     }
                   10357:     return $slotinfo{$which};
1.614     albertel 10358: }
1.1150    raeburn  10359: 
                   10360: sub get_reservable_slots {
                   10361:     my ($cnum,$cdom,$uname,$udom) = @_;
                   10362:     my $now = time;
                   10363:     my $reservable_info;
                   10364:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   10365:     if (exists($remembered{$key})) {
                   10366:         $reservable_info = $remembered{$key};
                   10367:     } else {
                   10368:         my %resv;
                   10369:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   10370:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   10371:         $reservable_info = \%resv;
                   10372:         $remembered{$key} = $reservable_info;
                   10373:     }
                   10374:     return $reservable_info;
                   10375: }
                   10376: 
                   10377: sub get_course_slots {
                   10378:     my ($cnum,$cdom) = @_;
                   10379:     my $hashid=$cnum.':'.$cdom;
                   10380:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   10381:     if (defined($cached)) {
                   10382:         if (ref($result) eq 'HASH') {
                   10383:             return %{$result};
                   10384:         }
                   10385:     } else {
                   10386:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   10387:         my ($tmp) = keys(%slots);
                   10388:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   10389:             &Apache::lonnet::do_cache_new('allslots',$hashid,\%slots,600);
                   10390:             return %slots;
                   10391:         }
                   10392:     }
                   10393:     return;
                   10394: }
                   10395: 
                   10396: sub devalidate_slots_cache {
                   10397:     my ($cnum,$cdom)=@_;
                   10398:     my $hashid=$cnum.':'.$cdom;
                   10399:     &devalidate_cache_new('allslots',$hashid);
                   10400: }
                   10401: 
1.1172.2.8  raeburn  10402: sub get_coursechange {
                   10403:     my ($cdom,$cnum) = @_;
                   10404:     if ($cdom eq '' || $cnum eq '') {
                   10405:         return unless ($env{'request.course.id'});
                   10406:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10407:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10408:     }
                   10409:     my $hashid=$cdom.'_'.$cnum;
                   10410:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   10411:     if ((defined($cached)) && ($change ne '')) {
                   10412:         return $change;
                   10413:     } else {
                   10414:         my %crshash;
                   10415:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   10416:         if ($crshash{'internal.contentchange'} eq '') {
                   10417:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   10418:             if ($change eq '') {
                   10419:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   10420:                 $change = $crshash{'internal.created'};
                   10421:             }
                   10422:         } else {
                   10423:             $change = $crshash{'internal.contentchange'};
                   10424:         }
                   10425:         my $cachetime = 600;
                   10426:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   10427:     }
                   10428:     return $change;
                   10429: }
                   10430: 
                   10431: sub devalidate_coursechange_cache {
                   10432:     my ($cnum,$cdom)=@_;
                   10433:     my $hashid=$cnum.':'.$cdom;
                   10434:     &devalidate_cache_new('crschange',$hashid);
                   10435: }
                   10436: 
1.31      www      10437: # ------------------------------------------------- Update symbolic store links
                   10438: 
                   10439: sub symblist {
                   10440:     my ($mapname,%newhash)=@_;
1.438     www      10441:     $mapname=&deversion(&declutter($mapname));
1.31      www      10442:     my %hash;
1.620     albertel 10443:     if (($env{'request.course.fn'}) && (%newhash)) {
                   10444:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10445:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  10446: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 10447: 		next if ($url eq 'last_known'
                   10448: 			 && $env{'form.no_update_last_known'});
                   10449: 		$hash{declutter($url)}=&encode_symb($mapname,
                   10450: 						    $newhash{$url}->[1],
                   10451: 						    $newhash{$url}->[0]);
1.191     harris41 10452:             }
1.31      www      10453:             if (untie(%hash)) {
                   10454: 		return 'ok';
                   10455:             }
                   10456:         }
                   10457:     }
                   10458:     return 'error';
1.212     www      10459: }
                   10460: 
                   10461: # --------------------------------------------------------------- Verify a symb
                   10462: 
                   10463: sub symbverify {
1.1172.2.11  raeburn  10464:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      10465:     my $thisfn=$thisurl;
1.439     www      10466:     $thisfn=&declutter($thisfn);
1.215     www      10467: # direct jump to resource in page or to a sequence - will construct own symbs
                   10468:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   10469: # check URL part
1.409     www      10470:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      10471: 
1.431     www      10472:     unless ($url eq $thisfn) { return 0; }
1.213     www      10473: 
1.216     www      10474:     $symb=&symbclean($symb);
1.510     www      10475:     $thisurl=&deversion($thisurl);
1.439     www      10476:     $thisfn=&deversion($thisfn);
1.213     www      10477: 
                   10478:     my %bighash;
                   10479:     my $okay=0;
1.431     www      10480: 
1.620     albertel 10481:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10482:                             &GDBM_READER(),0640)) {
1.1172.2.13  raeburn  10483:         my $noclutter;
1.1032    raeburn  10484:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   10485:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  10486:             if ($map =~ m{^uploaded/.+\.page$}) {
                   10487:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   10488:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   10489:                 $noclutter = 1;
                   10490:             }
                   10491:         }
                   10492:         my $ids;
                   10493:         if ($noclutter) {
                   10494:             $ids=$bighash{'ids_'.$thisurl};
                   10495:         } else {
                   10496:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  10497:         }
1.1102    raeburn  10498:         unless ($ids) {
1.1172.2.13  raeburn  10499:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  10500:             $ids=$bighash{$idkey};
1.216     www      10501:         }
                   10502:         if ($ids) {
                   10503: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  10504:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   10505:                 $symb =~ s/\?.+$//;
                   10506:             }
1.800     albertel 10507: 	    foreach my $id (split(/\,/,$ids)) {
                   10508: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      10509:                if (
                   10510:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  10511:    eq $symb) {
1.1172.2.11  raeburn  10512:                    if (ref($encstate)) {
                   10513:                        $$encstate = $bighash{'encrypted_'.$id};
                   10514:                    }
1.1172.2.13  raeburn  10515:                    if (($env{'request.role.adv'}) ||
                   10516:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  10517:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  10518:                        $okay=1;
                   10519:                        last;
                   10520:                    }
                   10521:                }
                   10522:            }
1.216     www      10523:         }
1.213     www      10524: 	untie(%bighash);
                   10525:     }
                   10526:     return $okay;
1.31      www      10527: }
                   10528: 
1.210     www      10529: # --------------------------------------------------------------- Clean-up symb
                   10530: 
                   10531: sub symbclean {
                   10532:     my $symb=shift;
1.568     albertel 10533:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      10534: # remove version from map
                   10535:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      10536: 
1.210     www      10537: # remove version from URL
                   10538:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      10539: 
1.507     www      10540: # remove wrapper
                   10541: 
1.510     www      10542:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 10543:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      10544:     return $symb;
1.409     www      10545: }
                   10546: 
                   10547: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 10548: 
                   10549: sub encode_symb {
                   10550:     my ($map,$resid,$url)=@_;
                   10551:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   10552: }
1.409     www      10553: 
                   10554: sub decode_symb {
1.568     albertel 10555:     my $symb=shift;
                   10556:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   10557:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      10558:     return (&fixversion($map),$resid,&fixversion($url));
                   10559: }
                   10560: 
                   10561: sub fixversion {
                   10562:     my $fn=shift;
1.609     banghart 10563:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      10564:     my %bighash;
                   10565:     my $uri=&clutter($fn);
1.620     albertel 10566:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      10567: # is this cached?
1.599     albertel 10568:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      10569:     if (defined($cached)) { return $result; }
                   10570: # unfortunately not cached, or expired
1.620     albertel 10571:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      10572: 	    &GDBM_READER(),0640)) {
                   10573:  	if ($bighash{'version_'.$uri}) {
                   10574:  	    my $version=$bighash{'version_'.$uri};
1.444     www      10575:  	    unless (($version eq 'mostrecent') || 
                   10576: 		    ($version==&getversion($uri))) {
1.440     www      10577:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   10578:  	    }
                   10579:  	}
                   10580:  	untie %bighash;
1.413     www      10581:     }
1.599     albertel 10582:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      10583: }
                   10584: 
                   10585: sub deversion {
                   10586:     my $url=shift;
                   10587:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   10588:     return $url;
1.210     www      10589: }
                   10590: 
1.31      www      10591: # ------------------------------------------------------ Return symb list entry
                   10592: 
                   10593: sub symbread {
1.249     www      10594:     my ($thisfn,$donotrecurse)=@_;
1.1172.2.13  raeburn  10595:     my $cache_str;
                   10596:     if ($thisfn ne '') {
                   10597:         $cache_str='request.symbread.cached.'.$thisfn;
                   10598:         if ($env{$cache_str} ne '') {
1.1172.2.8  raeburn  10599:             return $env{$cache_str};
                   10600:         }
1.1172.2.13  raeburn  10601:    } else {
1.242     www      10602: # no filename provided? try from environment
1.620     albertel 10603:         if ($env{'request.symb'}) {
1.1172.2.13  raeburn  10604:             return $env{$cache_str}=&symbclean($env{'request.symb'});
                   10605:         }
                   10606:         $thisfn=$env{'request.filename'};
1.44      www      10607:     }
1.569     albertel 10608:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      10609: # is that filename actually a symb? Verify, clean, and return
                   10610:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 10611: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 10612: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 10613: 	}
1.242     www      10614:     }
1.44      www      10615:     $thisfn=declutter($thisfn);
1.31      www      10616:     my %hash;
1.37      www      10617:     my %bighash;
                   10618:     my $syval='';
1.620     albertel 10619:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  10620:         my $targetfn = $thisfn;
1.609     banghart 10621:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  10622:             $targetfn = 'adm/wrapper/'.$thisfn;
                   10623:         }
1.687     albertel 10624: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   10625: 	    $targetfn=$1;
                   10626: 	}
1.620     albertel 10627:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10628:                       &GDBM_READER(),0640)) {
1.481     raeburn  10629: 	    $syval=$hash{$targetfn};
1.37      www      10630:             untie(%hash);
                   10631:         }
                   10632: # ---------------------------------------------------------- There was an entry
                   10633:         if ($syval) {
1.601     albertel 10634: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 10635: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  10636: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10637: 		    #return $env{$cache_str}='';
1.601     albertel 10638: 		#}    
                   10639: 		#$syval.=$1;
                   10640: 	    #}
1.37      www      10641:         } else {
                   10642: # ------------------------------------------------------- Was not in symb table
1.620     albertel 10643:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10644:                             &GDBM_READER(),0640)) {
1.37      www      10645: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      10646:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      10647:               unless ($ids) { 
                   10648:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      10649:               }
                   10650:               unless ($ids) {
                   10651: # alias?
                   10652: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      10653:               }
1.37      www      10654:               if ($ids) {
                   10655: # ------------------------------------------------------------------- Has ID(s)
                   10656:                  my @possibilities=split(/\,/,$ids);
1.39      www      10657:                  if ($#possibilities==0) {
                   10658: # ----------------------------------------------- There is only one possibility
1.37      www      10659: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 10660: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10661: 						    $resid,$thisfn);
1.249     www      10662:                  } elsif (!$donotrecurse) {
1.39      www      10663: # ------------------------------------------ There is more than one possibility
                   10664:                      my $realpossible=0;
1.800     albertel 10665:                      foreach my $id (@possibilities) {
                   10666: 			 my $file=$bighash{'src_'.$id};
1.39      www      10667:                          if (&allowed('bre',$file)) {
1.800     albertel 10668:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      10669:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   10670: 				$realpossible++;
1.626     albertel 10671:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10672: 						    $resid,$thisfn);
1.39      www      10673:                             }
                   10674: 			 }
1.191     harris41 10675:                      }
1.39      www      10676: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      10677:                  } else {
                   10678:                      $syval='';
1.37      www      10679:                  }
                   10680: 	      }
                   10681:               untie(%bighash)
1.481     raeburn  10682:            }
1.31      www      10683:         }
1.62      www      10684:         if ($syval) {
1.620     albertel 10685: 	    return $env{$cache_str}=$syval;
1.62      www      10686:         }
1.31      www      10687:     }
1.949     raeburn  10688:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10689:     return $env{$cache_str}='';
1.31      www      10690: }
                   10691: 
                   10692: # ---------------------------------------------------------- Return random seed
                   10693: 
1.32      www      10694: sub numval {
                   10695:     my $txt=shift;
                   10696:     $txt=~tr/A-J/0-9/;
                   10697:     $txt=~tr/a-j/0-9/;
                   10698:     $txt=~tr/K-T/0-9/;
                   10699:     $txt=~tr/k-t/0-9/;
                   10700:     $txt=~tr/U-Z/0-5/;
                   10701:     $txt=~tr/u-z/0-5/;
                   10702:     $txt=~s/\D//g;
1.564     albertel 10703:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      10704:     return int($txt);
1.368     albertel 10705: }
                   10706: 
1.484     albertel 10707: sub numval2 {
                   10708:     my $txt=shift;
                   10709:     $txt=~tr/A-J/0-9/;
                   10710:     $txt=~tr/a-j/0-9/;
                   10711:     $txt=~tr/K-T/0-9/;
                   10712:     $txt=~tr/k-t/0-9/;
                   10713:     $txt=~tr/U-Z/0-5/;
                   10714:     $txt=~tr/u-z/0-5/;
                   10715:     $txt=~s/\D//g;
                   10716:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10717:     my $total;
                   10718:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 10719:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 10720:     return int($total);
                   10721: }
                   10722: 
1.575     albertel 10723: sub numval3 {
                   10724:     use integer;
                   10725:     my $txt=shift;
                   10726:     $txt=~tr/A-J/0-9/;
                   10727:     $txt=~tr/a-j/0-9/;
                   10728:     $txt=~tr/K-T/0-9/;
                   10729:     $txt=~tr/k-t/0-9/;
                   10730:     $txt=~tr/U-Z/0-5/;
                   10731:     $txt=~tr/u-z/0-5/;
                   10732:     $txt=~s/\D//g;
                   10733:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10734:     my $total;
                   10735:     foreach my $val (@txts) { $total+=$val; }
                   10736:     if ($_64bit) { $total=(($total<<32)>>32); }
                   10737:     return $total;
                   10738: }
                   10739: 
1.675     albertel 10740: sub digest {
                   10741:     my ($data)=@_;
                   10742:     my $digest=&Digest::MD5::md5($data);
                   10743:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   10744:     my ($e,$f);
                   10745:     {
                   10746:         use integer;
                   10747:         $e=($a+$b);
                   10748:         $f=($c+$d);
                   10749:         if ($_64bit) {
                   10750:             $e=(($e<<32)>>32);
                   10751:             $f=(($f<<32)>>32);
                   10752:         }
                   10753:     }
                   10754:     if (wantarray) {
                   10755: 	return ($e,$f);
                   10756:     } else {
                   10757: 	my $g;
                   10758: 	{
                   10759: 	    use integer;
                   10760: 	    $g=($e+$f);
                   10761: 	    if ($_64bit) {
                   10762: 		$g=(($g<<32)>>32);
                   10763: 	    }
                   10764: 	}
                   10765: 	return $g;
                   10766:     }
                   10767: }
                   10768: 
1.368     albertel 10769: sub latest_rnd_algorithm_id {
1.675     albertel 10770:     return '64bit5';
1.366     albertel 10771: }
1.32      www      10772: 
1.503     albertel 10773: sub get_rand_alg {
                   10774:     my ($courseid)=@_;
1.790     albertel 10775:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 10776:     if ($courseid) {
1.620     albertel 10777: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 10778:     }
                   10779:     return &latest_rnd_algorithm_id();
                   10780: }
                   10781: 
1.562     albertel 10782: sub validCODE {
                   10783:     my ($CODE)=@_;
                   10784:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   10785:     return 0;
                   10786: }
                   10787: 
1.491     albertel 10788: sub getCODE {
1.620     albertel 10789:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 10790:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   10791: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   10792: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 10793: 	return $Apache::lonhomework::history{'resource.CODE'};
                   10794:     }
                   10795:     return undef;
                   10796: }
1.1133    foxr     10797: #
                   10798: #  Determines the random seed for a specific context:
                   10799: #
                   10800: # parameters:
                   10801: #   symb      - in course context the symb for the seed.
                   10802: #   course_id - The course id of the form domain_coursenum.
                   10803: #   domain    - Domain for the user.
                   10804: #   course    - Course for the user.
                   10805: #   cenv      - environment of the course.
                   10806: #
                   10807: # NOTE:
                   10808: #   All parameters are picked out of the environment if missing
                   10809: #   or not defined.
                   10810: #   If a symb cannot be determined the current time is used instead.
                   10811: #
                   10812: #  For a given well defined symb, courside, domain, username,
                   10813: #  and course environment, the seed is reproducible.
                   10814: #
1.31      www      10815: sub rndseed {
1.1133    foxr     10816:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 10817:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 10818:     if (!defined($symb)) {
1.366     albertel 10819: 	unless ($symb=$wsymb) { return time; }
                   10820:     }
1.1146    foxr     10821:     if (!defined $courseid) { 
                   10822: 	$courseid=$wcourseid; 
                   10823:     }
                   10824:     if (!defined $domain) { $domain=$wdomain; }
                   10825:     if (!defined $username) { $username=$wusername }
1.1133    foxr     10826: 
                   10827:     my $which;
                   10828:     if (defined($cenv->{'rndseed'})) {
                   10829: 	$which = $cenv->{'rndseed'};
                   10830:     } else {
                   10831: 	$which =&get_rand_alg($courseid);
                   10832:     }
1.491     albertel 10833:     if (defined(&getCODE())) {
1.675     albertel 10834: 	if ($which eq '64bit5') {
                   10835: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   10836: 	} elsif ($which eq '64bit4') {
1.575     albertel 10837: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   10838: 	} else {
                   10839: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   10840: 	}
1.675     albertel 10841:     } elsif ($which eq '64bit5') {
                   10842: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 10843:     } elsif ($which eq '64bit4') {
                   10844: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 10845:     } elsif ($which eq '64bit3') {
                   10846: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 10847:     } elsif ($which eq '64bit2') {
                   10848: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 10849:     } elsif ($which eq '64bit') {
                   10850: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   10851:     }
                   10852:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   10853: }
                   10854: 
                   10855: sub rndseed_32bit {
                   10856:     my ($symb,$courseid,$domain,$username)=@_;
                   10857:     {
                   10858: 	use integer;
                   10859: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   10860: 	my $symbseed=numval($symb) << 22;
                   10861: 	my $namechck=unpack("%32C*",$username) << 17;
                   10862: 	my $nameseed=numval($username) << 12;
                   10863: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   10864: 	my $courseseed=unpack("%32C*",$courseid);
                   10865: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 10866: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10867: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 10868: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 10869: 	return $num;
                   10870:     }
                   10871: }
                   10872: 
                   10873: sub rndseed_64bit {
                   10874:     my ($symb,$courseid,$domain,$username)=@_;
                   10875:     {
                   10876: 	use integer;
                   10877: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   10878: 	my $symbseed=numval($symb) << 10;
                   10879: 	my $namechck=unpack("%32S*",$username);
                   10880: 	
                   10881: 	my $nameseed=numval($username) << 21;
                   10882: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   10883: 	my $courseseed=unpack("%32S*",$courseid);
                   10884: 	
                   10885: 	my $num1=$symbchck+$symbseed+$namechck;
                   10886: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10887: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10888: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 10889: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 10890: 	return "$num1,$num2";
1.155     albertel 10891:     }
1.366     albertel 10892: }
                   10893: 
1.443     albertel 10894: sub rndseed_64bit2 {
                   10895:     my ($symb,$courseid,$domain,$username)=@_;
                   10896:     {
                   10897: 	use integer;
                   10898: 	# strings need to be an even # of cahracters long, it it is odd the
                   10899:         # last characters gets thrown away
                   10900: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10901: 	my $symbseed=numval($symb) << 10;
                   10902: 	my $namechck=unpack("%32S*",$username.' ');
                   10903: 	
                   10904: 	my $nameseed=numval($username) << 21;
1.501     albertel 10905: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10906: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10907: 	
                   10908: 	my $num1=$symbchck+$symbseed+$namechck;
                   10909: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10910: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10911: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 10912: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 10913: 	return "$num1,$num2";
                   10914:     }
                   10915: }
                   10916: 
                   10917: sub rndseed_64bit3 {
                   10918:     my ($symb,$courseid,$domain,$username)=@_;
                   10919:     {
                   10920: 	use integer;
                   10921: 	# strings need to be an even # of cahracters long, it it is odd the
                   10922:         # last characters gets thrown away
                   10923: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10924: 	my $symbseed=numval2($symb) << 10;
                   10925: 	my $namechck=unpack("%32S*",$username.' ');
                   10926: 	
                   10927: 	my $nameseed=numval2($username) << 21;
1.443     albertel 10928: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10929: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10930: 	
                   10931: 	my $num1=$symbchck+$symbseed+$namechck;
                   10932: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10933: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10934: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 10935: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      10936: 	
1.503     albertel 10937: 	return "$num1:$num2";
1.443     albertel 10938:     }
                   10939: }
                   10940: 
1.575     albertel 10941: sub rndseed_64bit4 {
                   10942:     my ($symb,$courseid,$domain,$username)=@_;
                   10943:     {
                   10944: 	use integer;
                   10945: 	# strings need to be an even # of cahracters long, it it is odd the
                   10946:         # last characters gets thrown away
                   10947: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10948: 	my $symbseed=numval3($symb) << 10;
                   10949: 	my $namechck=unpack("%32S*",$username.' ');
                   10950: 	
                   10951: 	my $nameseed=numval3($username) << 21;
                   10952: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10953: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10954: 	
                   10955: 	my $num1=$symbchck+$symbseed+$namechck;
                   10956: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10957: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10958: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 10959: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      10960: 	
1.575     albertel 10961: 	return "$num1:$num2";
                   10962:     }
                   10963: }
                   10964: 
1.675     albertel 10965: sub rndseed_64bit5 {
                   10966:     my ($symb,$courseid,$domain,$username)=@_;
                   10967:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   10968:     return "$num1:$num2";
                   10969: }
                   10970: 
1.366     albertel 10971: sub rndseed_CODE_64bit {
                   10972:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 10973:     {
1.366     albertel 10974: 	use integer;
1.443     albertel 10975: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 10976: 	my $symbseed=numval2($symb);
1.491     albertel 10977: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   10978: 	my $CODEseed=numval(&getCODE());
1.443     albertel 10979: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 10980: 	my $num1=$symbseed+$CODEchck;
                   10981: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 10982: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   10983: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 10984: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   10985: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 10986: 	return "$num1:$num2";
1.366     albertel 10987:     }
                   10988: }
                   10989: 
1.575     albertel 10990: sub rndseed_CODE_64bit4 {
                   10991:     my ($symb,$courseid,$domain,$username)=@_;
                   10992:     {
                   10993: 	use integer;
                   10994: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   10995: 	my $symbseed=numval3($symb);
                   10996: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   10997: 	my $CODEseed=numval3(&getCODE());
                   10998: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10999: 	my $num1=$symbseed+$CODEchck;
                   11000: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11001: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11002: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 11003: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11004: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   11005: 	return "$num1:$num2";
                   11006:     }
                   11007: }
                   11008: 
1.675     albertel 11009: sub rndseed_CODE_64bit5 {
                   11010:     my ($symb,$courseid,$domain,$username)=@_;
                   11011:     my $code = &getCODE();
                   11012:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   11013:     return "$num1:$num2";
                   11014: }
                   11015: 
1.366     albertel 11016: sub setup_random_from_rndseed {
                   11017:     my ($rndseed)=@_;
1.503     albertel 11018:     if ($rndseed =~/([,:])/) {
                   11019: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 11020: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   11021:     } else {
                   11022: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 11023:     }
1.36      albertel 11024: }
                   11025: 
1.474     albertel 11026: sub latest_receipt_algorithm_id {
1.835     albertel 11027:     return 'receipt3';
1.474     albertel 11028: }
                   11029: 
1.480     www      11030: sub recunique {
                   11031:     my $fucourseid=shift;
                   11032:     my $unique;
1.835     albertel 11033:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   11034: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11035: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      11036:     } else {
                   11037: 	$unique=$perlvar{'lonReceipt'};
                   11038:     }
                   11039:     return unpack("%32C*",$unique);
                   11040: }
                   11041: 
                   11042: sub recprefix {
                   11043:     my $fucourseid=shift;
                   11044:     my $prefix;
1.835     albertel 11045:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   11046: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11047: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      11048:     } else {
                   11049: 	$prefix=$perlvar{'lonHostID'};
                   11050:     }
                   11051:     return unpack("%32C*",$prefix);
                   11052: }
                   11053: 
1.76      www      11054: sub ireceipt {
1.474     albertel 11055:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 11056: 
                   11057:     my $return =&recprefix($fucourseid).'-';
                   11058: 
                   11059:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   11060: 	$env{'request.state'} eq 'construct') {
                   11061: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   11062: 	return $return;
                   11063:     }
                   11064: 
1.76      www      11065:     my $cuname=unpack("%32C*",$funame);
                   11066:     my $cudom=unpack("%32C*",$fudom);
                   11067:     my $cucourseid=unpack("%32C*",$fucourseid);
                   11068:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      11069:     my $cunique=&recunique($fucourseid);
1.474     albertel 11070:     my $cpart=unpack("%32S*",$part);
1.835     albertel 11071:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   11072: 
1.790     albertel 11073: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 11074: 			       
                   11075: 	$return.= ($cunique%$cuname+
                   11076: 		   $cunique%$cudom+
                   11077: 		   $cusymb%$cuname+
                   11078: 		   $cusymb%$cudom+
                   11079: 		   $cucourseid%$cuname+
                   11080: 		   $cucourseid%$cudom+
                   11081: 		   $cpart%$cuname+
                   11082: 		   $cpart%$cudom);
                   11083:     } else {
                   11084: 	$return.= ($cunique%$cuname+
                   11085: 		   $cunique%$cudom+
                   11086: 		   $cusymb%$cuname+
                   11087: 		   $cusymb%$cudom+
                   11088: 		   $cucourseid%$cuname+
                   11089: 		   $cucourseid%$cudom);
                   11090:     }
                   11091:     return $return;
1.76      www      11092: }
                   11093: 
                   11094: sub receipt {
1.474     albertel 11095:     my ($part)=@_;
1.790     albertel 11096:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 11097:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      11098: }
1.260     ng       11099: 
1.790     albertel 11100: sub whichuser {
                   11101:     my ($passedsymb)=@_;
                   11102:     my ($symb,$courseid,$domain,$name,$publicuser);
                   11103:     if (defined($env{'form.grade_symb'})) {
                   11104: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   11105: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   11106: 	if (!$allowed &&
                   11107: 	    exists($env{'request.course.sec'}) &&
                   11108: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   11109: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   11110: 			      '/'.$env{'request.course.sec'});
                   11111: 	}
                   11112: 	if ($allowed) {
                   11113: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   11114: 	    $courseid=$tmp_courseid;
                   11115: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   11116: 	    ($name)=&get_env_multiple('form.grade_username');
                   11117: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   11118: 	}
                   11119:     }
                   11120:     if (!$passedsymb) {
                   11121: 	$symb=&symbread();
                   11122:     } else {
                   11123: 	$symb=$passedsymb;
                   11124:     }
                   11125:     $courseid=$env{'request.course.id'};
                   11126:     $domain=$env{'user.domain'};
                   11127:     $name=$env{'user.name'};
                   11128:     if ($name eq 'public' && $domain eq 'public') {
                   11129: 	if (!defined($env{'form.username'})) {
                   11130: 	    $env{'form.username'}.=time.rand(10000000);
                   11131: 	}
                   11132: 	$name.=$env{'form.username'};
                   11133:     }
                   11134:     return ($symb,$courseid,$domain,$name,$publicuser);
                   11135: 
                   11136: }
                   11137: 
1.36      albertel 11138: # ------------------------------------------------------------ Serves up a file
1.472     albertel 11139: # returns either the contents of the file or 
                   11140: # -1 if the file doesn't exist
1.481     raeburn  11141: #
                   11142: # if the target is a file that was uploaded via DOCS, 
                   11143: # a check will be made to see if a current copy exists on the local server,
                   11144: # if it does this will be served, otherwise a copy will be retrieved from
                   11145: # the home server for the course and stored in /home/httpd/html/userfiles on
                   11146: # the local server.   
1.472     albertel 11147: 
1.36      albertel 11148: sub getfile {
1.538     albertel 11149:     my ($file) = @_;
1.609     banghart 11150:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 11151:     &repcopy($file);
                   11152:     return &readfile($file);
                   11153: }
                   11154: 
                   11155: sub repcopy_userfile {
                   11156:     my ($file)=@_;
1.1142    raeburn  11157:     my $londocroot = $perlvar{'lonDocRoot'};
                   11158:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  11159:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 11160:     my ($cdom,$cnum,$filename) = 
1.811     albertel 11161: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 11162:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   11163:     if (-e "$file") {
1.828     www      11164: # we already have a local copy, check it out
1.538     albertel 11165: 	my @fileinfo = stat($file);
1.828     www      11166: 	my $rtncode;
                   11167: 	my $info;
1.538     albertel 11168: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 11169: 	if ($lwpresp ne 'ok') {
1.828     www      11170: # there is no such file anymore, even though we had a local copy
1.482     albertel 11171: 	    if ($rtncode eq '404') {
1.538     albertel 11172: 		unlink($file);
1.482     albertel 11173: 	    }
                   11174: 	    return -1;
                   11175: 	}
                   11176: 	if ($info < $fileinfo[9]) {
1.828     www      11177: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  11178: 	    return 'ok';
1.828     www      11179: 	} else {
                   11180: # the file is outdated, get rid of it
                   11181: 	    unlink($file);
1.482     albertel 11182: 	}
1.828     www      11183:     }
                   11184: # one way or the other, at this point, we don't have the file
                   11185: # construct the correct path for the file
                   11186:     my @parts = ($cdom,$cnum); 
                   11187:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   11188: 	push @parts, split(/\//,$1);
                   11189:     }
                   11190:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   11191:     foreach my $part (@parts) {
                   11192: 	$path .= '/'.$part;
                   11193: 	if (!-e $path) {
                   11194: 	    mkdir($path,0770);
1.482     albertel 11195: 	}
                   11196:     }
1.828     www      11197: # now the path exists for sure
                   11198: # get a user agent
                   11199:     my $ua=new LWP::UserAgent;
                   11200:     my $transferfile=$file.'.in.transfer';
                   11201: # FIXME: this should flock
                   11202:     if (-e $transferfile) { return 'ok'; }
                   11203:     my $request;
                   11204:     $uri=~s/^\///;
1.980     raeburn  11205:     my $homeserver = &homeserver($cnum,$cdom);
                   11206:     my $protocol = $protocol{$homeserver};
                   11207:     $protocol = 'http' if ($protocol ne 'https');
                   11208:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      11209:     my $response=$ua->request($request,$transferfile);
                   11210: # did it work?
                   11211:     if ($response->is_error()) {
                   11212: 	unlink($transferfile);
                   11213: 	&logthis("Userfile repcopy failed for $uri");
                   11214: 	return -1;
                   11215:     }
                   11216: # worked, rename the transfer file
                   11217:     rename($transferfile,$file);
1.607     raeburn  11218:     return 'ok';
1.481     raeburn  11219: }
                   11220: 
1.517     albertel 11221: sub tokenwrapper {
                   11222:     my $uri=shift;
1.980     raeburn  11223:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 11224:     $uri=~s|^/||;
1.620     albertel 11225:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 11226:     my $token=$1;
1.552     albertel 11227:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   11228:     if ($udom && $uname && $file) {
                   11229: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  11230:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  11231:         my $homeserver = &homeserver($uname,$udom);
                   11232:         my $protocol = $protocol{$homeserver};
                   11233:         $protocol = 'http' if ($protocol ne 'https');
                   11234:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 11235:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   11236:                                '&tokenissued='.$perlvar{'lonHostID'};
                   11237:     } else {
                   11238:         return '/adm/notfound.html';
                   11239:     }
                   11240: }
                   11241: 
1.828     www      11242: # call with reqtype HEAD: get last modification time
                   11243: # call with reqtype GET: get the file contents
                   11244: # Do not call this with reqtype GET for large files! It loads everything into memory
                   11245: #
1.481     raeburn  11246: sub getuploaded {
                   11247:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   11248:     $uri=~s/^\///;
1.980     raeburn  11249:     my $homeserver = &homeserver($cnum,$cdom);
                   11250:     my $protocol = $protocol{$homeserver};
                   11251:     $protocol = 'http' if ($protocol ne 'https');
                   11252:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  11253:     my $ua=new LWP::UserAgent;
                   11254:     my $request=new HTTP::Request($reqtype,$uri);
                   11255:     my $response=$ua->request($request);
                   11256:     $$rtncode = $response->code;
1.482     albertel 11257:     if (! $response->is_success()) {
                   11258: 	return 'failed';
                   11259:     }      
                   11260:     if ($reqtype eq 'HEAD') {
1.486     www      11261: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 11262:     } elsif ($reqtype eq 'GET') {
                   11263: 	$$info = $response->content;
1.472     albertel 11264:     }
1.482     albertel 11265:     return 'ok';
1.36      albertel 11266: }
                   11267: 
1.481     raeburn  11268: sub readfile {
                   11269:     my $file = shift;
                   11270:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   11271:     my $fh;
                   11272:     open($fh,"<$file");
                   11273:     my $a='';
1.800     albertel 11274:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  11275:     return $a;
                   11276: }
                   11277: 
1.36      albertel 11278: sub filelocation {
1.590     banghart 11279:     my ($dir,$file) = @_;
                   11280:     my $location;
                   11281:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 11282: 
                   11283:     if ($file =~ m-^/adm/-) {
                   11284: 	$file=~s-^/adm/wrapper/-/-;
                   11285: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   11286:     }
1.882     albertel 11287: 
1.1139    www      11288:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  11289:         $location = $file;
1.609     banghart 11290:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 11291:         my ($udom,$uname,$filename)=
1.811     albertel 11292:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 11293:         my $home=&homeserver($uname,$udom);
                   11294:         my $is_me=0;
                   11295:         my @ids=&current_machine_ids();
                   11296:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   11297:         if ($is_me) {
1.1117    foxr     11298:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 11299:         } else {
                   11300:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   11301:   	      $udom.'/'.$uname.'/'.$filename;
                   11302:         }
1.882     albertel 11303:     } elsif ($file =~ m-^/adm/-) {
                   11304: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 11305:     } else {
                   11306:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      11307:         $file=~s:^/(res|priv)/:/:;
                   11308:         my $space=$1;
1.590     banghart 11309:         if ( !( $file =~ m:^/:) ) {
                   11310:             $location = $dir. '/'.$file;
                   11311:         } else {
1.1142    raeburn  11312:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 11313:         }
1.59      albertel 11314:     }
1.590     banghart 11315:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 11316:     while ($location=~m{/\.\./}) {
                   11317: 	if ($location =~ m{/[^/]+/\.\./}) {
                   11318: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   11319: 	} else {
                   11320: 	    $location=~ s{/\.\./}{/}g;
                   11321: 	}
                   11322:     } #remove dir/..
1.590     banghart 11323:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   11324:     return $location;
1.46      www      11325: }
1.36      albertel 11326: 
1.46      www      11327: sub hreflocation {
                   11328:     my ($dir,$file)=@_;
1.980     raeburn  11329:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 11330: 	$file=filelocation($dir,$file);
1.700     albertel 11331:     } elsif ($file=~m-^/adm/-) {
                   11332: 	$file=~s-^/adm/wrapper/-/-;
                   11333: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 11334:     }
                   11335:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   11336: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   11337:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  11338: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   11339: 	        {/uploaded/$1/$2/}x;
1.46      www      11340:     }
1.913     albertel 11341:     if ($file=~ m{^/userfiles/}) {
                   11342: 	$file =~ s{^/userfiles/}{/uploaded/};
                   11343:     }
1.462     albertel 11344:     return $file;
1.465     albertel 11345: }
                   11346: 
1.1139    www      11347: 
                   11348: 
                   11349: 
                   11350: 
1.465     albertel 11351: sub current_machine_domains {
1.853     albertel 11352:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   11353: }
                   11354: 
                   11355: sub machine_domains {
                   11356:     my ($hostname) = @_;
1.465     albertel 11357:     my @domains;
1.838     albertel 11358:     my %hostname = &all_hostnames();
1.465     albertel 11359:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  11360: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 11361: 	if ($hostname eq $name) {
1.844     albertel 11362: 	    push(@domains,&host_domain($id));
1.465     albertel 11363: 	}
                   11364:     }
                   11365:     return @domains;
                   11366: }
                   11367: 
                   11368: sub current_machine_ids {
1.853     albertel 11369:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   11370: }
                   11371: 
                   11372: sub machine_ids {
                   11373:     my ($hostname) = @_;
                   11374:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 11375:     my @ids;
1.888     albertel 11376:     my %name_to_host = &all_names();
1.889     albertel 11377:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   11378: 	return @{ $name_to_host{$hostname} };
                   11379:     }
                   11380:     return;
1.31      www      11381: }
                   11382: 
1.824     raeburn  11383: sub additional_machine_domains {
                   11384:     my @domains;
                   11385:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   11386:     while( my $line = <$fh>) {
                   11387:         $line =~ s/\s//g;
                   11388:         push(@domains,$line);
                   11389:     }
                   11390:     return @domains;
                   11391: }
                   11392: 
                   11393: sub default_login_domain {
                   11394:     my $domain = $perlvar{'lonDefDomain'};
                   11395:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   11396:     foreach my $posdom (&current_machine_domains(),
                   11397:                         &additional_machine_domains()) {
                   11398:         if (lc($posdom) eq lc($testdomain)) {
                   11399:             $domain=$posdom;
                   11400:             last;
                   11401:         }
                   11402:     }
                   11403:     return $domain;
                   11404: }
                   11405: 
1.31      www      11406: # ------------------------------------------------------------- Declutters URLs
                   11407: 
                   11408: sub declutter {
                   11409:     my $thisfn=shift;
1.569     albertel 11410:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 11411:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      11412:     $thisfn=~s/^\///;
1.697     albertel 11413:     $thisfn=~s|^adm/wrapper/||;
                   11414:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      11415:     $thisfn=~s/^res\///;
1.1172    bisitz   11416:     $thisfn=~s/^priv\///;
1.1032    raeburn  11417:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   11418:         $thisfn=~s/\?.+$//;
                   11419:     }
1.268     www      11420:     return $thisfn;
                   11421: }
                   11422: 
                   11423: # ------------------------------------------------------------- Clutter up URLs
                   11424: 
                   11425: sub clutter {
                   11426:     my $thisfn='/'.&declutter(shift);
1.887     albertel 11427:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 11428: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      11429:        $thisfn='/res'.$thisfn; 
                   11430:     }
1.1031    raeburn  11431:     if ($thisfn !~m|^/adm|) {
                   11432: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 11433: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 11434: 	} else {
                   11435: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   11436: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 11437: 	    if ($embstyle eq 'ssi'
                   11438: 		|| ($embstyle eq 'hdn')
                   11439: 		|| ($embstyle eq 'rat')
                   11440: 		|| ($embstyle eq 'prv')
                   11441: 		|| ($embstyle eq 'ign')) {
                   11442: 		#do nothing with these
                   11443: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 11444: 		|| ($embstyle eq 'emb')
                   11445: 		|| ($embstyle eq 'wrp')) {
                   11446: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 11447: 	    } elsif ($embstyle eq 'unk'
                   11448: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 11449: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 11450: 	    } else {
1.718     www      11451: #		&logthis("Got a blank emb style");
1.695     albertel 11452: 	    }
1.694     albertel 11453: 	}
                   11454:     }
1.31      www      11455:     return $thisfn;
1.12      www      11456: }
                   11457: 
1.787     albertel 11458: sub clutter_with_no_wrapper {
                   11459:     my $uri = &clutter(shift);
                   11460:     if ($uri =~ m-^/adm/-) {
                   11461: 	$uri =~ s-^/adm/wrapper/-/-;
                   11462: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   11463:     }
                   11464:     return $uri;
                   11465: }
                   11466: 
1.557     albertel 11467: sub freeze_escape {
                   11468:     my ($value)=@_;
                   11469:     if (ref($value)) {
                   11470: 	$value=&nfreeze($value);
                   11471: 	return '__FROZEN__'.&escape($value);
                   11472:     }
                   11473:     return &escape($value);
                   11474: }
                   11475: 
1.11      www      11476: 
1.557     albertel 11477: sub thaw_unescape {
                   11478:     my ($value)=@_;
                   11479:     if ($value =~ /^__FROZEN__/) {
                   11480: 	substr($value,0,10,undef);
                   11481: 	$value=&unescape($value);
                   11482: 	return &thaw($value);
                   11483:     }
                   11484:     return &unescape($value);
                   11485: }
                   11486: 
1.436     albertel 11487: sub correct_line_ends {
                   11488:     my ($result)=@_;
                   11489:     $$result =~s/\r\n/\n/mg;
                   11490:     $$result =~s/\r/\n/mg;
1.415     albertel 11491: }
1.1       albertel 11492: # ================================================================ Main Program
                   11493: 
1.184     www      11494: sub goodbye {
1.204     albertel 11495:    &logthis("Starting Shut down");
1.443     albertel 11496: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 11497:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 11498: #converted
1.599     albertel 11499: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 11500:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   11501: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   11502: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 11503: #1.1 only
1.870     albertel 11504: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   11505: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   11506: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   11507: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   11508:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 11509:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   11510:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      11511:    &flushcourselogs();
                   11512:    &logthis("Shutting down");
                   11513: }
                   11514: 
1.852     albertel 11515: sub get_dns {
1.869     albertel 11516:     my ($url,$func,$ignore_cache) = @_;
                   11517:     if (!$ignore_cache) {
                   11518: 	my ($content,$cached)=
                   11519: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   11520: 	if ($cached) {
                   11521: 	    &$func($content);
                   11522: 	    return;
                   11523: 	}
                   11524:     }
                   11525: 
                   11526:     my %alldns;
1.852     albertel 11527:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11528:     foreach my $dns (<$config>) {
                   11529: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  11530:         my $line = $1;
                   11531:         my ($host,$protocol) = split(/:/,$line);
                   11532:         if ($protocol ne 'https') {
                   11533:             $protocol = 'http';
                   11534:         }
                   11535: 	$alldns{$host} = $protocol;
1.869     albertel 11536:     }
                   11537:     while (%alldns) {
                   11538: 	my ($dns) = keys(%alldns);
1.852     albertel 11539: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  11540:         $ua->timeout(30);
1.979     raeburn  11541: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 11542: 	my $response=$ua->request($request);
1.979     raeburn  11543:         delete($alldns{$dns});
1.852     albertel 11544: 	next if ($response->is_error());
                   11545: 	my @content = split("\n",$response->content);
1.869     albertel 11546: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 11547: 	&$func(\@content);
1.869     albertel 11548: 	return;
1.852     albertel 11549:     }
                   11550:     close($config);
1.871     albertel 11551:     my $which = (split('/',$url))[3];
                   11552:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   11553:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 11554:     my @content = <$config>;
                   11555:     &$func(\@content);
                   11556:     return;
1.852     albertel 11557: }
1.327     albertel 11558: # ------------------------------------------------------------ Read domain file
                   11559: {
1.852     albertel 11560:     my $loaded;
1.846     albertel 11561:     my %domain;
                   11562: 
1.852     albertel 11563:     sub parse_domain_tab {
                   11564: 	my ($lines) = @_;
                   11565: 	foreach my $line (@$lines) {
                   11566: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      11567: 
1.846     albertel 11568: 	    chomp($line);
1.852     albertel 11569: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 11570: 	    my %this_domain;
                   11571: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   11572: 			       'lang_def', 'city', 'longi', 'lati',
                   11573: 			       'primary') {
                   11574: 		$this_domain{$field} = shift(@elements);
                   11575: 	    }
                   11576: 	    $domain{$name} = \%this_domain;
1.852     albertel 11577: 	}
                   11578:     }
1.864     albertel 11579: 
                   11580:     sub reset_domain_info {
                   11581: 	undef($loaded);
                   11582: 	undef(%domain);
                   11583:     }
                   11584: 
1.852     albertel 11585:     sub load_domain_tab {
1.869     albertel 11586: 	my ($ignore_cache) = @_;
                   11587: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 11588: 	my $fh;
                   11589: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   11590: 	    my @lines = <$fh>;
                   11591: 	    &parse_domain_tab(\@lines);
1.448     albertel 11592: 	}
1.852     albertel 11593: 	close($fh);
                   11594: 	$loaded = 1;
1.327     albertel 11595:     }
1.846     albertel 11596: 
                   11597:     sub domain {
1.852     albertel 11598: 	&load_domain_tab() if (!$loaded);
                   11599: 
1.846     albertel 11600: 	my ($name,$what) = @_;
                   11601: 	return if ( !exists($domain{$name}) );
                   11602: 
                   11603: 	if (!$what) {
                   11604: 	    return $domain{$name}{'description'};
                   11605: 	}
                   11606: 	return $domain{$name}{$what};
                   11607:     }
1.974     raeburn  11608: 
                   11609:     sub domain_info {
                   11610:         &load_domain_tab() if (!$loaded);
                   11611:         return %domain;
                   11612:     }
                   11613: 
1.327     albertel 11614: }
                   11615: 
                   11616: 
1.1       albertel 11617: # ------------------------------------------------------------- Read hosts file
                   11618: {
1.838     albertel 11619:     my %hostname;
1.844     albertel 11620:     my %hostdom;
1.845     albertel 11621:     my %libserv;
1.852     albertel 11622:     my $loaded;
1.888     albertel 11623:     my %name_to_host;
1.1074    raeburn  11624:     my %internetdom;
1.1107    raeburn  11625:     my %LC_dns_serv;
1.852     albertel 11626: 
                   11627:     sub parse_hosts_tab {
                   11628: 	my ($file) = @_;
                   11629: 	foreach my $configline (@$file) {
                   11630: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  11631:             chomp($configline);
                   11632: 	    if ($configline =~ /^\^/) {
                   11633:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   11634:                     $LC_dns_serv{$1} = 1;
                   11635:                 }
                   11636:                 next;
                   11637:             }
1.1074    raeburn  11638: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 11639: 	    $name=~s/\s//g;
                   11640: 	    if ($id && $domain && $role && $name) {
                   11641: 		$hostname{$id}=$name;
1.888     albertel 11642: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 11643: 		$hostdom{$id}=$domain;
                   11644: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  11645:                 if (defined($protocol)) {
                   11646:                     if ($protocol eq 'https') {
                   11647:                         $protocol{$id} = $protocol;
                   11648:                     } else {
                   11649:                         $protocol{$id} = 'http'; 
                   11650:                     }
1.968     raeburn  11651:                 } else {
1.969     raeburn  11652:                     $protocol{$id} = 'http';
1.968     raeburn  11653:                 }
1.1074    raeburn  11654:                 if (defined($intdom)) {
                   11655:                     $internetdom{$id} = $intdom;
                   11656:                 }
1.852     albertel 11657: 	    }
                   11658: 	}
                   11659:     }
1.864     albertel 11660:     
                   11661:     sub reset_hosts_info {
1.897     albertel 11662: 	&purge_remembered();
1.864     albertel 11663: 	&reset_domain_info();
                   11664: 	&reset_hosts_ip_info();
1.892     albertel 11665: 	undef(%name_to_host);
1.864     albertel 11666: 	undef(%hostname);
                   11667: 	undef(%hostdom);
                   11668: 	undef(%libserv);
                   11669: 	undef($loaded);
                   11670:     }
1.1       albertel 11671: 
1.852     albertel 11672:     sub load_hosts_tab {
1.869     albertel 11673: 	my ($ignore_cache) = @_;
                   11674: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 11675: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11676: 	my @config = <$config>;
                   11677: 	&parse_hosts_tab(\@config);
                   11678: 	close($config);
                   11679: 	$loaded=1;
1.1       albertel 11680:     }
1.852     albertel 11681: 
1.838     albertel 11682:     sub hostname {
1.852     albertel 11683: 	&load_hosts_tab() if (!$loaded);
                   11684: 
1.838     albertel 11685: 	my ($lonid) = @_;
                   11686: 	return $hostname{$lonid};
                   11687:     }
1.845     albertel 11688: 
1.838     albertel 11689:     sub all_hostnames {
1.852     albertel 11690: 	&load_hosts_tab() if (!$loaded);
                   11691: 
1.838     albertel 11692: 	return %hostname;
                   11693:     }
1.845     albertel 11694: 
1.888     albertel 11695:     sub all_names {
                   11696: 	&load_hosts_tab() if (!$loaded);
                   11697: 
                   11698: 	return %name_to_host;
                   11699:     }
                   11700: 
1.974     raeburn  11701:     sub all_host_domain {
                   11702:         &load_hosts_tab() if (!$loaded);
                   11703:         return %hostdom;
                   11704:     }
                   11705: 
1.845     albertel 11706:     sub is_library {
1.852     albertel 11707: 	&load_hosts_tab() if (!$loaded);
                   11708: 
1.845     albertel 11709: 	return exists($libserv{$_[0]});
                   11710:     }
                   11711: 
                   11712:     sub all_library {
1.852     albertel 11713: 	&load_hosts_tab() if (!$loaded);
                   11714: 
1.845     albertel 11715: 	return %libserv;
                   11716:     }
                   11717: 
1.1062    droeschl 11718:     sub unique_library {
                   11719: 	#2x reverse removes all hostnames that appear more than once
                   11720:         my %unique = reverse &all_library();
                   11721:         return reverse %unique;
                   11722:     }
                   11723: 
1.841     albertel 11724:     sub get_servers {
1.852     albertel 11725: 	&load_hosts_tab() if (!$loaded);
                   11726: 
1.841     albertel 11727: 	my ($domain,$type) = @_;
                   11728: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   11729: 	                                          : %hostname;
                   11730: 	my %result;
1.842     albertel 11731: 	if (ref($domain) eq 'ARRAY') {
                   11732: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 11733: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 11734: 		    $result{$host} = $hostname;
                   11735: 		}
                   11736: 	    }
                   11737: 	} else {
                   11738: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   11739: 		if ($hostdom{$host} eq $domain) {
                   11740: 		    $result{$host} = $hostname;
                   11741: 		}
1.841     albertel 11742: 	    }
                   11743: 	}
                   11744: 	return %result;
                   11745:     }
1.845     albertel 11746: 
1.1062    droeschl 11747:     sub get_unique_servers {
                   11748:         my %unique = reverse &get_servers(@_);
                   11749: 	return reverse %unique;
                   11750:     }
                   11751: 
1.844     albertel 11752:     sub host_domain {
1.852     albertel 11753: 	&load_hosts_tab() if (!$loaded);
                   11754: 
1.844     albertel 11755: 	my ($lonid) = @_;
                   11756: 	return $hostdom{$lonid};
                   11757:     }
                   11758: 
1.841     albertel 11759:     sub all_domains {
1.852     albertel 11760: 	&load_hosts_tab() if (!$loaded);
                   11761: 
1.841     albertel 11762: 	my %seen;
                   11763: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   11764: 	return @uniq;
                   11765:     }
1.1074    raeburn  11766: 
                   11767:     sub internet_dom {
                   11768:         &load_hosts_tab() if (!$loaded);
                   11769: 
                   11770:         my ($lonid) = @_;
                   11771:         return $internetdom{$lonid};
                   11772:     }
1.1107    raeburn  11773: 
                   11774:     sub is_LC_dns {
                   11775:         &load_hosts_tab() if (!$loaded);
                   11776: 
                   11777:         my ($hostname) = @_;
                   11778:         return exists($LC_dns_serv{$hostname});
                   11779:     }
                   11780: 
1.1       albertel 11781: }
                   11782: 
1.847     albertel 11783: { 
                   11784:     my %iphost;
1.856     albertel 11785:     my %name_to_ip;
                   11786:     my %lonid_to_ip;
1.869     albertel 11787: 
1.847     albertel 11788:     sub get_hosts_from_ip {
                   11789: 	my ($ip) = @_;
                   11790: 	my %iphosts = &get_iphost();
                   11791: 	if (ref($iphosts{$ip})) {
                   11792: 	    return @{$iphosts{$ip}};
                   11793: 	}
                   11794: 	return;
1.839     albertel 11795:     }
1.864     albertel 11796:     
                   11797:     sub reset_hosts_ip_info {
                   11798: 	undef(%iphost);
                   11799: 	undef(%name_to_ip);
                   11800: 	undef(%lonid_to_ip);
                   11801:     }
1.856     albertel 11802: 
                   11803:     sub get_host_ip {
                   11804: 	my ($lonid) = @_;
                   11805: 	if (exists($lonid_to_ip{$lonid})) {
                   11806: 	    return $lonid_to_ip{$lonid};
                   11807: 	}
                   11808: 	my $name=&hostname($lonid);
                   11809:    	my $ip = gethostbyname($name);
                   11810: 	return if (!$ip || length($ip) ne 4);
                   11811: 	$ip=inet_ntoa($ip);
                   11812: 	$name_to_ip{$name}   = $ip;
                   11813: 	$lonid_to_ip{$lonid} = $ip;
                   11814: 	return $ip;
                   11815:     }
1.847     albertel 11816:     
                   11817:     sub get_iphost {
1.869     albertel 11818: 	my ($ignore_cache) = @_;
1.894     albertel 11819: 
1.869     albertel 11820: 	if (!$ignore_cache) {
                   11821: 	    if (%iphost) {
                   11822: 		return %iphost;
                   11823: 	    }
                   11824: 	    my ($ip_info,$cached)=
                   11825: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   11826: 	    if ($cached) {
                   11827: 		%iphost      = %{$ip_info->[0]};
                   11828: 		%name_to_ip  = %{$ip_info->[1]};
                   11829: 		%lonid_to_ip = %{$ip_info->[2]};
                   11830: 		return %iphost;
                   11831: 	    }
                   11832: 	}
1.894     albertel 11833: 
                   11834: 	# get yesterday's info for fallback
                   11835: 	my %old_name_to_ip;
                   11836: 	my ($ip_info,$cached)=
                   11837: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   11838: 	if ($cached) {
                   11839: 	    %old_name_to_ip = %{$ip_info->[1]};
                   11840: 	}
                   11841: 
1.888     albertel 11842: 	my %name_to_host = &all_names();
                   11843: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 11844: 	    my $ip;
                   11845: 	    if (!exists($name_to_ip{$name})) {
                   11846: 		$ip = gethostbyname($name);
                   11847: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 11848: 		    if (defined($old_name_to_ip{$name})) {
                   11849: 			$ip = $old_name_to_ip{$name};
                   11850: 			&logthis("Can't find $name defaulting to old $ip");
                   11851: 		    } else {
                   11852: 			&logthis("Name $name no IP found");
                   11853: 			next;
                   11854: 		    }
                   11855: 		} else {
                   11856: 		    $ip=inet_ntoa($ip);
1.847     albertel 11857: 		}
                   11858: 		$name_to_ip{$name} = $ip;
                   11859: 	    } else {
                   11860: 		$ip = $name_to_ip{$name};
1.653     albertel 11861: 	    }
1.888     albertel 11862: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   11863: 		$lonid_to_ip{$id} = $ip;
                   11864: 	    }
                   11865: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 11866: 	}
1.869     albertel 11867: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   11868: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 11869: 				      48*60*60);
1.869     albertel 11870: 
1.847     albertel 11871: 	return %iphost;
1.598     albertel 11872:     }
                   11873: 
1.992     raeburn  11874:     #
                   11875:     #  Given a DNS returns the loncapa host name for that DNS 
                   11876:     # 
                   11877:     sub host_from_dns {
                   11878:         my ($dns) = @_;
                   11879:         my @hosts;
                   11880:         my $ip;
                   11881: 
1.993     raeburn  11882:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  11883:             $ip = $name_to_ip{$dns};
                   11884:         }
                   11885:         if (!$ip) {
                   11886:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   11887:             if (length($ip) == 4) { 
                   11888: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   11889:             }
                   11890:         }
                   11891:         if ($ip) {
                   11892: 	    @hosts = get_hosts_from_ip($ip);
                   11893: 	    return $hosts[0];
                   11894:         }
                   11895:         return undef;
1.986     foxr     11896:     }
1.992     raeburn  11897: 
1.1074    raeburn  11898:     sub get_internet_names {
                   11899:         my ($lonid) = @_;
                   11900:         return if ($lonid eq '');
                   11901:         my ($idnref,$cached)=
                   11902:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   11903:         if ($cached) {
                   11904:             return $idnref;
                   11905:         }
                   11906:         my $ip = &get_host_ip($lonid);
                   11907:         my @hosts = &get_hosts_from_ip($ip);
                   11908:         my %iphost = &get_iphost();
                   11909:         my (@idns,%seen);
                   11910:         foreach my $id (@hosts) {
                   11911:             my $dom = &host_domain($id);
                   11912:             my $prim_id = &domain($dom,'primary');
                   11913:             my $prim_ip = &get_host_ip($prim_id);
                   11914:             next if ($seen{$prim_ip});
                   11915:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   11916:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   11917:                     my $intdom = &internet_dom($id);
                   11918:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   11919:                         push(@idns,$intdom);
                   11920:                     }
                   11921:                 }
                   11922:             }
                   11923:             $seen{$prim_ip} = 1;
                   11924:         }
                   11925:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
                   11926:     }
                   11927: 
1.986     foxr     11928: }
                   11929: 
1.1079    raeburn  11930: sub all_loncaparevs {
                   11931:     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);
                   11932: }
                   11933: 
1.862     albertel 11934: BEGIN {
                   11935: 
                   11936: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   11937:     unless ($readit) {
                   11938: {
                   11939:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   11940:     %perlvar = (%perlvar,%{$configvars});
                   11941: }
                   11942: 
                   11943: 
1.1       albertel 11944: # ------------------------------------------------------ Read spare server file
                   11945: {
1.448     albertel 11946:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 11947: 
                   11948:     while (my $configline=<$config>) {
                   11949:        chomp($configline);
1.284     matthew  11950:        if ($configline) {
1.784     albertel 11951: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 11952: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 11953: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 11954:        }
                   11955:     }
1.448     albertel 11956:     close($config);
1.1       albertel 11957: }
1.11      www      11958: # ------------------------------------------------------------ Read permissions
                   11959: {
1.448     albertel 11960:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      11961: 
                   11962:     while (my $configline=<$config>) {
1.448     albertel 11963: 	chomp($configline);
                   11964: 	if ($configline) {
                   11965: 	    my ($role,$perm)=split(/ /,$configline);
                   11966: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   11967: 	}
1.11      www      11968:     }
1.448     albertel 11969:     close($config);
1.11      www      11970: }
                   11971: 
                   11972: # -------------------------------------------- Read plain texts for permissions
                   11973: {
1.448     albertel 11974:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      11975: 
                   11976:     while (my $configline=<$config>) {
1.448     albertel 11977: 	chomp($configline);
                   11978: 	if ($configline) {
1.742     raeburn  11979: 	    my ($short,@plain)=split(/:/,$configline);
                   11980:             %{$prp{$short}} = ();
                   11981: 	    if (@plain > 0) {
                   11982:                 $prp{$short}{'std'} = $plain[0];
                   11983:                 for (my $i=1; $i<@plain; $i++) {
                   11984:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   11985:                 }
                   11986:             }
1.448     albertel 11987: 	}
1.135     www      11988:     }
1.448     albertel 11989:     close($config);
1.135     www      11990: }
                   11991: 
                   11992: # ---------------------------------------------------------- Read package table
                   11993: {
1.448     albertel 11994:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      11995: 
                   11996:     while (my $configline=<$config>) {
1.483     albertel 11997: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 11998: 	chomp($configline);
                   11999: 	my ($short,$plain)=split(/:/,$configline);
                   12000: 	my ($pack,$name)=split(/\&/,$short);
                   12001: 	if ($plain ne '') {
                   12002: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   12003: 	    $packagetab{$short}=$plain; 
                   12004: 	}
1.11      www      12005:     }
1.448     albertel 12006:     close($config);
1.329     matthew  12007: }
                   12008: 
1.1073    raeburn  12009: # ---------------------------------------------------------- Read loncaparev table
                   12010: {
                   12011:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   12012:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   12013:             while (my $configline=<$config>) {
                   12014:                 chomp($configline);
                   12015:                 my ($hostid,$loncaparev)=split(/:/,$configline);
                   12016:                 $loncaparevs{$hostid}=$loncaparev;
                   12017:             }
                   12018:             close($config);
                   12019:         }
                   12020:     }
                   12021: }
                   12022: 
1.1074    raeburn  12023: # ---------------------------------------------------------- Read serverhostID table
                   12024: {
                   12025:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   12026:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   12027:             while (my $configline=<$config>) {
                   12028:                 chomp($configline);
                   12029:                 my ($name,$id)=split(/:/,$configline);
                   12030:                 $serverhomeIDs{$name}=$id;
                   12031:             }
                   12032:             close($config);
                   12033:         }
                   12034:     }
                   12035: }
                   12036: 
1.1079    raeburn  12037: {
                   12038:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   12039:     if (-e $file) {
                   12040:         my $parser = HTML::LCParser->new($file);
                   12041:         while (my $token = $parser->get_token()) {
                   12042:             if ($token->[0] eq 'S') {
                   12043:                 my $item = $token->[1];
                   12044:                 my $name = $token->[2]{'name'};
                   12045:                 my $value = $token->[2]{'value'};
                   12046:                 if ($item ne '' && $name ne '' && $value ne '') {
                   12047:                     my $release = $parser->get_text();
                   12048:                     $release =~ s/(^\s*|\s*$ )//gx;
                   12049:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   12050:                 }
                   12051:             }
                   12052:         }
                   12053:     }
1.1073    raeburn  12054: }
                   12055: 
1.1138    raeburn  12056: # ---------------------------------------------------------- Read managers table
                   12057: {
                   12058:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   12059:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   12060:             while (my $configline=<$config>) {
                   12061:                 chomp($configline);
                   12062:                 next if ($configline =~ /^\#/);
                   12063:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   12064:                     $managerstab{$configline} = 1;
                   12065:                 }
                   12066:             }
                   12067:             close($config);
                   12068:         }
                   12069:     }
                   12070: }
                   12071: 
1.329     matthew  12072: # ------------- set up temporary directory
                   12073: {
1.1117    foxr     12074:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  12075: 
1.11      www      12076: }
                   12077: 
1.794     albertel 12078: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   12079: 				'compress_threshold'=> 20_000,
                   12080:  			        });
1.185     www      12081: 
1.281     www      12082: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      12083: $dumpcount=0;
1.958     www      12084: $locknum=0;
1.22      www      12085: 
1.163     harris41 12086: &logtouch();
1.672     albertel 12087: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      12088: $readit=1;
1.564     albertel 12089:     {
                   12090: 	use integer;
                   12091: 	my $test=(2**32)+1;
1.568     albertel 12092: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 12093: 	&logthis(" Detected 64bit platform ($_64bit)");
                   12094:     }
1.195     www      12095: }
1.1       albertel 12096: }
1.179     www      12097: 
1.1       albertel 12098: 1;
1.191     harris41 12099: __END__
                   12100: 
1.243     albertel 12101: =pod
                   12102: 
1.191     harris41 12103: =head1 NAME
                   12104: 
1.243     albertel 12105: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 12106: 
                   12107: =head1 SYNOPSIS
                   12108: 
1.243     albertel 12109: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 12110: 
                   12111:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   12112: 
1.243     albertel 12113: Common parameters:
                   12114: 
                   12115: =over 4
                   12116: 
                   12117: =item *
                   12118: 
                   12119: $uname : an internal username (if $cname expecting a course Id specifically)
                   12120: 
                   12121: =item *
                   12122: 
                   12123: $udom : a domain (if $cdom expecting a course's domain specifically)
                   12124: 
                   12125: =item *
                   12126: 
                   12127: $symb : a resource instance identifier
                   12128: 
                   12129: =item *
                   12130: 
                   12131: $namespace : the name of a .db file that contains the data needed or
                   12132: being set.
                   12133: 
                   12134: =back
                   12135: 
1.394     bowersj2 12136: =head1 OVERVIEW
1.191     harris41 12137: 
1.394     bowersj2 12138: lonnet provides subroutines which interact with the
                   12139: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   12140: about classes, users, and resources.
1.243     albertel 12141: 
                   12142: For many of these objects you can also use this to store data about
                   12143: them or modify them in various ways.
1.191     harris41 12144: 
1.394     bowersj2 12145: =head2 Symbs
1.191     harris41 12146: 
1.394     bowersj2 12147: To identify a specific instance of a resource, LON-CAPA uses symbols
                   12148: or "symbs"X<symb>. These identifiers are built from the URL of the
                   12149: map, the resource number of the resource in the map, and the URL of
                   12150: the resource itself. The latter is somewhat redundant, but might help
                   12151: if maps change.
                   12152: 
                   12153: An example is
                   12154: 
                   12155:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   12156: 
                   12157: The respective map entry is
                   12158: 
                   12159:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   12160:   title="Problem 2">
                   12161:  </resource>
                   12162: 
                   12163: Symbs are used by the random number generator, as well as to store and
                   12164: restore data specific to a certain instance of for example a problem.
                   12165: 
                   12166: =head2 Storing And Retrieving Data
                   12167: 
                   12168: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   12169: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   12170: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   12171: is is the non-critical message twin of cstore. These functions are for
                   12172: handlers to store a perl hash to a user's permanent data space in an
                   12173: easy manner, and to retrieve it again on another call. It is expected
                   12174: that a handler would use this once at the beginning to retrieve data,
                   12175: and then again once at the end to send only the new data back.
                   12176: 
                   12177: The data is stored in the user's data directory on the user's
                   12178: homeserver under the ID of the course.
                   12179: 
                   12180: The hash that is returned by restore will have all of the previous
                   12181: value for all of the elements of the hash.
                   12182: 
                   12183: Example:
                   12184: 
                   12185:  #creating a hash
                   12186:  my %hash;
                   12187:  $hash{'foo'}='bar';
                   12188: 
                   12189:  #storing it
                   12190:  &Apache::lonnet::cstore(\%hash);
                   12191: 
                   12192:  #changing a value
                   12193:  $hash{'foo'}='notbar';
                   12194: 
                   12195:  #adding a new value
                   12196:  $hash{'bar'}='foo';
                   12197:  &Apache::lonnet::cstore(\%hash);
                   12198: 
                   12199:  #retrieving the hash
                   12200:  my %history=&Apache::lonnet::restore();
                   12201: 
                   12202:  #print the hash
                   12203:  foreach my $key (sort(keys(%history))) {
                   12204:    print("\%history{$key} = $history{$key}");
                   12205:  }
                   12206: 
                   12207: Will print out:
1.191     harris41 12208: 
1.394     bowersj2 12209:  %history{1:foo} = bar
                   12210:  %history{1:keys} = foo:timestamp
                   12211:  %history{1:timestamp} = 990455579
                   12212:  %history{2:bar} = foo
                   12213:  %history{2:foo} = notbar
                   12214:  %history{2:keys} = foo:bar:timestamp
                   12215:  %history{2:timestamp} = 990455580
                   12216:  %history{bar} = foo
                   12217:  %history{foo} = notbar
                   12218:  %history{timestamp} = 990455580
                   12219:  %history{version} = 2
                   12220: 
                   12221: Note that the special hash entries C<keys>, C<version> and
                   12222: C<timestamp> were added to the hash. C<version> will be equal to the
                   12223: total number of versions of the data that have been stored. The
                   12224: C<timestamp> attribute will be the UNIX time the hash was
                   12225: stored. C<keys> is available in every historical section to list which
                   12226: keys were added or changed at a specific historical revision of a
                   12227: hash.
                   12228: 
                   12229: B<Warning>: do not store the hash that restore returns directly. This
                   12230: will cause a mess since it will restore the historical keys as if the
                   12231: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 12232: 
1.394     bowersj2 12233: Calling convention:
1.191     harris41 12234: 
1.394     bowersj2 12235:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   12236:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 12237: 
1.394     bowersj2 12238: For more detailed information, see lonnet specific documentation.
1.191     harris41 12239: 
1.394     bowersj2 12240: =head1 RETURN MESSAGES
1.191     harris41 12241: 
1.394     bowersj2 12242: =over 4
1.191     harris41 12243: 
1.394     bowersj2 12244: =item * B<con_lost>: unable to contact remote host
1.191     harris41 12245: 
1.394     bowersj2 12246: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   12247: when the connection is brought back up
1.191     harris41 12248: 
1.394     bowersj2 12249: =item * B<con_failed>: unable to contact remote host and unable to save message
                   12250: for later delivery
1.191     harris41 12251: 
1.967     bisitz   12252: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 12253: 
1.394     bowersj2 12254: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 12255: that was requested
1.191     harris41 12256: 
1.243     albertel 12257: =back
1.191     harris41 12258: 
1.243     albertel 12259: =head1 PUBLIC SUBROUTINES
1.191     harris41 12260: 
1.243     albertel 12261: =head2 Session Environment Functions
1.191     harris41 12262: 
1.243     albertel 12263: =over 4
1.191     harris41 12264: 
1.394     bowersj2 12265: =item * 
                   12266: X<appenv()>
1.949     raeburn  12267: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 12268: the user envirnoment file, and will be restored for each access this
1.620     albertel 12269: user makes during this session, also modifies the %env for the current
1.949     raeburn  12270: process. Optional rolesarrayref - if defined contains a reference to an array
                   12271: of roles which are exempt from the restriction on modifying user.role entries 
                   12272: in the user's environment.db and in %env.    
1.191     harris41 12273: 
                   12274: =item *
1.394     bowersj2 12275: X<delenv()>
1.987     raeburn  12276: B<delenv($delthis,$regexp)>: removes all items from the session
                   12277: environment file that begin with $delthis. If the 
                   12278: optional second arg - $regexp - is true, $delthis is treated as a 
                   12279: regular expression, otherwise \Q$delthis\E is used. 
                   12280: The values are also deleted from the current processes %env.
1.191     harris41 12281: 
1.795     albertel 12282: =item * get_env_multiple($name) 
                   12283: 
                   12284: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   12285: values may be defined and end up as an array ref.
                   12286: 
                   12287: returns an array of values
                   12288: 
1.243     albertel 12289: =back
                   12290: 
                   12291: =head2 User Information
1.191     harris41 12292: 
1.243     albertel 12293: =over 4
1.191     harris41 12294: 
                   12295: =item *
1.394     bowersj2 12296: X<queryauthenticate()>
                   12297: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 12298: authentication scheme
                   12299: 
                   12300: =item *
1.394     bowersj2 12301: X<authenticate()>
1.1073    raeburn  12302: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 12303: authenticate user from domain's lib servers (first use the current
                   12304: one). C<$upass> should be the users password.
1.1073    raeburn  12305: $checkdefauth is optional (value is 1 if a check should be made to
                   12306:    authenticate user using default authentication method, and allow
                   12307:    account creation if username does not have account in the domain).
                   12308: $clientcancheckhost is optional (value is 1 if checking whether the
                   12309:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 12310: 
                   12311: =item *
1.394     bowersj2 12312: X<homeserver()>
                   12313: B<homeserver($uname,$udom)>: find the server which has
                   12314: the user's directory and files (there must be only one), this caches
                   12315: the answer, and also caches if there is a borken connection.
1.191     harris41 12316: 
                   12317: =item *
1.394     bowersj2 12318: X<idget()>
                   12319: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   12320: (IDs are a unique resource in a domain, there must be only 1 ID per
                   12321: username, and only 1 username per ID in a specific domain) (returns
                   12322: hash: id=>name,id=>name)
1.191     harris41 12323: 
                   12324: =item *
1.394     bowersj2 12325: X<idrget()>
                   12326: B<idrget($udom,@unames)>: find the IDs behind a list of
                   12327: usernames (returns hash: name=>id,name=>id)
1.191     harris41 12328: 
                   12329: =item *
1.394     bowersj2 12330: X<idput()>
                   12331: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 12332: 
                   12333: =item *
1.394     bowersj2 12334: X<rolesinit()>
1.1169    droeschl 12335: B<rolesinit($udom,$username)>: get user privileges.
                   12336: returns user role, first access and timer interval hashes
1.243     albertel 12337: 
                   12338: =item *
1.1171    droeschl 12339: X<privileged()>
                   12340: B<privileged($username,$domain)>: returns a true if user has a
                   12341: privileged and active role (i.e. su or dc), false otherwise.
                   12342: 
                   12343: =item *
1.551     albertel 12344: X<getsection()>
                   12345: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 12346: course $cname, return section name/number or '' for "not in course"
                   12347: and '-1' for "no section"
                   12348: 
                   12349: =item *
1.394     bowersj2 12350: X<userenvironment()>
                   12351: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 12352: passed in @what from the requested user's environment, returns a hash
                   12353: 
1.858     raeburn  12354: =item * 
                   12355: X<userlog_query()>
1.859     albertel 12356: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   12357: activity.log file. %filters defines filters applied when parsing the
                   12358: log file. These can be start or end timestamps, or the type of action
                   12359: - log to look for Login or Logout events, check for Checkin or
                   12360: Checkout, role for role selection. The response is in the form
                   12361: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   12362: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  12363: 
1.243     albertel 12364: =back
                   12365: 
                   12366: =head2 User Roles
                   12367: 
                   12368: =over 4
                   12369: 
                   12370: =item *
                   12371: 
1.810     raeburn  12372: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 12373:  F: full access
                   12374:  U,I,K: authentication modes (cxx only)
                   12375:  '': forbidden
                   12376:  1: user needs to choose course
                   12377:  2: browse allowed
1.766     albertel 12378:  A: passphrase authentication needed
1.243     albertel 12379: 
                   12380: =item *
                   12381: 
1.1172.2.13  raeburn  12382: constructaccess($url,$setpriv) : check for access to construction space URL
                   12383: 
                   12384: See if the owner domain and name in the URL match those in the
                   12385: expected environment.  If so, return three element list
                   12386: ($ownername,$ownerdomain,$ownerhome).
                   12387: 
                   12388: Otherwise return the null string.
                   12389: 
                   12390: If second argument 'setpriv' is true, it assigns the privileges,
                   12391: and returns the same three element list, unless the owner has
                   12392: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   12393: in which case the null string is returned.
                   12394: 
                   12395: =item *
                   12396: 
1.243     albertel 12397: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   12398: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   12399: and course level
                   12400: 
                   12401: =item *
                   12402: 
1.988     raeburn  12403: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   12404: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  12405: $type is Course (default) or Community.
1.988     raeburn  12406: If $forcedefault evaluates to true, text returned will be default 
                   12407: text for $type. Otherwise, if this is a course, the text returned 
                   12408: will be a custom name for the role (if defined in the course's 
                   12409: environment).  If no custom name is defined the default is returned.
                   12410:    
1.832     raeburn  12411: =item *
                   12412: 
1.935     raeburn  12413: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  12414: All arguments are optional. Returns a hash of a roles, either for
                   12415: co-author/assistant author roles for a user's Construction Space
1.906     albertel 12416: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  12417: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   12418: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   12419: For each key, value is set to colon-separated start and end times for
                   12420: the role.  If no username and domain are specified, will default to
1.934     raeburn  12421: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  12422: of role statuses (active, future or previous), roles 
                   12423: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   12424: to restrict the list of roles reported. If no array ref is 
                   12425: provided for types, will default to return only active roles.
1.834     albertel 12426: 
1.1172.2.13  raeburn  12427: =item *
                   12428: 
                   12429: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   12430: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   12431: 
                   12432: Additional optional arguments are: $type (if role checking is to be restricted
                   12433: to certain user status types -- previous (expired roles), active (currently
                   12434: available roles) or future (roles available in the future), and
                   12435: $hideprivileged -- if true will not report course roles for users who
                   12436: have active Domain Coordinator or Super User roles.
                   12437: 
1.243     albertel 12438: =back
                   12439: 
                   12440: =head2 User Modification
                   12441: 
                   12442: =over 4
                   12443: 
                   12444: =item *
                   12445: 
1.957     raeburn  12446: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 12447: user for the level given by URL.  Optional start and end dates (leave empty
                   12448: string or zero for "no date")
1.191     harris41 12449: 
                   12450: =item *
                   12451: 
1.243     albertel 12452: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   12453: change a users, password, possible return values are: ok,
                   12454: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   12455: refused
1.191     harris41 12456: 
                   12457: =item *
                   12458: 
1.243     albertel 12459: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 12460: 
                   12461: =item *
                   12462: 
1.1058    raeburn  12463: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   12464:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   12465: 
                   12466: will update user information (firstname,middlename,lastname,generation,
                   12467: permanentemail), and if forceid is true, student/employee ID also.
                   12468: A user's institutional affiliation(s) can also be updated.
                   12469: User information fields will not be overwritten with empty entries 
                   12470: unless the field is included in the $candelete array reference.
                   12471: This array is included when a single user is modified via "Manage Users",
                   12472: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 12473: 
                   12474: =item *
                   12475: 
1.286     matthew  12476: modifystudent
                   12477: 
1.957     raeburn  12478: modify a student's enrollment and identification information.
1.286     matthew  12479: The course id is resolved based on the current users environment.  
                   12480: This means the envoking user must be a course coordinator or otherwise
                   12481: associated with a course.
                   12482: 
1.297     matthew  12483: This call is essentially a wrapper for lonnet::modifyuser and
                   12484: lonnet::modify_student_enrollment
1.286     matthew  12485: 
                   12486: Inputs: 
                   12487: 
                   12488: =over 4
                   12489: 
1.957     raeburn  12490: =item B<$udom> Student's loncapa domain
1.286     matthew  12491: 
1.957     raeburn  12492: =item B<$uname> Student's loncapa login name
1.286     matthew  12493: 
1.964     bisitz   12494: =item B<$uid> Student/Employee ID
1.286     matthew  12495: 
1.957     raeburn  12496: =item B<$umode> Student's authentication mode
1.286     matthew  12497: 
1.957     raeburn  12498: =item B<$upass> Student's password
1.286     matthew  12499: 
1.957     raeburn  12500: =item B<$first> Student's first name
1.286     matthew  12501: 
1.957     raeburn  12502: =item B<$middle> Student's middle name
1.286     matthew  12503: 
1.957     raeburn  12504: =item B<$last> Student's last name
1.286     matthew  12505: 
1.957     raeburn  12506: =item B<$gene> Student's generation
1.286     matthew  12507: 
1.957     raeburn  12508: =item B<$usec> Student's section in course
1.286     matthew  12509: 
                   12510: =item B<$end> Unix time of the roles expiration
                   12511: 
                   12512: =item B<$start> Unix time of the roles start date
                   12513: 
                   12514: =item B<$forceid> If defined, allow $uid to be changed
                   12515: 
                   12516: =item B<$desiredhome> server to use as home server for student
                   12517: 
1.957     raeburn  12518: =item B<$email> Student's permanent e-mail address
                   12519: 
                   12520: =item B<$type> Type of enrollment (auto or manual)
                   12521: 
1.963     raeburn  12522: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   12523: 
                   12524: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  12525: 
1.963     raeburn  12526: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  12527: 
1.963     raeburn  12528: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  12529: 
1.963     raeburn  12530: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  12531: 
1.286     matthew  12532: =back
1.297     matthew  12533: 
                   12534: =item *
                   12535: 
                   12536: modify_student_enrollment
                   12537: 
                   12538: Change a students enrollment status in a class.  The environment variable
                   12539: 'role.request.course' must be defined for this function to proceed.
                   12540: 
                   12541: Inputs:
                   12542: 
                   12543: =over 4
                   12544: 
                   12545: =item $udom, students domain
                   12546: 
                   12547: =item $uname, students name
                   12548: 
                   12549: =item $uid, students user id
                   12550: 
                   12551: =item $first, students first name
                   12552: 
                   12553: =item $middle
                   12554: 
                   12555: =item $last
                   12556: 
                   12557: =item $gene
                   12558: 
                   12559: =item $usec
                   12560: 
                   12561: =item $end
                   12562: 
                   12563: =item $start
                   12564: 
1.957     raeburn  12565: =item $type
                   12566: 
                   12567: =item $locktype
                   12568: 
                   12569: =item $cid
                   12570: 
                   12571: =item $selfenroll
                   12572: 
                   12573: =item $context
                   12574: 
1.297     matthew  12575: =back
                   12576: 
1.191     harris41 12577: 
                   12578: =item *
                   12579: 
1.243     albertel 12580: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   12581: custom role; give a custom role to a user for the level given by URL.  Specify
                   12582: name and domain of role author, and role name
1.191     harris41 12583: 
                   12584: =item *
                   12585: 
1.243     albertel 12586: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 12587: 
                   12588: =item *
                   12589: 
1.243     albertel 12590: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   12591: 
                   12592: =back
                   12593: 
                   12594: =head2 Course Infomation
                   12595: 
                   12596: =over 4
1.191     harris41 12597: 
                   12598: =item *
                   12599: 
1.1118    foxr     12600: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 12601: specified course id, including all environment settings for the
                   12602: course, the description of the course will be in the hash under the
                   12603: key 'description'
1.191     harris41 12604: 
1.1118    foxr     12605: $options is an optional parameter that if supplied is a hash reference that controls
                   12606: what how this function works.  It has the following key/values:
                   12607: 
                   12608: =over 4
                   12609: 
                   12610: =item freshen_cache
                   12611: 
                   12612: If defined, and the environment cache for the course is valid, it is 
                   12613: returned in the returned hash.
                   12614: 
                   12615: =item one_time
                   12616: 
                   12617: If defined, the last cache time is set to _now_
                   12618: 
                   12619: =item user
                   12620: 
                   12621: If defined, the supplied username is used instead of the current user.
                   12622: 
                   12623: 
                   12624: =back
                   12625: 
1.191     harris41 12626: =item *
                   12627: 
1.624     albertel 12628: resdata($name,$domain,$type,@which) : request for current parameter
                   12629: setting for a specific $type, where $type is either 'course' or 'user',
                   12630: @what should be a list of parameters to ask about. This routine caches
                   12631: answers for 5 minutes.
1.243     albertel 12632: 
1.877     foxr     12633: =item *
                   12634: 
                   12635: get_courseresdata($courseid, $domain) : dump the entire course resource
                   12636: data base, returning a hash that is keyed by the resource name and has
                   12637: values that are the resource value.  I believe that the timestamps and
                   12638: versions are also returned.
                   12639: 
1.243     albertel 12640: =back
                   12641: 
                   12642: =head2 Course Modification
                   12643: 
                   12644: =over 4
1.191     harris41 12645: 
                   12646: =item *
                   12647: 
1.243     albertel 12648: writecoursepref($courseid,%prefs) : write preferences (environment
                   12649: database) for a course
1.191     harris41 12650: 
                   12651: =item *
                   12652: 
1.1011    raeburn  12653: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   12654: 
                   12655: =item *
                   12656: 
1.1038    raeburn  12657: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 12658: 
1.1167    droeschl 12659: =item *
                   12660: 
                   12661: is_course($courseid), is_course($cdom, $cnum)
                   12662: 
                   12663: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   12664: two component version $cdom, $cnum. It checks if the specified course exists.
                   12665: 
                   12666: Returns:
                   12667:     undef if the course doesn't exist, otherwise
                   12668:     in scalar context the combined courseid.
                   12669:     in list context the two components of the course identifier, domain and 
                   12670:     courseid.    
                   12671: 
1.243     albertel 12672: =back
                   12673: 
                   12674: =head2 Resource Subroutines
                   12675: 
                   12676: =over 4
1.191     harris41 12677: 
                   12678: =item *
                   12679: 
1.243     albertel 12680: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 12681: 
                   12682: =item *
                   12683: 
1.243     albertel 12684: repcopy($filename) : subscribes to the requested file, and attempts to
                   12685: replicate from the owning library server, Might return
1.607     raeburn  12686: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   12687: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 12688: resource. Expects the local filesystem pathname
                   12689: (/home/httpd/html/res/....)
                   12690: 
                   12691: =back
                   12692: 
                   12693: =head2 Resource Information
                   12694: 
                   12695: =over 4
1.191     harris41 12696: 
                   12697: =item *
                   12698: 
1.243     albertel 12699: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   12700: a vairety of different possible values, $varname should be a request
                   12701: string, and the other parameters can be used to specify who and what
                   12702: one is asking about.
                   12703: 
                   12704: Possible values for $varname are environment.lastname (or other item
                   12705: from the envirnment hash), user.name (or someother aspect about the
                   12706: user), resource.0.maxtries (or some other part and parameter of a
                   12707: resource)
1.204     albertel 12708: 
                   12709: =item *
                   12710: 
1.243     albertel 12711: directcondval($number) : get current value of a condition; reads from a state
                   12712: string
1.204     albertel 12713: 
                   12714: =item *
                   12715: 
1.243     albertel 12716: condval($condidx) : value of condition index based on state
1.204     albertel 12717: 
                   12718: =item *
                   12719: 
1.243     albertel 12720: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   12721: resource's metadata, $what should be either a specific key, or either
                   12722: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   12723: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   12724: 
                   12725: this function automatically caches all requests
1.191     harris41 12726: 
                   12727: =item *
                   12728: 
1.243     albertel 12729: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   12730: network of library servers; returns file handle of where SQL and regex results
                   12731: will be stored for query
1.191     harris41 12732: 
                   12733: =item *
                   12734: 
1.243     albertel 12735: symbread($filename) : return symbolic list entry (filename argument optional);
                   12736: returns the data handle
1.191     harris41 12737: 
                   12738: =item *
                   12739: 
1.1172.2.11  raeburn  12740: symbverify($symb,$thisfn,$ecstate) : verifies that $symb actually exists
                   12741: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 12742: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  12743: on failure, user must be in a course, as it assumes the existence of
                   12744: the course initial hash, and uses $env('request.course.id'}.  The third
                   12745: arg is an optional reference to a scalar.  If this arg is passed in the
                   12746: call to symbverify, it will be set to 1 if the symb has been set to be 
                   12747: encrypted; otherwise it will be null.
1.243     albertel 12748: 
1.191     harris41 12749: =item *
                   12750: 
1.243     albertel 12751: symbclean($symb) : removes versions numbers from a symb, returns the
                   12752: cleaned symb
1.191     harris41 12753: 
                   12754: =item *
                   12755: 
1.243     albertel 12756: is_on_map($uri) : checks if the $uri is somewhere on the current
                   12757: course map, user must be in a course for it to work.
1.191     harris41 12758: 
                   12759: =item *
                   12760: 
1.243     albertel 12761: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 12762: 
                   12763: =item *
                   12764: 
1.243     albertel 12765: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   12766: a random seed, all arguments are optional, if they aren't sent it uses the
                   12767: environment to derive them. Note: if symb isn't sent and it can't get one
                   12768: from &symbread it will use the current time as its return value
1.191     harris41 12769: 
                   12770: =item *
                   12771: 
1.243     albertel 12772: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   12773: unfakeable, receipt
1.191     harris41 12774: 
                   12775: =item *
                   12776: 
1.620     albertel 12777: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 12778: 
                   12779: =item *
                   12780: 
1.243     albertel 12781: countacc($url) : count the number of accesses to a given URL
1.191     harris41 12782: 
                   12783: =item *
                   12784: 
1.243     albertel 12785: 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 12786: 
                   12787: =item *
                   12788: 
1.243     albertel 12789: 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 12790: 
                   12791: =item *
                   12792: 
1.243     albertel 12793: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 12794: 
                   12795: =item *
                   12796: 
1.243     albertel 12797: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   12798: forcing spreadsheet to reevaluate the resource scores next time.
                   12799: 
1.1172.2.13  raeburn  12800: =item *
                   12801: 
                   12802: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   12803: when viewing in course context.
                   12804: 
                   12805:  input: six args -- filename (decluttered), course number, course domain,
                   12806:                     url, symb (if registered) and group (if this is a
                   12807:                     group item -- e.g., bulletin board, group page etc.).
                   12808: 
                   12809:  output: array of five scalars --
                   12810:          $cfile -- url for file editing if editable on current server
                   12811:          $home -- homeserver of resource (i.e., for author if published,
                   12812:                                           or course if uploaded.).
                   12813:          $switchserver --  1 if server switch will be needed.
                   12814:          $forceedit -- 1 if icon/link should be to go to edit mode
                   12815:          $forceview -- 1 if icon/link should be to go to view mode
                   12816: 
                   12817: =item *
                   12818: 
                   12819: is_course_upload($file,$cnum,$cdom)
                   12820: 
                   12821: Used in course context to determine if current file was uploaded to
                   12822: the course (i.e., would be found in /userfiles/docs on the course's
                   12823: homeserver.
                   12824: 
                   12825:   input: 3 args -- filename (decluttered), course number and course domain.
                   12826:   output: boolean -- 1 if file was uploaded.
                   12827: 
1.243     albertel 12828: =back
                   12829: 
                   12830: =head2 Storing/Retreiving Data
                   12831: 
                   12832: =over 4
1.191     harris41 12833: 
                   12834: =item *
                   12835: 
1.243     albertel 12836: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   12837: for this url; hashref needs to be given and should be a \%hashname; the
                   12838: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 12839: be derived from the env
1.191     harris41 12840: 
                   12841: =item *
                   12842: 
1.243     albertel 12843: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   12844: uses critical subroutine
1.191     harris41 12845: 
                   12846: =item *
                   12847: 
1.243     albertel 12848: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   12849: all args are optional
1.191     harris41 12850: 
                   12851: =item *
                   12852: 
1.717     albertel 12853: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   12854: dumps the complete (or key matching regexp) namespace into a hash
                   12855: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   12856: normally &store()ed into
                   12857: 
                   12858: $range should be either an integer '100' (give me the first 100
                   12859:                                            matching records)
                   12860:               or be  two integers sperated by a - with no spaces
                   12861:                  '30-50' (give me the 30th through the 50th matching
                   12862:                           records)
                   12863: 
                   12864: 
                   12865: =item *
                   12866: 
                   12867: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   12868: replaces a &store() version of data with a replacement set of data
                   12869: for a particular resource in a namespace passed in the $storehash hash 
                   12870: reference
                   12871: 
                   12872: =item *
                   12873: 
1.243     albertel 12874: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   12875: works very similar to store/cstore, but all data is stored in a
                   12876: temporary location and can be reset using tmpreset, $storehash should
                   12877: be a hash reference, returns nothing on success
1.191     harris41 12878: 
                   12879: =item *
                   12880: 
1.243     albertel 12881: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   12882: similar to restore, but all data is stored in a temporary location and
                   12883: can be reset using tmpreset. Returns a hash of values on success,
                   12884: error string otherwise.
1.191     harris41 12885: 
                   12886: =item *
                   12887: 
1.243     albertel 12888: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   12889: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 12890: 
                   12891: =item *
                   12892: 
1.243     albertel 12893: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   12894: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 12895: 
                   12896: =item *
                   12897: 
1.243     albertel 12898: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   12899: namesp ($udom and $uname are optional)
1.191     harris41 12900: 
                   12901: =item *
                   12902: 
1.702     albertel 12903: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 12904: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 12905: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  12906: 
1.702     albertel 12907: $range should be either an integer '100' (give me the first 100
                   12908:                                            matching records)
                   12909:               or be  two integers sperated by a - with no spaces
                   12910:                  '30-50' (give me the 30th through the 50th matching
                   12911:                           records)
1.449     matthew  12912: =item *
                   12913: 
                   12914: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   12915: $store can be a scalar, an array reference, or if the amount to be 
                   12916: incremented is > 1, a hash reference.
                   12917: 
                   12918: ($udom and $uname are optional)
1.191     harris41 12919: 
                   12920: =item *
                   12921: 
1.243     albertel 12922: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   12923: ($udom and $uname are optional)
1.191     harris41 12924: 
                   12925: =item *
                   12926: 
1.243     albertel 12927: cput($namespace,$storehash,$udom,$uname) : critical put
                   12928: ($udom and $uname are optional)
1.191     harris41 12929: 
                   12930: =item *
                   12931: 
1.748     albertel 12932: newput($namespace,$storehash,$udom,$uname) :
                   12933: 
                   12934: Attempts to store the items in the $storehash, but only if they don't
                   12935: currently exist, if this succeeds you can be certain that you have 
                   12936: successfully created a new key value pair in the $namespace db.
                   12937: 
                   12938: 
                   12939: Args:
                   12940:  $namespace: name of database to store values to
                   12941:  $storehash: hashref to store to the db
                   12942:  $udom: (optional) domain of user containing the db
                   12943:  $uname: (optional) name of user caontaining the db
                   12944: 
                   12945: Returns:
                   12946:  'ok' -> succeeded in storing all keys of $storehash
                   12947:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   12948:                         least <key> already existed in the db (other
                   12949:                         requested keys may also already exist)
1.967     bisitz   12950:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 12951:  'con_lost' -> unable to contact request server
                   12952:  'refused' -> action was not allowed by remote machine
                   12953: 
                   12954: 
                   12955: =item *
                   12956: 
1.243     albertel 12957: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   12958: reference filled in from namesp (encrypts the return communication)
                   12959: ($udom and $uname are optional)
1.191     harris41 12960: 
                   12961: =item *
                   12962: 
1.243     albertel 12963: log($udom,$name,$home,$message) : write to permanent log for user; use
                   12964: critical subroutine
                   12965: 
1.806     raeburn  12966: =item *
                   12967: 
1.860     raeburn  12968: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   12969: array reference filled in from namespace found in domain level on either
                   12970: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  12971: 
                   12972: =item *
                   12973: 
1.860     raeburn  12974: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   12975: domain level either on specified domain server ($uhome) or primary domain 
                   12976: server ($udom and $uhome are optional)
1.806     raeburn  12977: 
1.943     raeburn  12978: =item * 
                   12979: 
                   12980: get_domain_defaults($target_domain) : returns hash with defaults for
                   12981: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   12982: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   12983: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   12984: Values are retrieved from cache (if current), or from domain's configuration.db
                   12985: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   12986: or lonTabs/domain.tab. 
                   12987: 
                   12988: %domdefaults = &get_auth_defaults($target_domain);
                   12989: 
1.243     albertel 12990: =back
                   12991: 
                   12992: =head2 Network Status Functions
                   12993: 
                   12994: =over 4
1.191     harris41 12995: 
                   12996: =item *
                   12997: 
1.1137    raeburn  12998: dirlist() : return directory list based on URI (first arg).
                   12999: 
                   13000: Inputs: 1 required, 5 optional.
                   13001: 
                   13002: =over
                   13003: 
                   13004: =item 
                   13005: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   13006: 
                   13007: =item
                   13008: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   13009: 
                   13010: =item
                   13011: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   13012: 
                   13013: =item
                   13014: $getpropath - boolean: 1 if prepend path using &propath(). 
                   13015: 
                   13016: =item
                   13017: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   13018: 
                   13019: =item 
                   13020: $alternateRoot - path to prepend in place of path from $uri.
                   13021: 
                   13022: =back
                   13023: 
                   13024: Returns: Array of up to two items.
                   13025: 
                   13026: =over
                   13027: 
                   13028: a reference to an array of files/subdirectories
                   13029: 
                   13030: =over
                   13031: 
                   13032: Each element in the array of files/subdirectories is a & separated list of
                   13033: item name and the result of running stat on the item.  If dirlist was requested
                   13034: for a file instead of a directory, the item name will be ''. For a directory 
                   13035: listing, if the item is a metadata file, the element will end &N&M 
                   13036: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   13037: default copyright set (1).  
                   13038: 
                   13039: =back
                   13040: 
                   13041: a scalar containing error condition (if encountered).
                   13042: 
                   13043: =over
                   13044: 
                   13045: =item 
                   13046: no_host (no homeserver identified for $username:$domain).
                   13047: 
                   13048: =item 
                   13049: no_such_host (server contacted for listing not identified as valid host).
                   13050: 
                   13051: =item 
                   13052: con_lost (connection to remote server failed).
                   13053: 
                   13054: =item 
                   13055: refused (invalid $username:$domain received on lond side).
                   13056: 
                   13057: =item 
                   13058: no_such_dir (directory at specified path on lond side does not exist). 
                   13059: 
                   13060: =item 
                   13061: empty (directory at specified path on lond side is empty).
                   13062: 
                   13063: =over
                   13064: 
                   13065: This is currently not encountered because the &ls3, &ls2, 
                   13066: &ls (_handler) routines on the lond side do not filter out
                   13067: . and .. from a directory listing. 
                   13068: 
                   13069: =back
                   13070: 
                   13071: =back
                   13072: 
                   13073: =back
1.191     harris41 13074: 
                   13075: =item *
                   13076: 
1.243     albertel 13077: spareserver() : find server with least workload from spare.tab
                   13078: 
1.986     foxr     13079: 
                   13080: =item *
                   13081: 
                   13082: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   13083: if there is no corresponding loncapa host.
                   13084: 
1.243     albertel 13085: =back
                   13086: 
1.986     foxr     13087: 
1.243     albertel 13088: =head2 Apache Request
                   13089: 
                   13090: =over 4
1.191     harris41 13091: 
                   13092: =item *
                   13093: 
1.243     albertel 13094: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   13095: localhost, posts hash
                   13096: 
                   13097: =back
                   13098: 
                   13099: =head2 Data to String to Data
                   13100: 
                   13101: =over 4
1.191     harris41 13102: 
                   13103: =item *
                   13104: 
1.243     albertel 13105: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   13106: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 13107: 
                   13108: =item *
                   13109: 
1.243     albertel 13110: hashref2str($hashref) : convert a hashref into a string complete with
                   13111: escaping and '=' and '&' separators, supports elements that are
                   13112: arrayrefs and hashrefs
1.191     harris41 13113: 
                   13114: =item *
                   13115: 
1.243     albertel 13116: arrayref2str($arrayref) : convert an arrayref into a string complete
                   13117: with escaping and '&' separators, supports elements that are arrayrefs
                   13118: and hashrefs
1.191     harris41 13119: 
                   13120: =item *
                   13121: 
1.243     albertel 13122: str2hash($string) : convert string to hash using unescaping and
                   13123: splitting on '=' and '&', supports elements that are arrayrefs and
                   13124: hashrefs
1.191     harris41 13125: 
                   13126: =item *
                   13127: 
1.243     albertel 13128: str2array($string) : convert string to hash using unescaping and
                   13129: splitting on '&', supports elements that are arrayrefs and hashrefs
                   13130: 
                   13131: =back
                   13132: 
                   13133: =head2 Logging Routines
                   13134: 
                   13135: 
                   13136: These routines allow one to make log messages in the lonnet.log and
                   13137: lonnet.perm logfiles.
1.191     harris41 13138: 
1.1119    foxr     13139: =over 4
                   13140: 
1.191     harris41 13141: =item *
                   13142: 
1.243     albertel 13143: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 13144: 
                   13145: =item *
                   13146: 
1.243     albertel 13147: logthis() : append message to the normal lonnet.log file, it gets
                   13148: preiodically rolled over and deleted.
1.191     harris41 13149: 
                   13150: =item *
                   13151: 
1.243     albertel 13152: logperm() : append a permanent message to lonnet.perm.log, this log
                   13153: file never gets deleted by any automated portion of the system, only
                   13154: messages of critical importance should go in here.
                   13155: 
1.1119    foxr     13156: 
1.243     albertel 13157: =back
                   13158: 
                   13159: =head2 General File Helper Routines
                   13160: 
                   13161: =over 4
1.191     harris41 13162: 
                   13163: =item *
                   13164: 
1.481     raeburn  13165: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   13166: (a) files in /uploaded
                   13167:   (i) If a local copy of the file exists - 
                   13168:       compares modification date of local copy with last-modified date for 
                   13169:       definitive version stored on home server for course. If local copy is 
                   13170:       stale, requests a new version from the home server and stores it. 
                   13171:       If the original has been removed from the home server, then local copy 
                   13172:       is unlinked.
                   13173:   (ii) If local copy does not exist -
                   13174:       requests the file from the home server and stores it. 
                   13175:   
                   13176:   If $caller is 'uploadrep':  
                   13177:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   13178:     for request for files originally uploaded via DOCS. 
                   13179:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   13180:   
                   13181:   Otherwise:
                   13182:      This indicates a call from the content generation phase of the request.
                   13183:      -  returns the entire contents of the file or -1.
                   13184:      
                   13185: (b) files in /res
                   13186:    - returns the entire contents of a file or -1; 
                   13187:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 13188: 
1.712     albertel 13189: 
                   13190: =item *
                   13191: 
                   13192: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   13193:                   reference
                   13194: 
                   13195: returns either a stat() list of data about the file or an empty list
                   13196: if the file doesn't exist or couldn't find out about it (connection
                   13197: problems or user unknown)
                   13198: 
1.191     harris41 13199: =item *
                   13200: 
1.243     albertel 13201: filelocation($dir,$file) : returns file system location of a file
                   13202: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   13203: directory that relative $file lookups are to looked in ($dir of /a/dir
                   13204: and a file of ../bob will become /a/bob)
1.191     harris41 13205: 
                   13206: =item *
                   13207: 
                   13208: hreflocation($dir,$file) : returns file system location or a URL; same as
                   13209: filelocation except for hrefs
                   13210: 
                   13211: =item *
                   13212: 
                   13213: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   13214: 
1.243     albertel 13215: =back
                   13216: 
1.608     albertel 13217: =head2 Usererfile file routines (/uploaded*)
                   13218: 
                   13219: =over 4
                   13220: 
                   13221: =item *
                   13222: 
                   13223: userfileupload(): main rotine for putting a file in a user or course's
                   13224:                   filespace, arguments are,
                   13225: 
1.620     albertel 13226:  formname - required - this is the name of the element in $env where the
1.608     albertel 13227:            filename, and the contents of the file to create/modifed exist
1.620     albertel 13228:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   13229:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  13230:  context - if coursedoc, store the file in the course of the active role
                   13231:              of the current user; 
                   13232:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   13233:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 13234:  subdir - required - subdirectory to put the file in under ../userfiles/
                   13235:          if undefined, it will be placed in "unknown"
                   13236: 
                   13237:  (This routine calls clean_filename() to remove any dangerous
                   13238:  characters from the filename, and then calls finuserfileupload() to
                   13239:  complete the transaction)
                   13240: 
                   13241:  returns either the url of the uploaded file (/uploaded/....) if successful
                   13242:  and /adm/notfound.html if unsuccessful
                   13243: 
                   13244: =item *
                   13245: 
                   13246: clean_filename(): routine for cleaing a filename up for storage in
                   13247:                  userfile space, argument is:
                   13248: 
                   13249:  filename - proposed filename
                   13250: 
                   13251: returns: the new clean filename
                   13252: 
                   13253: =item *
                   13254: 
1.1090    raeburn  13255: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 13256: userspace, probably shouldn't be called directly
                   13257: 
                   13258:   docuname: username or courseid of destination for the file
                   13259:   docudom: domain of user/course of destination for the file
                   13260:   formname: same as for userfileupload()
1.1090    raeburn  13261:   fname: filename (including subdirectories) for the file
                   13262:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   13263:   allfiles: reference to hash used to store objects found by parser
                   13264:   codebase: reference to hash used for codebases of java objects found by parser
                   13265:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   13266:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   13267:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   13268:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   13269:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   13270:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  13271:   mimetype: reference to scalar to accommodate mime type determined
                   13272:             from File::MMagic if $parser = parse.
1.608     albertel 13273: 
                   13274:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  13275:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   13276:  was 'overwrite').
                   13277:  
1.608     albertel 13278: 
                   13279: =item *
                   13280: 
                   13281: renameuserfile(): renames an existing userfile to a new name
                   13282: 
                   13283:   Args:
                   13284:    docuname: username or courseid of destination for the file
                   13285:    docudom: domain of user/course of destination for the file
                   13286:    old: current file name (including any subdirs under userfiles)
                   13287:    new: desired file name (including any subdirs under userfiles)
                   13288: 
                   13289: =item *
                   13290: 
                   13291: mkdiruserfile(): creates a directory is a userfiles dir
                   13292: 
                   13293:   Args:
                   13294:    docuname: username or courseid of destination for the file
                   13295:    docudom: domain of user/course of destination for the file
                   13296:    dir: dir to create (including any subdirs under userfiles)
                   13297: 
                   13298: =item *
                   13299: 
                   13300: removeuserfile(): removes a file that exists in userfiles
                   13301: 
                   13302:   Args:
                   13303:    docuname: username or courseid of destination for the file
                   13304:    docudom: domain of user/course of destination for the file
                   13305:    fname: filname to delete (including any subdirs under userfiles)
                   13306: 
                   13307: =item *
                   13308: 
                   13309: removeuploadedurl(): convience function for removeuserfile()
                   13310: 
                   13311:   Args:
                   13312:    url:  a full /uploaded/... url to delete
                   13313: 
1.747     albertel 13314: =item * 
                   13315: 
                   13316: get_portfile_permissions():
                   13317:   Args:
                   13318:     domain: domain of user or course contain the portfolio files
                   13319:     user: name of user or num of course contain the portfolio files
                   13320:   Returns:
                   13321:     hashref of a dump of the proper file_permissions.db
                   13322:    
                   13323: 
                   13324: =item * 
                   13325: 
                   13326: get_access_controls():
                   13327: 
                   13328: Args:
                   13329:   current_permissions: the hash ref returned from get_portfile_permissions()
                   13330:   group: (optional) the group you want the files associated with
                   13331:   file: (optional) the file you want access info on
                   13332: 
                   13333: Returns:
1.749     raeburn  13334:     a hash (keys are file names) of hashes containing
                   13335:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   13336:         values are XML containing access control settings (see below) 
1.747     albertel 13337: 
                   13338: Internal notes:
                   13339: 
1.749     raeburn  13340:  access controls are stored in file_permissions.db as key=value pairs.
                   13341:     key -> path to file/file_name\0uniqueID:scope_end_start
                   13342:         where scope -> public,guest,course,group,domains or users.
                   13343:               end -> UNIX time for end of access (0 -> no end date)
                   13344:               start -> UNIX time for start of access
                   13345: 
                   13346:     value -> XML description of access control
                   13347:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   13348:             <start></start>
                   13349:             <end></end>
                   13350: 
                   13351:             <password></password>  for scope type = guest
                   13352: 
                   13353:             <domain></domain>     for scope type = course or group
                   13354:             <number></number>
                   13355:             <roles id="">
                   13356:              <role></role>
                   13357:              <access></access>
                   13358:              <section></section>
                   13359:              <group></group>
                   13360:             </roles>
                   13361: 
                   13362:             <dom></dom>         for scope type = domains
                   13363: 
                   13364:             <users>             for scope type = users
                   13365:              <user>
                   13366:               <uname></uname>
                   13367:               <udom></udom>
                   13368:              </user>
                   13369:             </users>
                   13370:            </scope> 
                   13371:               
                   13372:  Access data is also aggregated for each file in an additional key=value pair:
                   13373:  key -> path to file/file_name\0accesscontrol 
                   13374:  value -> reference to hash
                   13375:           hash contains key = value pairs
                   13376:           where key = uniqueID:scope_end_start
                   13377:                 value = UNIX time record was last updated
                   13378: 
                   13379:           Used to improve speed of look-ups of access controls for each file.  
                   13380:  
                   13381:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   13382: 
1.1172.2.13  raeburn  13383: =item *
                   13384: 
1.749     raeburn  13385: modify_access_controls():
                   13386: 
                   13387: Modifies access controls for a portfolio file
                   13388: Args
                   13389: 1. file name
                   13390: 2. reference to hash of required changes,
                   13391: 3. domain
                   13392: 4. username
                   13393:   where domain,username are the domain of the portfolio owner 
                   13394:   (either a user or a course) 
                   13395: 
                   13396: Returns:
                   13397: 1. result of additions or updates ('ok' or 'error', with error message). 
                   13398: 2. result of deletions ('ok' or 'error', with error message).
                   13399: 3. reference to hash of any new or updated access controls.
                   13400: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   13401:    key = integer (inbound ID)
1.1172.2.13  raeburn  13402:    value = uniqueID
                   13403: 
                   13404: =item *
                   13405: 
                   13406: get_timebased_id():
                   13407: 
                   13408: Attempts to get a unique timestamp-based suffix for use with items added to a
                   13409: course via the Course Editor (e.g., folders, composite pages,
                   13410: group bulletin boards).
                   13411: 
                   13412: Args: (first three required; six others optional)
                   13413: 
                   13414: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   13415:    docssequence, or name of group
                   13416: 
                   13417: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   13418:    e.g., num, boardids
                   13419: 
                   13420: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   13421:    file will be named nohist_namespace.db
                   13422: 
                   13423: 4. cdom: domain of course; default is current course domain from %env
                   13424: 
                   13425: 5. cnum: course number; default is current course number from %env
                   13426: 
                   13427: 6. idtype: set to concat if an additional digit is to be appended to the
                   13428:    unix timestamp to form the suffix, if the plain timestamp is already
                   13429:    in use.  Default is to not do this, but simply increment the unix
                   13430:    timestamp by 1 until a unique key is obtained.
                   13431: 
                   13432: 7. who: holder of locking key; defaults to user:domain for user.
                   13433: 
                   13434: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   13435:    retrying); default is 3.
                   13436: 
                   13437: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   13438: 
                   13439: Returns:
                   13440: 
                   13441: 1. suffix obtained (numeric)
                   13442: 
                   13443: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   13444: 
                   13445: 3. error: contains (localized) error message if an error occurred.
                   13446: 
1.747     albertel 13447: 
1.608     albertel 13448: =back
                   13449: 
1.243     albertel 13450: =head2 HTTP Helper Routines
                   13451: 
                   13452: =over 4
                   13453: 
1.191     harris41 13454: =item *
                   13455: 
                   13456: escape() : unpack non-word characters into CGI-compatible hex codes
                   13457: 
                   13458: =item *
                   13459: 
                   13460: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   13461: 
1.243     albertel 13462: =back
                   13463: 
                   13464: =head1 PRIVATE SUBROUTINES
                   13465: 
                   13466: =head2 Underlying communication routines (Shouldn't call)
                   13467: 
                   13468: =over 4
                   13469: 
                   13470: =item *
                   13471: 
                   13472: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   13473: 
                   13474: =item *
                   13475: 
                   13476: reply() : uses subreply to send a message to remote machine, logs all failures
                   13477: 
                   13478: =item *
                   13479: 
                   13480: critical() : passes a critical message to another server; if cannot
                   13481: get through then place message in connection buffer directory and
                   13482: returns con_delayed, if incapable of saving message, returns
                   13483: con_failed
                   13484: 
                   13485: =item *
                   13486: 
                   13487: reconlonc() : tries to reconnect lonc client processes.
                   13488: 
                   13489: =back
                   13490: 
                   13491: =head2 Resource Access Logging
                   13492: 
                   13493: =over 4
                   13494: 
                   13495: =item *
                   13496: 
                   13497: flushcourselogs() : flush (save) buffer logs and access logs
                   13498: 
                   13499: =item *
                   13500: 
                   13501: courselog($what) : save message for course in hash
                   13502: 
                   13503: =item *
                   13504: 
                   13505: courseacclog($what) : save message for course using &courselog().  Perform
                   13506: special processing for specific resource types (problems, exams, quizzes, etc).
                   13507: 
1.191     harris41 13508: =item *
                   13509: 
                   13510: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   13511: as a PerlChildExitHandler
1.243     albertel 13512: 
                   13513: =back
                   13514: 
                   13515: =head2 Other
                   13516: 
                   13517: =over 4
                   13518: 
                   13519: =item *
                   13520: 
                   13521: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 13522: 
                   13523: =back
                   13524: 
                   13525: =cut
1.877     foxr     13526: 

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